Scrapy, a fast high-level web crawling & scraping framework for Python.
Merge branch 'master' into addons
Andrey Rakhmatullin898e3045a1af
diff --cc docs/topics/settings.rstindex afcb8dd21,3e06d84f9..9e8c30efe--- a/docs/topics/settings.rst+++ b/docs/topics/settings.rst@@@ -585,16 -964,72 +964,81 @@@ some of them need to be enabled througFor more information See the :ref:`extensions user guide <topics-extensions>`and the :ref:`list of available extensions <topics-extensions-ref>`.+.. setting:: INSTALLED_ADDONS++INSTALLED_ADDONS+----------------++Default: ``()``++A tuple containing paths to the add-ons enabled in your project. For more+information, see :ref:`topics-addons`.+ .. setting:: FEED_TEMPDIR++ FEED_TEMPDIR+ ------------++ The Feed Temp dir allows you to set a custom folder to save crawler+ temporary files before uploading with :ref:`FTP feed storage <topics-feed-storage-ftp>` and+ :ref:`Amazon S3 <topics-feed-storage-s3>`.++ .. setting:: FEED_STORAGE_GCS_ACL++ FEED_STORAGE_GCS_ACL+ --------------------++ The Access Control List (ACL) used when storing items to :ref:`Google Cloud Storage <topics-feed-storage-gcs>`.+ For more information on how to set this value, please refer to the column *JSON API* in `Google Cloud documentation <https://cloud.google.com/storage/docs/access-control/lists>`_.++ .. setting:: FTP_PASSIVE_MODE++ FTP_PASSIVE_MODE+ ----------------++ Default: ``True``++ Whether or not to use passive mode when initiating FTP transfers.++ .. reqmeta:: ftp_password+ .. setting:: FTP_PASSWORD++ FTP_PASSWORD+ ------------++ Default: ``"guest"``++ The password to use for FTP connections when there is no ``"ftp_password"``+ in ``Request`` meta.++ .. note::+ Paraphrasing `RFC 1635`_, although it is common to use either the password+ "guest" or one's e-mail address for anonymous FTP,+ some FTP servers explicitly ask for the user's e-mail address+ and will not allow login with the "guest" password.++ .. _RFC 1635: https://tools.ietf.org/html/rfc1635++ .. reqmeta:: ftp_user+ .. setting:: FTP_USER++ FTP_USER+ --------++ Default: ``"anonymous"``++ The username to use for FTP connections when there is no ``"ftp_user"``+ in ``Request`` meta.++ .. setting:: GCS_PROJECT_ID++ GCS_PROJECT_ID+ -----------------++ Default: ``None``++ The Project ID that will be used when storing data on `Google Cloud Storage`_.+.. setting:: ITEM_PIPELINESITEM_PIPELINESdiff --cc scrapy/cmdline.pyindex b7c349793,730e55350..68f166849--- a/scrapy/cmdline.py+++ b/scrapy/cmdline.py@@@ -6,17 -7,25 +7,26 @@@ import syimport pkg_resourcesimport scrapy+from scrapy.addons import AddonManager+ from scrapy.commands import BaseRunSpiderCommand, ScrapyCommand, ScrapyHelpFormatterfrom scrapy.crawler import CrawlerProcess- from scrapy.xlib import lsprofcalltree- from scrapy.commands import ScrapyCommandfrom scrapy.exceptions import UsageErrorfrom scrapy.utils.misc import walk_modules- from scrapy.utils.project import inside_project, get_project_settings- from scrapy.settings.deprecated import check_deprecated_settings+ from scrapy.utils.project import get_project_settings, inside_project+ from scrapy.utils.python import garbage_collect+++ class ScrapyArgumentParser(argparse.ArgumentParser):+ def _parse_optional(self, arg_string):+ # if starts with -: it means that is a parameter not a argument+ if arg_string[:2] == "-:":+ return None++ return super()._parse_optional(arg_string)+def _iter_command_classes(module_name):- # TODO: add `name` attribute to commands and and merge this function with+ # TODO: add `name` attribute to commands and merge this function with# scrapy.utils.spider.iter_spider_classesfor module in walk_modules(module_name):for obj in vars(module).values():@@@ -99,28 -121,16 +122,18 @@@ def execute(argv=None, settings=None)if argv is None:argv = sys.argv- # --- backwards compatibility for scrapy.conf.settings singleton ---- if settings is None and 'scrapy.conf' in sys.modules:- from scrapy import conf- if hasattr(conf, 'settings'):- settings = conf.settings- # -------------------------------------------------------------------if settings is None:settings = get_project_settings()- check_deprecated_settings(settings)-- # --- backwards compatibility for scrapy.conf.settings singleton ---- import warnings- from scrapy.exceptions import ScrapyDeprecationWarning- with warnings.catch_warnings():- warnings.simplefilter("ignore", ScrapyDeprecationWarning)- from scrapy import conf- conf.settings = settings- # ------------------------------------------------------------------+ # set EDITOR from environment if available+ try:+ editor = os.environ["EDITOR"]+ except KeyError:+ pass+ else:+ settings["EDITOR"] = editor+ addons = AddonManager()+inproject = inside_project()cmds = _get_commands_dict(settings, inproject)cmdname = _pop_command_name(argv)@@@ -134,15 -142,19 +145,19 @@@sys.exit(2)cmd = cmds[cmdname]- parser.usage = "scrapy %s %s" % (cmdname, cmd.syntax())- parser.description = cmd.long_desc()- settings.setdict(cmd.default_settings, priority='command')+ parser = ScrapyArgumentParser(+ formatter_class=ScrapyHelpFormatter,+ usage=f"scrapy {cmdname} {cmd.syntax()}",+ conflict_handler="resolve",+ description=cmd.long_desc(),+ )+ settings.setdict(cmd.default_settings, priority="command")cmd.settings = settingscmd.add_options(parser)- opts, args = parser.parse_args(args=argv[1:])+ opts, args = parser.parse_known_args(args=argv[1:])_run_print_help(parser, cmd.process_options, args, opts)- cmd.crawler_process = CrawlerProcess(settings, addons)- cmd.crawler_process = CrawlerProcess(settings)++ cmd.crawler_process = CrawlerProcess(settings, addons=addons)_run_print_help(parser, _run_command, cmd, args, opts)sys.exit(cmd.exitcode)diff --cc scrapy/crawler.pyindex 8107a50aa,256f6e2c5..5e7499f9c--- a/scrapy/crawler.py+++ b/scrapy/crawler.py@@@ -1,48 -1,87 +1,95 @@@- import six- import signal+ from __future__ import annotations+import logging+ import pprint+ import signalimport warnings+ from typing import TYPE_CHECKING, Optional, Type, Union- from twisted.internet import reactor, defer- from zope.interface.verify import verifyClass, DoesNotImplement+ from twisted.internet import defer+ from zope.interface.exceptions import DoesNotImplement+ try:+ # zope >= 5.0 only supports MultipleInvalid+ from zope.interface.exceptions import MultipleInvalid+ except ImportError:+ MultipleInvalid = None++ from zope.interface.verify import verifyClass++ from scrapy import Spider, signals+from scrapy.addons import AddonManagerfrom scrapy.core.engine import ExecutionEngine- from scrapy.resolver import CachingThreadedResolver- from scrapy.interfaces import ISpiderLoader+ from scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.extension import ExtensionManager- from scrapy.settings import Settings+ from scrapy.interfaces import ISpiderLoader+ from scrapy.logformatter import LogFormatter+ from scrapy.settings import Settings, overridden_settingsfrom scrapy.signalmanager import SignalManager- from scrapy.exceptions import ScrapyDeprecationWarning+ from scrapy.statscollectors import StatsCollector+ from scrapy.utils.log import (+ LogCounterHandler,+ configure_logging,+ get_scrapy_root_handler,+ install_scrapy_root_handler,+ log_reactor_info,+ log_scrapy_info,+ )+ from scrapy.utils.misc import create_instance, load_objectfrom scrapy.utils.ossignal import install_shutdown_handlers, signal_names- from scrapy.utils.misc import load_object- from scrapy.utils.log import LogCounterHandler, configure_logging, log_scrapy_info- from scrapy import signals+ from scrapy.utils.reactor import (+ install_reactor,+ is_asyncio_reactor_installed,+ verify_installed_asyncio_event_loop,+ verify_installed_reactor,+ )++ if TYPE_CHECKING:+ from scrapy.utils.request import RequestFingerprinter+logger = logging.getLogger(__name__)- class Crawler(object):+ class Crawler:+ def __init__(+ self,+ spidercls: Type[Spider],+ settings: Union[None, dict, Settings] = None,+ init_reactor: bool = False,++ addons=None,+ ):+ if isinstance(spidercls, Spider):+ raise ValueError("The spidercls argument must be a class, not an object")- def __init__(self, spidercls, settings=None, addons=None):if isinstance(settings, dict) or settings is None:settings = Settings(settings)- self.spidercls = spidercls- self.settings = settings.copy()+ self.spidercls: Type[Spider] = spidercls+ self.settings: Settings = settings.copy()self.spidercls.update_settings(self.settings)+ self.addons = addons if addons is not None else AddonManager()+ self.addons.load_settings(self.settings)+ self.addons.update_addons()+ self.addons.check_dependency_clashes()+ self.addons.update_settings(self.settings)+- self.signals = SignalManager(self)- self.stats = load_object(self.settings['STATS_CLASS'])(self)+ self.signals: SignalManager = SignalManager(self)++ self.stats: StatsCollector = load_object(self.settings["STATS_CLASS"])(self)- handler = LogCounterHandler(self, level=settings.get('LOG_LEVEL'))+ handler = LogCounterHandler(self, level=self.settings.get("LOG_LEVEL"))logging.root.addHandler(handler)++ d = dict(overridden_settings(self.settings))+ logger.info(+ "Overridden settings:\n%(settings)s", {"settings": pprint.pformat(d)}+ )++ if get_scrapy_root_handler() is not None:+ # scrapy root handler already installed: update it with new settings+ install_scrapy_root_handler(self.settings)# lambda is assigned to Crawler attribute because this way it is not# garbage collected after leaving __init__ scopeself.__remove_handler = lambda: logging.root.removeHandler(handler)@@@ -116,17 -167,37 +176,38 @@@ class CrawlerRunnercrawlers = property(lambda self: self._crawlers,doc="Set of :class:`crawlers <scrapy.crawler.Crawler>` started by "- ":meth:`crawl` and managed by this class."+ ":meth:`crawl` and managed by this class.",)+ @staticmethod+ def _get_spider_loader(settings):+ """Get SpiderLoader instance from settings"""+ cls_path = settings.get("SPIDER_LOADER_CLASS")+ loader_cls = load_object(cls_path)+ excs = (+ (DoesNotImplement, MultipleInvalid) if MultipleInvalid else DoesNotImplement+ )+ try:+ verifyClass(ISpiderLoader, loader_cls)+ except excs:+ warnings.warn(+ "SPIDER_LOADER_CLASS (previously named SPIDER_MANAGER_CLASS) does "+ "not fully implement scrapy.interfaces.ISpiderLoader interface. "+ "Please add all missing methods to avoid unexpected runtime errors.",+ category=ScrapyDeprecationWarning,+ stacklevel=2,+ )+ return loader_cls.from_settings(settings.frozencopy())+- def __init__(self, settings=None):+ def __init__(self, settings=None, addons=None):if isinstance(settings, dict) or settings is None:settings = Settings(settings)self.settings = settings+ self.addons = addons- self.spider_loader = _get_spider_loader(settings)+ self.spider_loader = self._get_spider_loader(settings)self._crawlers = set()self._active = set()+ self.bootstrap_failed = False@propertydef spiders(self):@@@ -188,9 -273,9 +283,9 @@@return self._create_crawler(crawler_or_spidercls)def _create_crawler(self, spidercls):- if isinstance(spidercls, six.string_types):+ if isinstance(spidercls, str):spidercls = self.spider_loader.load(spidercls)- return Crawler(spidercls, self.settings)+ return Crawler(spidercls, self.settings, self.addons)def stop(self):"""@@@ -232,17 -321,21 +331,21 @@@ class CrawlerProcess(CrawlerRunner)process. See :ref:`run-from-script` for an example."""- def __init__(self, settings=None, addons=None):- super(CrawlerProcess, self).__init__(settings, addons)- install_shutdown_handlers(self._signal_shutdown)- configure_logging(self.settings)- def __init__(self, settings=None, install_root_handler=True):- super().__init__(settings)++ def __init__(self, settings=None, install_root_handler=True, addons=None):++ super().__init__(settings, addons)+ configure_logging(self.settings, install_root_handler)log_scrapy_info(self.settings)+ self._initialized_reactor = Falsedef _signal_shutdown(self, signum, _):+ from twisted.internet import reactor+install_shutdown_handlers(self._signal_kill)signame = signal_names[signum]- logger.info("Received %(signame)s, shutting down gracefully. Send again to force ",- {'signame': signame})+ logger.info(+ "Received %(signame)s, shutting down gracefully. Send again to force ",+ {"signame": signame},+ )reactor.callFromThread(self._graceful_stop_reactor)def _signal_kill(self, signum, _):diff --cc scrapy/interfaces.pyindex 75b72899e,9a2c5f170..d8e5f9866--- a/scrapy/interfaces.py+++ b/scrapy/interfaces.py@@@ -1,7 -1,7 +1,7 @@@- import zope.interface-from zope.interface import Interface++from zope.interface import Attribute, Interface- class ISpiderLoader(zope.interface.Interface):+ class ISpiderLoader(Interface):def from_settings(settings):"""Return an instance of the class for the given settings"""@@@ -15,27 -15,3 +15,27 @@@def find_by_request(request):"""Return the list of spiders names that can handle the given request"""+++# ISpiderManager is deprecated, don't use it!+# An alias is kept for backwards compatibility.+ISpiderManager = ISpiderLoader++- class IAddon(zope.interface.Interface):++class IAddon(Interface):+ """Scrapy add-on"""+- name = zope.interface.Attribute("""Add-on name""")- version = zope.interface.Attribute("""Add-on version string (PEP440)""")++ name = Attribute("""Add-on name""")++ version = Attribute("""Add-on version string (PEP440)""")++ # XXX: Can methods be declared optional? I.e., can I enforce the signature+ # but not the existence of a method?+- #def update_addons(config, addons):++ # def update_addons(config, addons):+ # """Enables and configures other add-ons"""+- #def update_settings(config, settings):++ # def update_settings(config, settings):+ # """Modifies `settings` to enable and configure required components"""+- #def check_configuration(config, crawler):++ # def check_configuration(config, crawler):+ # """Performs post-initialization checks on fully configured `crawler`"""diff --cc scrapy/settings/__init__.pyindex be9f740eb,a3b849f7b..8de3e1d62--- a/scrapy/settings/__init__.py+++ b/scrapy/settings/__init__.py@@@ -1,23 -1,17 +1,18 @@@- import six- import jsonimport copy- import warnings- from collections import MutableMapping+ import json+ from collections.abc import MutableMappingfrom importlib import import_module+ from pprint import pformat- from scrapy.utils.deprecate import create_deprecated_class- from scrapy.exceptions import ScrapyDeprecationWarning-- from . import default_settings-+ from scrapy.settings import default_settingsSETTINGS_PRIORITIES = {- 'default': 0,- 'command': 10,- 'addon': 15,- 'project': 20,- 'spider': 30,- 'cmdline': 40,+ "default": 0,+ "command": 10,++ "addon": 15,+ "project": 20,+ "spider": 30,+ "cmdline": 40,}diff --cc scrapy/settings/default_settings.pyindex 6068a1393,260ec1701..18704a43b--- a/scrapy/settings/default_settings.py+++ b/scrapy/settings/default_settings.py@@@ -13,15 -13,14 +13,16 @@@ Scrapy developers, if you add a settin"""- import osimport sysfrom importlib import import_module- from os.path import join, abspath, dirname+ from pathlib import Path+ADDONS = {}+AJAXCRAWL_ENABLED = False+ ASYNCIO_EVENT_LOOP = None+AUTOTHROTTLE_ENABLED = FalseAUTOTHROTTLE_DEBUG = FalseAUTOTHROTTLE_MAX_DELAY = 60.0diff --cc scrapy/utils/conf.pyindex 5a5418104,3ade1d105..8d1544c68--- a/scrapy/utils/conf.py+++ b/scrapy/utils/conf.py@@@ -82,26 -99,24 +99,30 @@@ def init_env(project="default", set_syssys.path.append(projdir)-def get_config(use_closest=True):- """Get Scrapy config file as a ConfigParser"""- sources = get_sources(use_closest)+def config_from_filepath(sources):- """Create a SafeConfigParser and read in the given `sources`, which can be++ """Create a ConfigParser and read in the given `sources`, which can be+ either a filename or a list of filenames."""- cfg = SafeConfigParser()+ cfg = ConfigParser()cfg.read(sources)return cfg+def get_config(use_closest=True):- """Get Scrapy config file as a SafeConfigParser"""++ """Get Scrapy config file as a ConfigParser"""+ sources = get_sources(use_closest)+ return config_from_filepath(sources)++- def get_sources(use_closest=True):- xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or \- os.path.expanduser('~/.config')- sources = ['/etc/scrapy.cfg', r'c:\scrapy\scrapy.cfg',- xdg_config_home + '/scrapy.cfg',- os.path.expanduser('~/.scrapy.cfg')]+ def get_sources(use_closest=True) -> List[str]:+ xdg_config_home = (+ os.environ.get("XDG_CONFIG_HOME") or Path("~/.config").expanduser()+ )+ sources = [+ "/etc/scrapy.cfg",+ r"c:\scrapy\scrapy.cfg",+ str(Path(xdg_config_home) / "scrapy.cfg"),+ str(Path("~/.scrapy.cfg").expanduser()),+ ]if use_closest:sources.append(closest_scrapy_cfg())return sourcesdiff --cc scrapy/utils/misc.pyindex e55edd63e,d861c9ab6..4bf7e7e66--- a/scrapy/utils/misc.py+++ b/scrapy/utils/misc.py@@@ -56,24 -72,8 +72,24 @@@ def load_object(path: Union[str, Callabreturn obj+def load_module_or_object(path):+ """Load python module or (non-module) object from given path.++ Path can be both a Python or a file path.+ """+ try:+ return import_module(path)+ except ImportError:+ pass+ try:+ return load_object(path)+ except (ValueError, NameError, ImportError):+ pass+ raise NameError("Could not load '%s'" % path)++def walk_modules(path):- """Loads a module and all its submodules from a the given module path and+ """Loads a module and all its submodules from the given module path andreturns them. If *any* module throws an exception while importing, thatexception is thrown back.diff --cc scrapy/utils/test.pyindex 0e11ec7d1,58576903a..364cca613--- a/scrapy/utils/test.py+++ b/scrapy/utils/test.py@@@ -2,25 -2,63 +2,63 @@@This module contains some assorted functions used in tests"""+ import asyncioimport os-from importlib import import_module+ from pathlib import Path+ from posixpath import split+ from unittest import mock+from twisted.trial.unittest import SkipTest+ from scrapy.utils.boto import is_botocore_available- def assert_aws_environ():- """Asserts the current environment is suitable for running AWS testsi.- Raises SkipTest with the reason if it's not.- """- try:- import boto- except ImportError as e:- raise SkipTest(str(e))- if 'AWS_ACCESS_KEY_ID' not in os.environ:- raise SkipTest("AWS keys not found")+ def assert_gcs_environ():+ if "GCS_PROJECT_ID" not in os.environ:+ raise SkipTest("GCS_PROJECT_ID not found")+++ def skip_if_no_boto():+ if not is_botocore_available():+ raise SkipTest("missing botocore library")+++ def get_gcs_content_and_delete(bucket, path):+ from google.cloud import storage++ client = storage.Client(project=os.environ.get("GCS_PROJECT_ID"))+ bucket = client.get_bucket(bucket)+ blob = bucket.get_blob(path)+ content = blob.download_as_string()+ acl = list(blob.acl) # loads acl before it will be deleted+ bucket.delete_blob(path)+ return content, acl, blob- def get_crawler(spidercls=None, settings_dict=None, addons=None):++ def get_ftp_content_and_delete(+ path, host, port, username, password, use_active_mode=False+ ):+ from ftplib import FTP++ ftp = FTP()+ ftp.connect(host, port)+ ftp.login(username, password)+ if use_active_mode:+ ftp.set_pasv(False)+ ftp_data = []++ def buffer_data(data):+ ftp_data.append(data)++ ftp.retrbinary(f"RETR {path}", buffer_data)+ dirname, filename = split(path)+ ftp.cwd(dirname)+ ftp.delete(filename)+ return "".join(ftp_data)++-def get_crawler(spidercls=None, settings_dict=None, prevent_warnings=True):++def get_crawler(spidercls=None, settings_dict=None, prevent_warnings=True, addons=None):"""Return an unconfigured Crawler object. If settings_dict is given, itwill be used to populate the crawler settings with a project levelpriority.@@@ -28,14 -66,21 +66,21 @@@from scrapy.crawler import CrawlerRunnerfrom scrapy.spiders import Spider- runner = CrawlerRunner(settings_dict, addons)+ # Set by default settings that prevent deprecation warnings.+ settings = {}+ if prevent_warnings:+ settings["REQUEST_FINGERPRINTER_IMPLEMENTATION"] = "2.7"+ settings.update(settings_dict or {})- runner = CrawlerRunner(settings)++ runner = CrawlerRunner(settings, addons)return runner.create_crawler(spidercls or Spider)- def get_pythonpath():++ def get_pythonpath() -> str:"""Return a PYTHONPATH suitable to use in processes so that they find thisinstallation of Scrapy"""- scrapy_path = import_module('scrapy').__path__[0]- return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '')+ scrapy_path = import_module("scrapy").__path__[0]+ return str(Path(scrapy_path).parent) + os.pathsep + os.environ.get("PYTHONPATH", "")+def get_testenv():"""Return a OS environment dict suitable to fork processes that need to importdiff --cc sep/sep-021.rstindex ce500fc00,e8affa943..cb1701014--- a/sep/sep-021.rst+++ b/sep/sep-021.rst@@@ -17,31 -17,19 +17,31 @@@ Scrapy currently supports many hooks anfunctionality, but no single entry point for enabling and configuring them.Instead, the hooks are spread over:-* Spider middlewares (SPIDER_MIDDLEWARES)-* Downloader middlewares (DOWNLOADER_MIDDLEWARES)-* Downloader handlers (DOWNLOADER_HANDLERS)-* Item pipelines (ITEM_PIPELINES)-* Feed exporters and storages (FEED_EXPORTERS, FEED_STORAGES)-* Overridable components (DUPEFILTER_CLASS, STATS_CLASS, SCHEDULER, SPIDER_MANAGER_CLASS, ITEM_PROCESSOR, etc)-* Generic extensions (EXTENSIONS)-* CLI commands (COMMANDS_MODULE)--One problem of this approach is that enabling an extension often requires-modifying many settings, often in a coordinated way, which is complex and error-prone. Add-ons are meant to fix this by providing a simple mechanism for-enabling extensions.+* Spider middlewares (``SPIDER_MIDDLEWARES``)+* Downloader middlewares (``DOWNLOADER_MIDDLEWARES``)+* Downloader handlers (``DOWNLOADER_HANDLERS``)+* Item pipelines (``ITEM_PIPELINES``)+* Feed exporters and storages (``FEED_EXPORTERS``, ``FEED_STORAGES``)- * Overrideable components (``DUPEFILTER_CLASS``, ``STATS_CLASS``,++* Overridable components (``DUPEFILTER_CLASS``, ``STATS_CLASS``,+ ``SCHEDULER``, ``SPIDER_MANAGER_CLASS``, ``ITEM_PROCESSOR``, etc.)+* Generic extensions (``EXTENSIONS``)+* CLI commands (``COMMANDS_MODULE``)++This approach has several shortfalls:++* Enabling an extension often requires modifying many settings, often in a+ coordinated way, which is complex and error prone.+* Extension developers have little control over ensuring their library+ dependencies and configuration requirements are met, especially since most+ extensions never 'see' a fully-configured crawler before it starts running.+* The user is burdened with supervising potential interplay of extensions,+ especially non-included ones, ranging from setting name clashes to mutually+ excluding dependencies/configuration requirements.++*Add-ons* search to remedy these shortcomings by enhancing Scrapy's extension+management, making it easy-to-use and transparent for users while giving more+configuration control to developers.+Design goals and non-goals==========================@@@ -58,186 -46,50 +58,188 @@@ Non-goals* a way to publish, distribute or discover extensions (use pypi for that)-Managing add-ons-================+User experience: managing add-ons+=================================-Add-ons are defined in the ``scrapy.cfg`` file, inside the ``[addons]``-section.+Add-ons are enabled and configured either via Scrapy's settings, or (for add-ons+not bound to any project) in ``scrapy.cfg``.-To enable the "httpcache" addon, either shipped with Scrapy or in the Python-search path, create an entry for it in your ``scrapy.cfg``, like this::+In the settings, add-ons can be enabled by adding either their name (for+built-in add-ons), their Python path, or their file path, to a+``INSTALLED_ADDONS`` setting. If necessary, each add-on can be configured by+providing a dictionary-valued setting with the uppercase add-on name. For+example, to enable and configure the built-in ``httpcache`` add-on and enable+(without configuring) two custom add-ons, one via Python path and one via file+path, add these entries to your settings module::- [addons]- httpcache =+ INSTALLED_ADDONS = (+ 'httpcache',+ 'mymodule.filters.myfilter',+ 'mymodule/filters/otherfilter.py',+ )-You may also specify the full path to an add-on (which may be either a .py file-or a folder containing __init__.py)::+ HTTPCACHE = {+ 'ignore_http_codes': [404, 503],+ }- [addons]- mongodb_pipeline = /path/to/mongodb_pipeline.py+In ``scrapy.cfg``, add-ons are enabled and configured with one section per+add-on. The section names correspond to the entries of ``INSTALLED_ADDONS``.+The configuration from above could look like this::+ [addon:httpcache]+ ignore_http_codes = 404,503-Writing add-ons-===============+ [addon:mymodule.filters.myfilter]-Add-ons are Python modules that implement the following callbacks.+ [addon:mymodule/filters/otherfilter.py]-addon_configure-----------------Receives the Settings object and modifies it to enable the required components.-If it raises an exception, Scrapy will print it and exit.+Developer experience: writing add-ons+=====================================++Add-ons are (any) Python *objects* that implement Scrapy's *add-on interface*.+The interface is enforced through ``zope.interface``. This leaves the choice of+Python object up the developer. Examples:++* for a small pipeline, the add-on interface could be implemented in the same+ class that also implements the ``open/close_spider`` and ``process_item``+ callbacks+* for larger add-ons, or for clearer structure, the interface could be provided+ by a stand-alone module++The absolute minimum interface consists of just two attributes:++* ``NAME``: string with add-on name+* ``VERSION``: PEP-440 style version string++To be any useful, an add-on should implement at least one of the following+callback methods:++* ``update_addons()``: adds and configures other add-ons+* ``update_settings()``: sets configuration (such as default values for this+ add-on and required settings for other extensions) and enables needed+ components.+* ``check_configuration()``: receives the fully-initialized ``Crawler``+ instance before it starts running, performs additional dependency and+ configuration requirement checks++Additionally, an add-on may (and should, where appropriate) provide one or more+variables that can be used for automated detection of possible dependency+clashes:++* ``REQUIRES``: list of built-in or custom components required by this add-on,+ as PEP-440 strings+* ``MODIFIES``: list of components whose functionality is affected or replaced+ by this add-on (a custom HTTP cache should list ``httpcache`` here)+* ``PROVIDES``: list of components provided by this add-on (e.g. ``mongodb``+ for an extension that provides generic read/write access to a MongoDB+ database, releasing other components from having to provide their own+ database access methods)++update_addons()+-----------------++Called:+~~~~~~~++Shortly after initialisation of the ``Crawler`` object.++Arguments:+~~~~~~~~~~++* ``config``: configuration of this add-on+* ``addons``: the add-on manager, providing methods to add and configure add-ons++Purpose:+~~~~~~~~++* Configure and enable related add-ons, useful for 'umbrella add-ons' which+ chain-load other add-ons based on the configurationExamples:+~~~~~~~~~- ::+ .. code-block:: python- def addon_configure(settings):- settings.overrides["DOWNLOADER_MIDDLEWARES"].update(- {- "scrapy.contrib.downloadermiddleware.httpcache.HttpCacheMiddleware": 900,- }- )+ def update_addons(config, addons):- if 'httpcache' not in addons.enabled:- addons.add('httpcache', {'expiration_secs': 60})++ if "httpcache" not in addons.enabled:++ addons.add("httpcache", {"expiration_secs": 60})+- or::++or:++ .. code-block:: python- def addon_configure(settings):+ def update_addons(config, addons):- if 'otheraddon' in addons.enabled:- addons.configs['otheraddon']['some_config_name'] = True++ if "otheraddon" in addons.enabled:++ addons.configs["otheraddon"]["some_config_name"] = True++update_settings()+-----------------++Called:+~~~~~~~++Directly after the ``update_addons()`` callback of all add-ons has been called.++Arguments:+~~~~~~~~~~++* ``config``: configuration of this add-on+* ``settings``: the crawler's ``Settings`` instance containing all project+ settings++Purpose:+~~~~~~~~++* Modify ``settings`` to enable required components+* Expose some add-on specific configuration (``config``) into the global+ settings namespace (``settings``) if necessary+* Raise exception if components can not be properly configured (e.g. on missing+ dependencies); Scrapy will print this exception *and exit* (making users+ explicitly acknowledge that the add-on does not work by forcing them to+ disable it).++Side note:+~~~~~~~~~~++The ``MiddlewareManager.from_settings()`` method will receive a slight+modification to allow directly placing Python objects instead of class paths+in the middleware dict settings. This way, add-ons can place already+instantiated components into the settings. This allows keeping configuration+as local to components as possible and avoids cluttering up the global+settings namespace. Furthermore, it allows reusing components (e.g. using+two instances of the same mongodb pipeline to write to different locations).++Examples:+~~~~~~~~~++::++ def update_settings(config, settings):+ # Don't care where this module is located+ settings.set['DOWNLADER_MIDDLEWARES']({+ __name__ + '.downloadermw.coolmw': 900,+ })++ # Instantiate components to not expose settings into+ # the global namespace+ from .pipelines import MySQLPipeline+ mysqlpl = MySQLPipeline(password = config['password'])+ settings.set['ITEM_PIPELINES']({+ mysqlpl: 200,+ })++or::++ def update_settings(config, settings):+ # Assuming this class also has a process_item() method+ settings.set['ITEM_PIPELINES']({+ self: 200,+ })++or::++ def update_settings(config, settings):try:import botoexcept ImportError:diff --cc tests/test_crawl.pyindex 7358009e9,ca9084294..e353f80cb--- a/tests/test_crawl.py+++ b/tests/test_crawl.py@@@ -1,18 -1,55 +1,56 @@@import json- import socketimport logging+ import unittest+ from ipaddress import IPv4Address+ from socket import gethostbyname+ from urllib.parse import urlparse+ from pytest import markfrom testfixtures import LogCapturefrom twisted.internet import defer+ from twisted.internet.ssl import Certificate+ from twisted.python.failure import Failurefrom twisted.trial.unittest import TestCase+ from scrapy import signals+from scrapy.addons import Addon, AddonManager- from scrapy.http import Requestfrom scrapy.crawler import CrawlerRunner- from tests import mock- from tests.spiders import FollowAllSpider, DelaySpider, SimpleSpider, \- BrokenStartRequestsSpider, SingleRequestSpider, DuplicateStartRequestsSpider+ from scrapy.exceptions import StopDownload+ from scrapy.http import Request+ from scrapy.http.response import Response+ from scrapy.utils.python import to_unicode+ from scrapy.utils.test import get_crawler+ from tests import NON_EXISTING_RESOLVABLEfrom tests.mockserver import MockServer+ from tests.spiders import (+ AsyncDefAsyncioGenComplexSpider,+ AsyncDefAsyncioGenExcSpider,+ AsyncDefAsyncioGenLoopSpider,+ AsyncDefAsyncioGenSpider,+ AsyncDefAsyncioReqsReturnSpider,+ AsyncDefAsyncioReturnSingleElementSpider,+ AsyncDefAsyncioReturnSpider,+ AsyncDefAsyncioSpider,+ AsyncDefDeferredDirectSpider,+ AsyncDefDeferredMaybeWrappedSpider,+ AsyncDefDeferredWrappedSpider,+ AsyncDefSpider,+ BrokenStartRequestsSpider,+ BytesReceivedCallbackSpider,+ BytesReceivedErrbackSpider,+ CrawlSpiderWithAsyncCallback,+ CrawlSpiderWithAsyncGeneratorCallback,+ CrawlSpiderWithErrback,+ CrawlSpiderWithParseMethod,+ CrawlSpiderWithProcessRequestCallbackKeywordArguments,+ DelaySpider,+ DuplicateStartRequestsSpider,+ FollowAllSpider,+ HeadersReceivedCallbackSpider,+ HeadersReceivedErrbackSpider,+ SimpleSpider,+ SingleRequestSpider,+ )class CrawlTestCase(TestCase):@@@ -268,18 -407,296 +408,314 @@@ with multiples lineself._assert_retried(log)self.assertIn("Got response 200", str(log))+ @defer.inlineCallbacks+ def test_abort_on_addon_failed_check(self):+ class FailedCheckAddon(Addon):- name = 'FailedCheckAddon'- version = '1.0'++ name = "FailedCheckAddon"++ version = "1.0"+++ def check_configuration(self, config, crawler):+ raise ValueError+++ addonmgr = AddonManager()+ addonmgr.add(FailedCheckAddon())+ crawler = self.runner.create_crawler(SimpleSpider)+ crawler.addons = addonmgr+ # Doesn't work in 'precise' test environment:- #with self.assertRaises(ValueError):++ # with self.assertRaises(ValueError):+ # yield crawler.crawl()+ yield self.assertFailure(crawler.crawl(), ValueError)++++ class CrawlSpiderTestCase(TestCase):+ def setUp(self):+ self.mockserver = MockServer()+ self.mockserver.__enter__()++ def tearDown(self):+ self.mockserver.__exit__(None, None, None)++ @defer.inlineCallbacks+ def _run_spider(self, spider_cls):+ items = []++ def _on_item_scraped(item):+ items.append(item)++ crawler = get_crawler(spider_cls)+ crawler.signals.connect(_on_item_scraped, signals.item_scraped)+ with LogCapture() as log:+ yield crawler.crawl(+ self.mockserver.url("/status?n=200"), mockserver=self.mockserver+ )+ return log, items, crawler.stats++ @defer.inlineCallbacks+ def test_crawlspider_with_parse(self):+ crawler = get_crawler(CrawlSpiderWithParseMethod)+ with LogCapture() as log:+ yield crawler.crawl(mockserver=self.mockserver)++ self.assertIn("[parse] status 200 (foo: None)", str(log))+ self.assertIn("[parse] status 201 (foo: None)", str(log))+ self.assertIn("[parse] status 202 (foo: bar)", str(log))++ @defer.inlineCallbacks+ def test_crawlspider_with_async_callback(self):+ crawler = get_crawler(CrawlSpiderWithAsyncCallback)+ with LogCapture() as log:+ yield crawler.crawl(mockserver=self.mockserver)++ self.assertIn("[parse_async] status 200 (foo: None)", str(log))+ self.assertIn("[parse_async] status 201 (foo: None)", str(log))+ self.assertIn("[parse_async] status 202 (foo: bar)", str(log))++ @defer.inlineCallbacks+ def test_crawlspider_with_async_generator_callback(self):+ crawler = get_crawler(CrawlSpiderWithAsyncGeneratorCallback)+ with LogCapture() as log:+ yield crawler.crawl(mockserver=self.mockserver)++ self.assertIn("[parse_async_gen] status 200 (foo: None)", str(log))+ self.assertIn("[parse_async_gen] status 201 (foo: None)", str(log))+ self.assertIn("[parse_async_gen] status 202 (foo: bar)", str(log))++ @defer.inlineCallbacks+ def test_crawlspider_with_errback(self):+ crawler = get_crawler(CrawlSpiderWithErrback)+ with LogCapture() as log:+ yield crawler.crawl(mockserver=self.mockserver)++ self.assertIn("[parse] status 200 (foo: None)", str(log))+ self.assertIn("[parse] status 201 (foo: None)", str(log))+ self.assertIn("[parse] status 202 (foo: bar)", str(log))+ self.assertIn("[errback] status 404", str(log))+ self.assertIn("[errback] status 500", str(log))+ self.assertIn("[errback] status 501", str(log))++ @defer.inlineCallbacks+ def test_crawlspider_process_request_cb_kwargs(self):+ crawler = get_crawler(CrawlSpiderWithProcessRequestCallbackKeywordArguments)+ with LogCapture() as log:+ yield crawler.crawl(mockserver=self.mockserver)++ self.assertIn("[parse] status 200 (foo: process_request)", str(log))+ self.assertIn("[parse] status 201 (foo: process_request)", str(log))+ self.assertIn("[parse] status 202 (foo: bar)", str(log))++ @defer.inlineCallbacks+ def test_async_def_parse(self):+ crawler = get_crawler(AsyncDefSpider)+ with LogCapture() as log:+ yield crawler.crawl(+ self.mockserver.url("/status?n=200"), mockserver=self.mockserver+ )+ self.assertIn("Got response 200", str(log))++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncio_parse(self):+ crawler = get_crawler(+ AsyncDefAsyncioSpider,+ {+ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor"+ },+ )+ with LogCapture() as log:+ yield crawler.crawl(+ self.mockserver.url("/status?n=200"), mockserver=self.mockserver+ )+ self.assertIn("Got response 200", str(log))++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncio_parse_items_list(self):+ log, items, _ = yield self._run_spider(AsyncDefAsyncioReturnSpider)+ self.assertIn("Got response 200", str(log))+ self.assertIn({"id": 1}, items)+ self.assertIn({"id": 2}, items)++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncio_parse_items_single_element(self):+ items = []++ def _on_item_scraped(item):+ items.append(item)++ crawler = get_crawler(AsyncDefAsyncioReturnSingleElementSpider)+ crawler.signals.connect(_on_item_scraped, signals.item_scraped)+ with LogCapture() as log:+ yield crawler.crawl(+ self.mockserver.url("/status?n=200"), mockserver=self.mockserver+ )+ self.assertIn("Got response 200", str(log))+ self.assertIn({"foo": 42}, items)++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncgen_parse(self):+ log, _, stats = yield self._run_spider(AsyncDefAsyncioGenSpider)+ self.assertIn("Got response 200", str(log))+ itemcount = stats.get_value("item_scraped_count")+ self.assertEqual(itemcount, 1)++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncgen_parse_loop(self):+ log, items, stats = yield self._run_spider(AsyncDefAsyncioGenLoopSpider)+ self.assertIn("Got response 200", str(log))+ itemcount = stats.get_value("item_scraped_count")+ self.assertEqual(itemcount, 10)+ for i in range(10):+ self.assertIn({"foo": i}, items)++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncgen_parse_exc(self):+ log, items, stats = yield self._run_spider(AsyncDefAsyncioGenExcSpider)+ log = str(log)+ self.assertIn("Spider error processing", log)+ self.assertIn("ValueError", log)+ itemcount = stats.get_value("item_scraped_count")+ self.assertEqual(itemcount, 7)+ for i in range(7):+ self.assertIn({"foo": i}, items)++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncgen_parse_complex(self):+ _, items, stats = yield self._run_spider(AsyncDefAsyncioGenComplexSpider)+ itemcount = stats.get_value("item_scraped_count")+ self.assertEqual(itemcount, 156)+ # some random items+ for i in [1, 4, 21, 22, 207, 311]:+ self.assertIn({"index": i}, items)+ for i in [10, 30, 122]:+ self.assertIn({"index2": i}, items)++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_asyncio_parse_reqs_list(self):+ log, *_ = yield self._run_spider(AsyncDefAsyncioReqsReturnSpider)+ for req_id in range(3):+ self.assertIn(f"Got response 200, req_id {req_id}", str(log))++ @mark.only_not_asyncio()+ @defer.inlineCallbacks+ def test_async_def_deferred_direct(self):+ _, items, _ = yield self._run_spider(AsyncDefDeferredDirectSpider)+ self.assertEqual(items, [{"code": 200}])++ @mark.only_asyncio()+ @defer.inlineCallbacks+ def test_async_def_deferred_wrapped(self):+ log, items, _ = yield self._run_spider(AsyncDefDeferredWrappedSpider)+ self.assertEqual(items, [{"code": 200}])++ @defer.inlineCallbacks+ def test_async_def_deferred_maybe_wrapped(self):+ _, items, _ = yield self._run_spider(AsyncDefDeferredMaybeWrappedSpider)+ self.assertEqual(items, [{"code": 200}])++ @defer.inlineCallbacks+ def test_response_ssl_certificate_none(self):+ crawler = get_crawler(SingleRequestSpider)+ url = self.mockserver.url("/echo?body=test", is_secure=False)+ yield crawler.crawl(seed=url, mockserver=self.mockserver)+ self.assertIsNone(crawler.spider.meta["responses"][0].certificate)++ @defer.inlineCallbacks+ def test_response_ssl_certificate(self):+ crawler = get_crawler(SingleRequestSpider)+ url = self.mockserver.url("/echo?body=test", is_secure=True)+ yield crawler.crawl(seed=url, mockserver=self.mockserver)+ cert = crawler.spider.meta["responses"][0].certificate+ self.assertIsInstance(cert, Certificate)+ self.assertEqual(cert.getSubject().commonName, b"localhost")+ self.assertEqual(cert.getIssuer().commonName, b"localhost")++ @mark.xfail(reason="Responses with no body return early and contain no certificate")+ @defer.inlineCallbacks+ def test_response_ssl_certificate_empty_response(self):+ crawler = get_crawler(SingleRequestSpider)+ url = self.mockserver.url("/status?n=200", is_secure=True)+ yield crawler.crawl(seed=url, mockserver=self.mockserver)+ cert = crawler.spider.meta["responses"][0].certificate+ self.assertIsInstance(cert, Certificate)+ self.assertEqual(cert.getSubject().commonName, b"localhost")+ self.assertEqual(cert.getIssuer().commonName, b"localhost")++ @defer.inlineCallbacks+ def test_dns_server_ip_address_none(self):+ crawler = get_crawler(SingleRequestSpider)+ url = self.mockserver.url("/status?n=200")+ yield crawler.crawl(seed=url, mockserver=self.mockserver)+ ip_address = crawler.spider.meta["responses"][0].ip_address+ self.assertIsNone(ip_address)++ @defer.inlineCallbacks+ def test_dns_server_ip_address(self):+ crawler = get_crawler(SingleRequestSpider)+ url = self.mockserver.url("/echo?body=test")+ expected_netloc, _ = urlparse(url).netloc.split(":")+ yield crawler.crawl(seed=url, mockserver=self.mockserver)+ ip_address = crawler.spider.meta["responses"][0].ip_address+ self.assertIsInstance(ip_address, IPv4Address)+ self.assertEqual(str(ip_address), gethostbyname(expected_netloc))++ @defer.inlineCallbacks+ def test_bytes_received_stop_download_callback(self):+ crawler = get_crawler(BytesReceivedCallbackSpider)+ yield crawler.crawl(mockserver=self.mockserver)+ self.assertIsNone(crawler.spider.meta.get("failure"))+ self.assertIsInstance(crawler.spider.meta["response"], Response)+ self.assertEqual(+ crawler.spider.meta["response"].body,+ crawler.spider.meta.get("bytes_received"),+ )+ self.assertLess(+ len(crawler.spider.meta["response"].body),+ crawler.spider.full_response_length,+ )++ @defer.inlineCallbacks+ def test_bytes_received_stop_download_errback(self):+ crawler = get_crawler(BytesReceivedErrbackSpider)+ yield crawler.crawl(mockserver=self.mockserver)+ self.assertIsNone(crawler.spider.meta.get("response"))+ self.assertIsInstance(crawler.spider.meta["failure"], Failure)+ self.assertIsInstance(crawler.spider.meta["failure"].value, StopDownload)+ self.assertIsInstance(crawler.spider.meta["failure"].value.response, Response)+ self.assertEqual(+ crawler.spider.meta["failure"].value.response.body,+ crawler.spider.meta.get("bytes_received"),+ )+ self.assertLess(+ len(crawler.spider.meta["failure"].value.response.body),+ crawler.spider.full_response_length,+ )++ @defer.inlineCallbacks+ def test_headers_received_stop_download_callback(self):+ crawler = get_crawler(HeadersReceivedCallbackSpider)+ yield crawler.crawl(mockserver=self.mockserver)+ self.assertIsNone(crawler.spider.meta.get("failure"))+ self.assertIsInstance(crawler.spider.meta["response"], Response)+ self.assertEqual(+ crawler.spider.meta["response"].headers,+ crawler.spider.meta.get("headers_received"),+ )++ @defer.inlineCallbacks+ def test_headers_received_stop_download_errback(self):+ crawler = get_crawler(HeadersReceivedErrbackSpider)+ yield crawler.crawl(mockserver=self.mockserver)+ self.assertIsNone(crawler.spider.meta.get("response"))+ self.assertIsInstance(crawler.spider.meta["failure"], Failure)+ self.assertIsInstance(crawler.spider.meta["failure"].value, StopDownload)+ self.assertIsInstance(crawler.spider.meta["failure"].value.response, Response)+ self.assertEqual(+ crawler.spider.meta["failure"].value.response.headers,+ crawler.spider.meta.get("headers_received"),+ )diff --cc tests/test_crawler.pyindex dfad11405,706bfbaa9..5eb5344f6--- a/tests/test_crawler.py+++ b/tests/test_crawler.py@@@ -1,14 -1,30 +1,31 @@@+ import logging+ import platform+ import subprocess+ import sysimport warnings- import unittest+ from pathlib import Path++ from pkg_resources import parse_version+ from pytest import mark, raises+ from twisted import version as twisted_version+ from twisted.internet import defer+ from twisted.python.versions import Version+ from twisted.trial import unittest+ from w3lib import __version__ as w3lib_versionimport scrapy+from scrapy.addons import Addon, AddonManager- from scrapy.crawler import Crawler, CrawlerRunner, CrawlerProcess+ from scrapy.crawler import Crawler, CrawlerProcess, CrawlerRunner+ from scrapy.exceptions import ScrapyDeprecationWarning+ from scrapy.extensions import telnet+ from scrapy.extensions.throttle import AutoThrottlefrom scrapy.settings import Settings, default_settingsfrom scrapy.spiderloader import SpiderLoader- from scrapy.utils.spider import DefaultSpider+ from scrapy.utils.log import configure_logging, get_scrapy_root_handlerfrom scrapy.utils.misc import load_object- from scrapy.extensions.throttle import AutoThrottle+ from scrapy.utils.spider import DefaultSpider+ from scrapy.utils.test import get_crawler, get_testenv+ from tests.mockserver import MockServerclass BaseCrawlerTest(unittest.TestCase):@@@ -52,37 -54,20 +55,46 @@@ class CrawlerTestCase(BaseCrawlerTest)self.assertFalse(settings.frozen)self.assertTrue(crawler.settings.frozen)+ def test_populate_addons_settings(self):+ class TestAddon(Addon):- name = 'TestAddon'- version = '1.0'- addonconfig = {'TEST1': 'addon', 'TEST2': 'addon', 'TEST3': 'addon'}++ name = "TestAddon"++ version = "1.0"++++ addonconfig = {"TEST1": "addon", "TEST2": "addon", "TEST3": "addon"}+++ class TestAddon2(Addon):- name = 'testAddon2'- version = '1.0'- addonconfig2 = {'TEST': 'addon2'}++ name = "testAddon2"++ version = "1.0"++++ addonconfig2 = {"TEST": "addon2"}++ settings = Settings()- settings.set('TESTADDON_TEST1', 'project', priority='project')- settings.set('TESTADDON_TEST2', 'default', priority='default')++ settings.set("TESTADDON_TEST1", "project", priority="project")++ settings.set("TESTADDON_TEST2", "default", priority="default")+ addonmgr = AddonManager()+ addonmgr.add(TestAddon(), addonconfig)+ addonmgr.add(TestAddon2(), addonconfig2)- crawler = Crawler(DefaultSpider, settings, addonmgr)++ crawler = Crawler(DefaultSpider, settings, addons=addonmgr)+- self.assertEqual(crawler.settings['TESTADDON_TEST1'], 'project')- self.assertEqual(crawler.settings['TESTADDON_TEST2'], 'addon')- self.assertEqual(crawler.settings['TESTADDON_TEST3'], 'addon')- self.assertEqual(crawler.settings['TESTADDON2_TEST'], 'addon2')++ self.assertEqual(crawler.settings["TESTADDON_TEST1"], "project")++ self.assertEqual(crawler.settings["TESTADDON_TEST2"], "addon")++ self.assertEqual(crawler.settings["TESTADDON_TEST3"], "addon")++ self.assertEqual(crawler.settings["TESTADDON2_TEST"], "addon2")+def test_crawler_accepts_dict(self):- crawler = Crawler(DefaultSpider, {'foo': 'bar'})- self.assertEqual(crawler.settings['foo'], 'bar')- self.assertOptionIsDefault(crawler.settings, 'RETRY_ENABLED')+ crawler = get_crawler(DefaultSpider, {"foo": "bar"})+ self.assertEqual(crawler.settings["foo"], "bar")+ self.assertOptionIsDefault(crawler.settings, "RETRY_ENABLED")def test_crawler_accepts_None(self):- crawler = Crawler(DefaultSpider)- self.assertOptionIsDefault(crawler.settings, 'RETRY_ENABLED')+ with warnings.catch_warnings():+ warnings.simplefilter("ignore", ScrapyDeprecationWarning)+ crawler = Crawler(DefaultSpider)+ self.assertOptionIsDefault(crawler.settings, "RETRY_ENABLED")++ def test_crawler_rejects_spider_objects(self):+ with raises(ValueError):+ Crawler(DefaultSpider())class SpiderSettingsTestCase(unittest.TestCase):diff --cc tests/test_middleware.pyindex 4e3c67d20,00ff746ee..7ddf952f7--- a/tests/test_middleware.py+++ b/tests/test_middleware.py@@@ -91,16 -87,3 +87,17 @@@ class MiddlewareManagerTest(unittest.Temwman = TestMiddlewareManager.from_settings(settings)classes = [x.__class__ for x in mwman.middlewares]self.assertEqual(classes, [M1, M3])++ def test_instances_from_settings(self):+ settings = Settings()+ myM3 = M3()+++ class InstanceTestMiddlewareManager(MiddlewareManager):+ @classmethod+ def _get_mwlist_from_settings(cls, settings):- return [ 'tests.test_middleware.M1', M2, myM3 ]++ return ["tests.test_middleware.M1", M2, myM3]+++ mwman = InstanceTestMiddlewareManager.from_settings(settings)+ self.assertIsInstance(mwman.middlewares[0], M1)+ self.assertIsInstance(mwman.middlewares[1], M2)+ self.assertIs(mwman.middlewares[2], myM3)-diff --cc tests/test_utils_deprecate.pyindex 7a35c424b,2d9210410..eedb6f6af--- a/tests/test_utils_deprecate.py+++ b/tests/test_utils_deprecate.py@@@ -276,10 -293,6 +293,10 @@@ class UpdateClassPathTest(unittest.Testdef test_unmatched_path_stays_the_same(self):with warnings.catch_warnings(record=True) as w:- output = update_classpath('scrapy.unmatched.Path')- self.assertEqual(output, 'scrapy.unmatched.Path')+ output = update_classpath("scrapy.unmatched.Path")+ self.assertEqual(output, "scrapy.unmatched.Path")self.assertEqual(len(w), 0)++ def test_returns_nonstring(self):+ for notastring in [None, True, [1, 2, 3], object()]:+ self.assertEqual(update_classpath(notastring), notastring)diff --cc tests/test_utils_misc/__init__.pyindex 8ea8786d7,69793ee75..7932ca04c--- a/tests/test_utils_misc/__init__.py+++ b/tests/test_utils_misc/__init__.py@@@ -1,66 -1,77 +1,84 @@@- import sysimport os+ import sysimport unittest+ from pathlib import Path+ from unittest import mock++ from scrapy.item import Field, Item+ from scrapy.utils.misc import (+ arg_to_iter,+ create_instance,++ load_module_or_object,+ load_object,+ rel_has_nofollow,+ set_environ,+ walk_modules,+ )- from scrapy.item import Item, Field- from scrapy.utils.misc import (load_object, load_module_or_object, arg_to_iter,- walk_modules)+ __doctests__ = ["scrapy.utils.misc"]- __doctests__ = ['scrapy.utils.misc']class UtilsMiscTestCase(unittest.TestCase):+ def test_load_object_class(self):+ obj = load_object(Field)+ self.assertIs(obj, Field)+ obj = load_object("scrapy.item.Field")+ self.assertIs(obj, Field)- def test_load_object(self):- obj = load_object('scrapy.utils.misc.load_object')+ def test_load_object_function(self):+ obj = load_object(load_object)self.assertIs(obj, load_object)- not_a_string = int(1000)- self.assertIs(load_object(not_a_string), not_a_string)- self.assertRaises(ImportError, load_object, 'nomodule999.mod.function')- self.assertRaises(NameError, load_object, 'scrapy.utils.misc.load_object999')+ obj = load_object("scrapy.utils.misc.load_object")+ self.assertIs(obj, load_object)++ def test_load_object_exceptions(self):+ self.assertRaises(ImportError, load_object, "nomodule999.mod.function")+ self.assertRaises(NameError, load_object, "scrapy.utils.misc.load_object999")+ self.assertRaises(TypeError, load_object, {})+ def test_load_module_or_object(self):- testmod = load_module_or_object(__name__ + '.testmod')- self.assertTrue(hasattr(testmod, 'TESTVAR'))- obj = load_object('scrapy.utils.misc.load_object')++ testmod = load_module_or_object(__name__ + ".testmod")++ self.assertTrue(hasattr(testmod, "TESTVAR"))++ obj = load_object("scrapy.utils.misc.load_object")+ self.assertIs(obj, load_object)+def test_walk_modules(self):- mods = walk_modules('tests.test_utils_misc.test_walk_modules')+ mods = walk_modules("tests.test_utils_misc.test_walk_modules")expected = [- 'tests.test_utils_misc.test_walk_modules',- 'tests.test_utils_misc.test_walk_modules.mod',- 'tests.test_utils_misc.test_walk_modules.mod.mod0',- 'tests.test_utils_misc.test_walk_modules.mod1',+ "tests.test_utils_misc.test_walk_modules",+ "tests.test_utils_misc.test_walk_modules.mod",+ "tests.test_utils_misc.test_walk_modules.mod.mod0",+ "tests.test_utils_misc.test_walk_modules.mod1",]- self.assertEquals(set([m.__name__ for m in mods]), set(expected))+ self.assertEqual({m.__name__ for m in mods}, set(expected))- mods = walk_modules('tests.test_utils_misc.test_walk_modules.mod')+ mods = walk_modules("tests.test_utils_misc.test_walk_modules.mod")expected = [- 'tests.test_utils_misc.test_walk_modules.mod',- 'tests.test_utils_misc.test_walk_modules.mod.mod0',+ "tests.test_utils_misc.test_walk_modules.mod",+ "tests.test_utils_misc.test_walk_modules.mod.mod0",]- self.assertEquals(set([m.__name__ for m in mods]), set(expected))+ self.assertEqual({m.__name__ for m in mods}, set(expected))- mods = walk_modules('tests.test_utils_misc.test_walk_modules.mod1')+ mods = walk_modules("tests.test_utils_misc.test_walk_modules.mod1")expected = [- 'tests.test_utils_misc.test_walk_modules.mod1',+ "tests.test_utils_misc.test_walk_modules.mod1",]- self.assertEquals(set([m.__name__ for m in mods]), set(expected))+ self.assertEqual({m.__name__ for m in mods}, set(expected))- self.assertRaises(ImportError, walk_modules, 'nomodule999')+ self.assertRaises(ImportError, walk_modules, "nomodule999")def test_walk_modules_egg(self):- egg = os.path.join(os.path.dirname(__file__), 'test.egg')+ egg = str(Path(__file__).parent / "test.egg")sys.path.append(egg)try:- mods = walk_modules('testegg')+ mods = walk_modules("testegg")expected = [- 'testegg.spiders',- 'testegg.spiders.a',- 'testegg.spiders.b',- 'testegg'+ "testegg.spiders",+ "testegg.spiders.a",+ "testegg.spiders.b",+ "testegg",]- self.assertEquals(set([m.__name__ for m in mods]), set(expected))+ self.assertEqual({m.__name__ for m in mods}, set(expected))finally:sys.path.remove(egg)