Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Use AsyncCrawlerProcess in commands. (#6845)

Andrey Rakhmatullin3aa5e757871c
diff --git a/docs/news.rst b/docs/news.rst
index ef3b549e7..d3e6c6774 100644
--- a/docs/news.rst
+++ b/docs/news.rst
@@ -3,6 +3,18 @@
Release notes
=============
+Scrapy VERSION (unreleased)
+---------------------------
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- If you set the :setting:`TWISTED_REACTOR` setting to a :ref:`non-asyncio
+ value <disable-asyncio>` at the :ref:`spider level <spider-settings>`, you
+ may now need to set the :setting:`FORCE_CRAWLER_PROCESS` setting to
+ ``True`` when running Scrapy via :ref:`its command-line tool
+ <topics-commands-crawlerprocess>` to avoid a reactor mismatch exception.
+
.. _release-2.13.1:
Scrapy 2.13.1 (2025-05-28)
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rst
index 6ffb8ae93..4994fe1d6 100644
--- a/docs/topics/commands.rst
+++ b/docs/topics/commands.rst
@@ -587,6 +587,44 @@ bench
Run a quick benchmark test. :ref:`benchmarking`.
+.. _topics-commands-crawlerprocess:
+
+Commands that run a crawl
+=========================
+
+Many commands need to run a crawl of some kind, running either a user-provided
+spider or a special internal one:
+
+* :command:`bench`
+* :command:`check`
+* :command:`crawl`
+* :command:`fetch`
+* :command:`parse`
+* :command:`runspider`
+* :command:`shell`
+* :command:`view`
+
+They use an internal instance of :class:`scrapy.crawler.AsyncCrawlerProcess` or
+:class:`scrapy.crawler.CrawlerProcess` for this. In most cases this detail
+shouldn't matter to the user running the command, but when the user :ref:`needs
+a non-default Twisted reactor <disable-asyncio>`, it may be important.
+
+Scrapy decides which of these two classes to use based on the value of the
+:setting:`TWISTED_REACTOR` setting. If the setting value is the default one
+(``'twisted.internet.asyncioreactor.AsyncioSelectorReactor'``),
+:class:`~scrapy.crawler.AsyncCrawlerProcess` will be used, otherwise
+:class:`~scrapy.crawler.CrawlerProcess` will be used. The :ref:`spider settings
+<spider-settings>` are not taken into account when doing this, as they are
+loaded after this decision is made. This may cause an error if the
+project-level setting is set to :ref:`the asyncio reactor <install-asyncio>`
+(:ref:`explicitly <project-settings>` or :ref:`by using the Scrapy default
+<default-settings>`) and :ref:`the setting of the spider being run
+<spider-settings>` is set to :ref:`a different one <disable-asyncio>`, because
+:class:`~scrapy.crawler.AsyncCrawlerProcess` only supports the asyncio reactor.
+In this case you should set the :setting:`FORCE_CRAWLER_PROCESS` setting to
+``True`` (at the project level or via the command line) so that Scrapy uses
+:class:`~scrapy.crawler.CrawlerProcess` which supports all reactors.
+
Custom project commands
=======================
diff --git a/docs/topics/settings.rst b/docs/topics/settings.rst
index 65f2e5ebd..2a1be5f88 100644
--- a/docs/topics/settings.rst
+++ b/docs/topics/settings.rst
@@ -1263,6 +1263,26 @@ 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:: FORCE_CRAWLER_PROCESS
+
+FORCE_CRAWLER_PROCESS
+---------------------
+
+Default: ``False``
+
+If ``False``, :ref:`Scrapy commands that need a CrawlerProcess
+<topics-commands-crawlerprocess>` will decide between using
+:class:`scrapy.crawler.AsyncCrawlerProcess` and
+:class:`scrapy.crawler.CrawlerProcess` based on the value of the
+:setting:`TWISTED_REACTOR` setting, but ignoring its value in :ref:`per-spider
+settings <spider-settings>`.
+
+If ``True``, these commands will always use
+:class:`~scrapy.crawler.CrawlerProcess`.
+
+Set this to ``True`` if you want to set :setting:`TWISTED_REACTOR` to a
+non-default value in :ref:`per-spider settings <spider-settings>`.
+
.. setting:: FTP_PASSIVE_MODE
FTP_PASSIVE_MODE
diff --git a/pyproject.toml b/pyproject.toml
index 02ab7858d..8ec0c1056 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -147,8 +147,10 @@ source = [
]
[tool.coverage.report]
-# https://github.com/nedbat/coveragepy/issues/831#issuecomment-517778185
-exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]
+exclude_also = [
+ "if TYPE_CHECKING:",
+ "@(abc\\.)?abstractmethod",
+]
[tool.pylint.MASTER]
persistent = "no"
diff --git a/scrapy/cmdline.py b/scrapy/cmdline.py
index 81e507a4e..3d448532b 100644
--- a/scrapy/cmdline.py
+++ b/scrapy/cmdline.py
@@ -10,11 +10,12 @@ from typing import TYPE_CHECKING
import scrapy
from scrapy.commands import BaseRunSpiderCommand, ScrapyCommand, ScrapyHelpFormatter
-from scrapy.crawler import CrawlerProcess
+from scrapy.crawler import AsyncCrawlerProcess, CrawlerProcess
from scrapy.exceptions import UsageError
from scrapy.utils.misc import walk_modules
from scrapy.utils.project import get_project_settings, inside_project
from scrapy.utils.python import garbage_collect
+from scrapy.utils.reactor import _asyncio_reactor_path
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
@@ -202,7 +203,12 @@ def execute(argv: list[str] | None = None, settings: Settings | None = None) ->
_run_print_help(parser, cmd.process_options, args, opts)
if cmd.requires_crawler_process:
- cmd.crawler_process = CrawlerProcess(settings)
+ if settings[
+ "TWISTED_REACTOR"
+ ] == _asyncio_reactor_path and not settings.getbool("FORCE_CRAWLER_PROCESS"):
+ cmd.crawler_process = AsyncCrawlerProcess(settings)
+ else:
+ cmd.crawler_process = CrawlerProcess(settings)
_run_print_help(parser, _run_command, cmd, args, opts)
sys.exit(cmd.exitcode)
diff --git a/scrapy/commands/__init__.py b/scrapy/commands/__init__.py
index 2818ead77..4ce070e6e 100644
--- a/scrapy/commands/__init__.py
+++ b/scrapy/commands/__init__.py
@@ -18,14 +18,14 @@ from scrapy.utils.conf import arglist_to_dict, feed_process_params_from_cli
if TYPE_CHECKING:
from collections.abc import Iterable
- from scrapy.crawler import Crawler, CrawlerProcess
+ from scrapy.crawler import Crawler, CrawlerProcessBase
from scrapy.settings import Settings
class ScrapyCommand:
requires_project: bool = False
requires_crawler_process: bool = True
- crawler_process: CrawlerProcess | None = None # set in scrapy.cmdline
+ crawler_process: CrawlerProcessBase | None = None # set in scrapy.cmdline
# default settings to be used for this command instead of global defaults
default_settings: dict[str, Any] = {}
diff --git a/scrapy/commands/crawl.py b/scrapy/commands/crawl.py
index 184bd5ca4..866ba9f6b 100644
--- a/scrapy/commands/crawl.py
+++ b/scrapy/commands/crawl.py
@@ -1,8 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, cast
-
-from twisted.python.failure import Failure
+from typing import TYPE_CHECKING
from scrapy.commands import BaseRunSpiderCommand
from scrapy.exceptions import UsageError
@@ -30,17 +28,7 @@ class Command(BaseRunSpiderCommand):
spname = args[0]
assert self.crawler_process
- crawl_defer = self.crawler_process.crawl(spname, **opts.spargs)
-
- if getattr(crawl_defer, "result", None) is not None and issubclass(
- cast(Failure, crawl_defer.result).type, Exception
- ):
+ self.crawler_process.crawl(spname, **opts.spargs)
+ self.crawler_process.start()
+ if self.crawler_process.bootstrap_failed:
self.exitcode = 1
- else:
- self.crawler_process.start()
-
- if self.crawler_process.bootstrap_failed or (
- hasattr(self.crawler_process, "has_exception")
- and self.crawler_process.has_exception
- ):
- self.exitcode = 1
diff --git a/scrapy/commands/fetch.py b/scrapy/commands/fetch.py
index ef6e13de2..e5eedffb5 100644
--- a/scrapy/commands/fetch.py
+++ b/scrapy/commands/fetch.py
@@ -18,8 +18,6 @@ if TYPE_CHECKING:
class Command(ScrapyCommand):
- requires_project = False
-
def syntax(self) -> str:
return "[options] <url>"
diff --git a/scrapy/commands/genspider.py b/scrapy/commands/genspider.py
index c4abfc4c9..0e90c3188 100644
--- a/scrapy/commands/genspider.py
+++ b/scrapy/commands/genspider.py
@@ -46,7 +46,6 @@ def verify_url_scheme(url: str) -> str:
class Command(ScrapyCommand):
- requires_project = False
requires_crawler_process = False
default_settings = {"LOG_ENABLED": False}
diff --git a/scrapy/commands/runspider.py b/scrapy/commands/runspider.py
index 3e826456e..eeb1303e2 100644
--- a/scrapy/commands/runspider.py
+++ b/scrapy/commands/runspider.py
@@ -30,7 +30,6 @@ def _import_file(filepath: str | PathLike[str]) -> ModuleType:
class Command(BaseRunSpiderCommand):
- requires_project = False
default_settings = {"SPIDER_LOADER_CLASS": DummySpiderLoader}
def syntax(self) -> str:
diff --git a/scrapy/commands/settings.py b/scrapy/commands/settings.py
index e63031f2d..704cc500d 100644
--- a/scrapy/commands/settings.py
+++ b/scrapy/commands/settings.py
@@ -6,7 +6,6 @@ from scrapy.settings import BaseSettings
class Command(ScrapyCommand):
- requires_project = False
requires_crawler_process = False
default_settings = {"LOG_ENABLED": False}
diff --git a/scrapy/commands/shell.py b/scrapy/commands/shell.py
index 9dabfcd9c..eedaeb263 100644
--- a/scrapy/commands/shell.py
+++ b/scrapy/commands/shell.py
@@ -22,7 +22,6 @@ if TYPE_CHECKING:
class Command(ScrapyCommand):
- requires_project = False
default_settings = {
"DUPEFILTER_CLASS": "scrapy.dupefilters.BaseDupeFilter",
"KEEP_ALIVE": True,
diff --git a/scrapy/commands/startproject.py b/scrapy/commands/startproject.py
index 323979193..8f4427580 100644
--- a/scrapy/commands/startproject.py
+++ b/scrapy/commands/startproject.py
@@ -33,7 +33,6 @@ def _make_writable(path: Path) -> None:
class Command(ScrapyCommand):
- requires_project = False
requires_crawler_process = False
default_settings = {"LOG_ENABLED": False}
diff --git a/scrapy/crawler.py b/scrapy/crawler.py
index 8e3223a5c..d6fb9972e 100644
--- a/scrapy/crawler.py
+++ b/scrapy/crawler.py
@@ -5,6 +5,7 @@ import contextlib
import logging
import pprint
import signal
+from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, TypeVar
from twisted.internet.defer import (
@@ -42,7 +43,7 @@ from scrapy.utils.reactor import (
)
if TYPE_CHECKING:
- from collections.abc import Generator, Iterable
+ from collections.abc import Awaitable, Generator, Iterable
from scrapy.logformatter import LogFormatter
from scrapy.statscollectors import StatsCollector
@@ -321,7 +322,7 @@ class Crawler:
return self._get_component(cls, self.engine.scraper.spidermw.middlewares)
-class CrawlerRunnerBase:
+class CrawlerRunnerBase(ABC):
def __init__(self, settings: dict[str, Any] | Settings | None = None):
if isinstance(settings, dict) or settings is None:
settings = Settings(settings)
@@ -364,6 +365,15 @@ class CrawlerRunnerBase:
spidercls = self.spider_loader.load(spidercls)
return Crawler(spidercls, self.settings)
+ @abstractmethod
+ def crawl(
+ self,
+ crawler_or_spidercls: type[Spider] | str | Crawler,
+ *args: Any,
+ **kwargs: Any,
+ ) -> Awaitable[None]:
+ raise NotImplementedError
+
class CrawlerRunner(CrawlerRunnerBase):
"""
@@ -560,6 +570,12 @@ class CrawlerProcessBase(CrawlerRunnerBase):
configure_logging(self.settings, install_root_handler)
log_scrapy_info(self.settings)
+ @abstractmethod
+ def start(
+ self, stop_after_crawl: bool = True, install_signal_handlers: bool = True
+ ) -> None:
+ raise NotImplementedError
+
def _signal_shutdown(self, signum: int, _: Any) -> None:
from twisted.internet import reactor
@@ -597,6 +613,7 @@ class CrawlerProcessBase(CrawlerRunnerBase):
"after", "startup", install_shutdown_handlers, self._signal_shutdown
)
+ @abstractmethod
def _stop_dfd(self) -> Deferred[Any]:
raise NotImplementedError
diff --git a/scrapy/settings/default_settings.py b/scrapy/settings/default_settings.py
index 01443fa17..4a27017a6 100644
--- a/scrapy/settings/default_settings.py
+++ b/scrapy/settings/default_settings.py
@@ -179,6 +179,8 @@ FEED_STORAGE_S3_ACL = ""
FILES_STORE_S3_ACL = "private"
FILES_STORE_GCS_ACL = ""
+FORCE_CRAWLER_PROCESS = False
+
FTP_USER = "anonymous"
FTP_PASSWORD = "guest" # noqa: S105
FTP_PASSIVE_MODE = True
diff --git a/tests/test_command_crawl.py b/tests/test_command_crawl.py
index 3d5e17977..0ab0659b2 100644
--- a/tests/test_command_crawl.py
+++ b/tests/test_command_crawl.py
@@ -30,6 +30,11 @@ class MySpider(scrapy.Spider):
"""
log = self.get_log(spider_code)
assert "[myspider] DEBUG: It works!" in log
+ assert (
+ "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor"
+ in log
+ )
+ assert "Spider closed (finished)" in log
def test_output(self):
spider_code = """
@@ -91,3 +96,23 @@ class MySpider(scrapy.Spider):
assert (
"error: Please use only one of -o/--output and -O/--overwrite-output" in log
)
+
+ def test_default_reactor(self):
+ spider_code = """
+import scrapy
+
+class MySpider(scrapy.Spider):
+ name = 'myspider'
+
+ async def start(self):
+ self.logger.debug('It works!')
+ return
+ yield
+"""
+ log = self.get_log(spider_code, args=("-s", "TWISTED_REACTOR="))
+ assert "[myspider] DEBUG: It works!" in log
+ assert (
+ "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor"
+ not in log
+ )
+ assert "Spider closed (finished)" in log
diff --git a/tests/test_command_runspider.py b/tests/test_command_runspider.py
index 664de16f8..c57c09249 100644
--- a/tests/test_command_runspider.py
+++ b/tests/test_command_runspider.py
@@ -65,8 +65,10 @@ class BadSpider(scrapy.Spider):
def test_runspider(self):
log = self.get_log(self.debug_log_spider)
assert "DEBUG: It Works!" in log
- assert "INFO: Spider opened" in log
- assert "INFO: Closing spider (finished)" in log
+ assert (
+ "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor"
+ in log
+ )
assert "INFO: Spider closed (finished)" in log
def test_run_fail_spider(self):
@@ -88,6 +90,17 @@ class BadSpider(scrapy.Spider):
assert "DEBUG: It Works!" not in log
assert "INFO: Spider opened" in log
+ def test_runspider_default_reactor(self):
+ log = self.get_log(self.debug_log_spider, args=("-s", "TWISTED_REACTOR="))
+ assert "DEBUG: It Works!" in log
+ assert (
+ "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor"
+ not in log
+ )
+ assert "INFO: Spider opened" in log
+ assert "INFO: Closing spider (finished)" in log
+ assert "INFO: Spider closed (finished)" in log
+
def test_runspider_dnscache_disabled(self):
# see https://github.com/scrapy/scrapy/issues/2811
# The spider below should not be able to connect to localhost:12345,
diff --git a/tests/test_command_shell.py b/tests/test_command_shell.py
index 0f45a7ee8..8041e7cb1 100644
--- a/tests/test_command_shell.py
+++ b/tests/test_command_shell.py
@@ -7,6 +7,7 @@ from pexpect.popen_spawn import PopenSpawn
from twisted.internet import defer
from twisted.trial import unittest
+from scrapy.utils.reactor import _asyncio_reactor_path
from tests import NON_EXISTING_RESOLVABLE, tests_datadir
from tests.mockserver import MockServer
from tests.utils.testproc import ProcessTest
@@ -132,10 +133,9 @@ class TestShellCommand(ProcessTest, SiteTest, unittest.TestCase):
@defer.inlineCallbacks
def test_shell_fetch_async(self):
- reactor_path = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
url = self.url("/html")
code = f"fetch('{url}')"
- args = ["-c", code, "--set", f"TWISTED_REACTOR={reactor_path}"]
+ args = ["-c", code, "--set", f"TWISTED_REACTOR={_asyncio_reactor_path}"]
_, _, err = yield self.execute(args, check_code=True)
assert b"RuntimeError: There is no current event loop in thread" not in err
diff --git a/tests/test_commands.py b/tests/test_commands.py
index 6e59f561d..8ca5d51e5 100644
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -20,6 +20,7 @@ from scrapy.cmdline import _pop_command_name, _print_unknown_command_msg
from scrapy.commands import ScrapyCommand, ScrapyHelpFormatter, view
from scrapy.settings import Settings
from scrapy.utils.python import to_unicode
+from scrapy.utils.reactor import _asyncio_reactor_path
from scrapy.utils.test import get_testenv
if TYPE_CHECKING:
@@ -124,6 +125,221 @@ class TestCommandBase(TestProjectBase):
self.env["SCRAPY_SETTINGS_MODULE"] = f"{self.project_name}.settings"
+class TestCommandCrawlerProcess(TestCommandBase):
+ """Test that the command uses the expected kind of *CrawlerProcess
+ and produces expected errors when needed."""
+
+ name = "crawltest"
+
+ NORMAL_MSG = "Type of self.crawler_process: <class 'scrapy.crawler.CrawlerProcess'>"
+ ASYNC_MSG = (
+ "Type of self.crawler_process: <class 'scrapy.crawler.AsyncCrawlerProcess'>"
+ )
+
+ def setUp(self):
+ super().setUp()
+ (self.cwd / self.project_name / "commands").mkdir(exist_ok=True)
+ (self.cwd / self.project_name / "commands" / "__init__.py").touch()
+ (self.cwd / self.project_name / "commands" / f"{self.name}.py").write_text("""
+from scrapy.commands.crawl import Command
+
+class CrawlerProcessCrawlCommand(Command):
+ requires_project = True
+
+ def run(self, args, opts):
+ print(f"Type of self.crawler_process: {type(self.crawler_process)}")
+ super().run(args, opts)
+""")
+
+ self._append_settings(f"COMMANDS_MODULE = '{self.project_name}.commands'\n")
+
+ (self.cwd / self.project_name / "spiders" / "sp.py").write_text("""
+import scrapy
+
+class MySpider(scrapy.Spider):
+ name = 'sp'
+
+ custom_settings = {}
+
+ async def start(self):
+ self.logger.debug('It works!')
+ return
+ yield
+""")
+
+ (self.cwd / self.project_name / "spiders" / "aiosp.py").write_text("""
+import asyncio
+
+import scrapy
+
+class MySpider(scrapy.Spider):
+ name = 'aiosp'
+
+ custom_settings = {}
+
+ async def start(self):
+ await asyncio.sleep(0.01)
+ self.logger.debug('It works!')
+ return
+ yield
+""")
+
+ def _append_settings(self, text: str) -> None:
+ """Add text to the end of the project settings.py."""
+ with (self.cwd / self.project_name / "settings.py").open(
+ "a", encoding="utf-8"
+ ) as f:
+ f.write(text)
+
+ def _replace_custom_settings(self, spider_name: str, text: str) -> None:
+ """Replace custom_settings in the given spider file with the given text."""
+ spider_path = self.cwd / self.project_name / "spiders" / f"{spider_name}.py"
+ with spider_path.open("r+", encoding="utf-8") as f:
+ content = f.read()
+ content = content.replace(
+ "custom_settings = {}", f"custom_settings = {text}"
+ )
+ f.seek(0)
+ f.write(content)
+ f.truncate()
+
+ def _assert_spider_works(self, msg: str, *args: str) -> None:
+ """The command uses the expected *CrawlerProcess, the spider works."""
+ _, out, err = self.proc(self.name, *args)
+ assert msg in out, out
+ assert "It works!" in err, err
+ assert "Spider closed (finished)" in err, err
+
+ def _assert_spider_asyncio_fail(self, msg: str, *args: str) -> None:
+ """The command uses the expected *CrawlerProcess, the spider fails to use asyncio."""
+ _, out, err = self.proc(self.name, *args)
+ assert msg in out, out
+ assert "no running event loop" in err, err
+
+ def test_project_settings(self):
+ """The reactor is set via the project default settings (to the asyncio value).
+
+ AsyncCrawlerProcess, the asyncio reactor, both spiders work."""
+ for spider in ["sp", "aiosp"]:
+ self._assert_spider_works(self.ASYNC_MSG, spider)
+
+ def test_cmdline_asyncio(self):
+ """The reactor is set via the command line to the asyncio value.
+ AsyncCrawlerProcess, the asyncio reactor, both spiders work."""
+ for spider in ["sp", "aiosp"]:
+ self._assert_spider_works(
+ self.ASYNC_MSG, spider, "-s", f"TWISTED_REACTOR={_asyncio_reactor_path}"
+ )
+
+ def test_project_settings_explicit_asyncio(self):
+ """The reactor explicitly is set via the project settings to the asyncio value.
+
+ AsyncCrawlerProcess, the asyncio reactor, both spiders work."""
+ self._append_settings(f"TWISTED_REACTOR = '{_asyncio_reactor_path}'\n")
+
+ for spider in ["sp", "aiosp"]:
+ self._assert_spider_works(self.ASYNC_MSG, spider)
+
+ def test_cmdline_empty(self):
+ """The reactor is set via the command line to the empty value.
+
+ CrawlerProcess, the default reactor, only the normal spider works."""
+ self._assert_spider_works(self.NORMAL_MSG, "sp", "-s", "TWISTED_REACTOR=")
+ self._assert_spider_asyncio_fail(
+ self.NORMAL_MSG, "aiosp", "-s", "TWISTED_REACTOR="
+ )
+
+ def test_project_settings_empty(self):
+ """The reactor is set via the project settings to the empty value.
+
+ CrawlerProcess, the default reactor, only the normal spider works."""
+ self._append_settings("TWISTED_REACTOR = None\n")
+
+ self._assert_spider_works(self.NORMAL_MSG, "sp")
+ self._assert_spider_asyncio_fail(
+ self.NORMAL_MSG, "aiosp", "-s", "TWISTED_REACTOR="
+ )
+
+ def test_spider_settings_asyncio(self):
+ """The reactor is set via the spider settings to the asyncio value.
+
+ AsyncCrawlerProcess, the asyncio reactor, both spiders work."""
+ for spider in ["sp", "aiosp"]:
+ self._replace_custom_settings(
+ spider, f"{{'TWISTED_REACTOR': '{_asyncio_reactor_path}'}}"
+ )
+ self._assert_spider_works(self.ASYNC_MSG, spider)
+
+ def test_spider_settings_asyncio_cmdline_empty(self):
+ """The reactor is set via the spider settings to the asyncio value
+ and via command line to the empty value. The command line value takes
+ precedence so the spider settings don't matter.
+
+ CrawlerProcess, the default reactor, only the normal spider works."""
+ for spider in ["sp", "aiosp"]:
+ self._replace_custom_settings(
+ spider, f"{{'TWISTED_REACTOR': '{_asyncio_reactor_path}'}}"
+ )
+
+ self._assert_spider_works(self.NORMAL_MSG, "sp", "-s", "TWISTED_REACTOR=")
+ self._assert_spider_asyncio_fail(
+ self.NORMAL_MSG, "aiosp", "-s", "TWISTED_REACTOR="
+ )
+
+ def test_project_empty_spider_settings_asyncio(self):
+ """The reactor is set via the project settings to the empty value
+ and via the spider settings to the asyncio value. CrawlerProcess is
+ chosen based on the project settings, but the asyncio reactor is chosen
+ based on the spider settings.
+
+ CrawlerProcess, the asyncio reactor, both spiders work."""
+ self._append_settings("TWISTED_REACTOR = None\n")
+ for spider in ["sp", "aiosp"]:
+ self._replace_custom_settings(
+ spider, f"{{'TWISTED_REACTOR': '{_asyncio_reactor_path}'}}"
+ )
+ self._assert_spider_works(self.NORMAL_MSG, spider)
+
+ def test_project_asyncio_spider_settings_select(self):
+ """The reactor is set via the project settings to the asyncio value
+ and via the spider settings to the select value. AsyncCrawlerProcess
+ is chosen based on the project settings, and the conflicting reactor
+ setting in the spider settings causes an exception.
+
+ AsyncCrawlerProcess, the asyncio reactor, both spiders produce a
+ mismatched reactor exception."""
+ self._append_settings(f"TWISTED_REACTOR = '{_asyncio_reactor_path}'\n")
+ for spider in ["sp", "aiosp"]:
+ self._replace_custom_settings(
+ spider,
+ "{'TWISTED_REACTOR': 'twisted.internet.selectreactor.SelectReactor'}",
+ )
+ _, out, err = self.proc(self.name, spider)
+ assert self.ASYNC_MSG in out, out
+ assert (
+ "The installed reactor (twisted.internet.asyncioreactor.AsyncioSelectorReactor)"
+ " does not match the requested one"
+ " (twisted.internet.selectreactor.SelectReactor)"
+ ) in err, err
+
+ def test_project_asyncio_spider_settings_select_forced(self):
+ """The reactor is set via the project settings to the asyncio value
+ and via the spider settings to the select value, CrawlerProcess is
+ forced via the project settings. The reactor is chosen based on the
+ spider settings.
+
+ CrawlerProcess, the select reactor, only the normal spider works."""
+ self._append_settings("FORCE_CRAWLER_PROCESS = True\n")
+ for spider in ["sp", "aiosp"]:
+ self._replace_custom_settings(
+ spider,
+ "{'TWISTED_REACTOR': 'twisted.internet.selectreactor.SelectReactor'}",
+ )
+
+ self._assert_spider_works(self.NORMAL_MSG, "sp")
+ self._assert_spider_asyncio_fail(self.NORMAL_MSG, "aiosp")
+
+
class TestMiscCommands(TestCommandBase):
def test_list(self):
assert self.call("list") == 0
diff --git a/tests/test_utils_defer.py b/tests/test_utils_defer.py
index 98962f74c..372213319 100644
--- a/tests/test_utils_defer.py
+++ b/tests/test_utils_defer.py
@@ -299,7 +299,7 @@ class TestDeferredFromCoro(unittest.TestCase):
@inlineCallbacks
def test_coroutine_asyncio(self):
async def coroutine() -> int:
- await asyncio.sleep(0)
+ await asyncio.sleep(0.01)
return 42
result = deferred_from_coro(coroutine())
@@ -379,7 +379,7 @@ class TestDeferredToFuture(unittest.TestCase):
@deferred_f_from_coro_f
async def test_wrapped_coroutine_asyncio(self):
async def c_f() -> int:
- await asyncio.sleep(0)
+ await asyncio.sleep(0.01)
return 42
d = deferred_from_coro(c_f())
@@ -414,7 +414,7 @@ class TestMaybeDeferredToFutureAsyncio(unittest.TestCase):
@deferred_f_from_coro_f
async def test_wrapped_coroutine_asyncio(self):
async def c_f() -> int:
- await asyncio.sleep(0)
+ await asyncio.sleep(0.01)
return 42
d = deferred_from_coro(c_f())