Spider Contracts
Testing spiders can get particularly annoying, and while nothing prevents you from writing unit tests, the task gets cumbersome quickly. Scrapy offers an integrated way of testing your spiders by the means of contracts.
Changed in version 2.19.0: Added support for callbacks defined with async def, including
asynchronous generators.
This allows you to test each callback of your spider by hardcoding a sample URL
and checking various constraints for how the callback processes the response.
Each contract is prefixed with an @ and included in the docstring. See the
following example:
def parse(self, response):
"""
This function parses a sample response. Some contracts are mingled
with this docstring.
@url http://www.example.com/s?field-keywords=selfish+gene
@returns items 1 16
@returns requests 0 0
@scrapes Title Author Year Price
"""
A callback docstring can also be split into several batches of contracts, one
per paragraph separated by a blank line, and a batch may repeat @url to
check the callback against more than one sample request:
Added in version 2.20.0.
def parse(self, response):
"""
@url http://www.example.com/s?field-keywords=selfish+gene
@url http://www.example.com/s?field-keywords=hitchhikers+guide
@returns items 16 16
@url http://www.example.com/s?field-keywords=out+of+stock+item
@returns items 0 0
"""
You can use the following contracts:
Use the check command to run the contract checks. It ignores
ITEM_PIPELINES and FEEDS, since contracts check the
output of callbacks instead of sending it to item processing; use the -s
command-line option to set them back for a check run.
Changed in version 2.18.0: ITEM_PIPELINES and FEEDS are now ignored.
Custom Contracts
If you find you need more power than the built-in Scrapy contracts, you can
create and load your own contracts in the project by using the
SPIDER_CONTRACTS setting:
SPIDER_CONTRACTS = {
"myproject.contracts.ResponseCheck": 10,
"myproject.contracts.ItemValidate": 10,
}
Each contract must inherit from Contract and can
override three methods:
Raise ContractFail from
pre_process or
post_process if expectations are not met:
Here is a demo contract which checks the presence of a custom header in the response received:
from scrapy.contracts import Contract
from scrapy.exceptions import ContractFail
class HasHeaderContract(Contract):
"""Demo contract that checks the presence of a custom header:
@has_header X-CustomHeader"""
name = "has_header"
def pre_process(self, response):
for header in self.args:
if header not in response.headers:
raise ContractFail("X-CustomHeader not present")
Detecting check runs
When scrapy check is running, the SCRAPY_CHECK environment variable is
set to the true string. You can use os.environ to make any changes
to your spiders or your settings when scrapy check is used:
import os
import scrapy
class ExampleSpider(scrapy.Spider):
name = "example"
def __init__(self):
if os.environ.get("SCRAPY_CHECK"):
pass # Do some scraper adjustments when a check is running