Skip to content

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

Simplify feed export tests that define their own item spider. (#8275)

Andrey Rakhmatullinef34abf3072f
diff --git a/tests/test_feedexport.py b/tests/test_feedexport.py
index cce00dea8..02afa3e47 100644
--- a/tests/test_feedexport.py
+++ b/tests/test_feedexport.py
@@ -33,11 +33,19 @@ from scrapy.utils.test import get_crawler
from tests.spiders import ItemSpider
from tests.utils.bases.feedexport import TestFeedExportBase
from tests.utils.decorators import coroutine_test, inline_callbacks_test
-from tests.utils.feedexport import MyItem, MyItem2, path_to_url, printf_escape
+from tests.utils.feedexport import (
+ MyItem,
+ MyItem2,
+ crawl_items,
+ path_to_url,
+ printf_escape,
+)
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Iterable
+ from tests.mockserver.http import MockServer
+
class FromCrawlerMixin:
init_with_crawler = False
@@ -381,25 +389,19 @@ class TestFeedExport(TestFeedExportBase):
await self.assertExported(items, header, rows)
@coroutine_test
- async def test_pathlib_uri_with_placeholders(self):
- feed_dir = Path(self.temp_dir, "pathlib_placeholders")
+ async def test_pathlib_uri_with_placeholders(
+ self, mockserver: MockServer, tmp_path: Path
+ ) -> None:
+ feed_dir = tmp_path / "pathlib_placeholders"
feed_dir.mkdir()
items = [MyItem({"foo": "bar1", "egg": "spam1"})]
- class TestSpider(scrapy.Spider):
- name = "testspider"
-
- def parse(self, response):
- yield from items
-
- TestSpider.start_urls = [self.mockserver.url("/")]
settings = {
"FEEDS": {
feed_dir / "%(time)s.json": {"format": "json"},
},
}
- crawler = get_crawler(TestSpider, settings)
- await crawler.crawl_async()
+ await crawl_items(mockserver, items, settings)
files = list(feed_dir.iterdir())
assert len(files) == 1
@@ -407,58 +409,46 @@ class TestFeedExport(TestFeedExportBase):
assert files[0].suffix == ".json"
@coroutine_test
- async def test_pathlib_uri_with_spaces_and_unicode(self):
+ async def test_pathlib_uri_with_spaces_and_unicode(
+ self, mockserver: MockServer, tmp_path: Path
+ ) -> None:
# A pathlib.Path key with spaces and non-ASCII characters must be kept
# verbatim (not percent-encoded), while %()s placeholders are still
# substituted. %(name)s resolves to the spider name deterministically,
# so the resulting file name can be asserted exactly.
- feed_dir = Path(self.temp_dir, "pathlib_spaces_unicode")
+ feed_dir = tmp_path / "pathlib_spaces_unicode"
feed_dir.mkdir()
items = [MyItem({"foo": "bar1", "egg": "spam1"})]
- class TestSpider(scrapy.Spider):
- name = "testspider"
-
- def parse(self, response):
- yield from items
-
- TestSpider.start_urls = [self.mockserver.url("/")]
settings = {
"FEEDS": {
feed_dir / "out %(name)s ünïcode.json": {"format": "json"},
},
}
- crawler = get_crawler(TestSpider, settings)
- await crawler.crawl_async()
+ await crawl_items(mockserver, items, settings)
files = list(feed_dir.iterdir())
assert len(files) == 1
assert files[0].name == "out testspider ünïcode.json"
@coroutine_test
- async def test_str_uri_with_percent_encoding_and_placeholder(self):
+ async def test_str_uri_with_percent_encoding_and_placeholder(
+ self, mockserver: MockServer, tmp_path: Path
+ ) -> None:
# A percent-encoded string URI (e.g. %20 for a space) must reach
# storage verbatim rather than being misinterpreted as a printf
# directive, while %()s placeholders are still substituted. See #6425
# and #5794.
- feed_dir = Path(self.temp_dir, "dir with spaces")
+ feed_dir = tmp_path / "dir with spaces"
feed_dir.mkdir()
items = [MyItem({"foo": "bar1", "egg": "spam1"})]
- class TestSpider(scrapy.Spider):
- name = "testspider"
-
- def parse(self, response):
- yield from items
-
- TestSpider.start_urls = [self.mockserver.url("/")]
settings = {
"FEEDS": {
f"{feed_dir.as_uri()}/%(time)s.json": {"format": "json"},
},
}
- crawler = get_crawler(TestSpider, settings)
- await crawler.crawl_async()
+ await crawl_items(mockserver, items, settings)
files = list(feed_dir.iterdir())
assert len(files) == 1
diff --git a/tests/test_feedexport_batch.py b/tests/test_feedexport_batch.py
index 9c522f699..43550d7a8 100644
--- a/tests/test_feedexport_batch.py
+++ b/tests/test_feedexport_batch.py
@@ -24,11 +24,13 @@ from scrapy.utils.test import get_crawler
from tests.spiders import ItemSpider
from tests.utils.bases.feedexport import TestFeedExportBase
from tests.utils.decorators import coroutine_test, inline_callbacks_test
-from tests.utils.feedexport import MyItem
+from tests.utils.feedexport import MyItem, crawl_items
if TYPE_CHECKING:
from os import PathLike
+ from tests.mockserver.http import MockServer
+
def build_url(path: str | PathLike[str]) -> str:
path_str = str(path)
@@ -454,8 +456,8 @@ class TestBatchDeliveries(TestFeedExportBase):
assert crawler.stats.get_value("feedexport/success_count/FileFeedStorage") == 12
@pytest.mark.requires_boto3
- @inline_callbacks_test
- def test_s3_export(self):
+ @coroutine_test
+ async def test_s3_export(self, mockserver: MockServer) -> None:
bucket = "mybucket"
items = [
MyItem({"foo": "bar1", "egg": "spam1"}),
@@ -507,15 +509,7 @@ class TestBatchDeliveries(TestFeedExportBase):
},
}
- class TestSpider(scrapy.Spider):
- name = "testspider"
-
- def parse(self, response):
- yield from items
-
- TestSpider.start_urls = [self.mockserver.url("/")]
- crawler = get_crawler(TestSpider, settings)
- yield crawler.crawl()
+ crawler = await crawl_items(mockserver, items, settings)
assert len(CustomS3FeedStorage.stubs) == len(items)
for stub in CustomS3FeedStorage.stubs:
diff --git a/tests/utils/feedexport.py b/tests/utils/feedexport.py
index 515082217..9c5e5bc9d 100644
--- a/tests/utils/feedexport.py
+++ b/tests/utils/feedexport.py
@@ -1,14 +1,19 @@
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from urllib.parse import urljoin
from urllib.request import pathname2url
-from scrapy import Field, Item
+from scrapy import Field, Item, Spider
+from scrapy.utils.test import get_crawler
if TYPE_CHECKING:
+ from collections.abc import Iterable
from pathlib import Path
+ from scrapy.crawler import Crawler
+ from tests.mockserver.http import MockServer
+
def path_to_url(path: str | Path) -> str:
return urljoin("file:", pathname2url(str(path)))
@@ -27,3 +32,21 @@ class MyItem(Item):
class MyItem2(Item):
foo = Field()
hello = Field()
+
+
+async def crawl_items(
+ mockserver: MockServer, items: Iterable[Any], settings: dict[str, Any]
+) -> Crawler:
+ """Run a spider that yields *items* from a single response with
+ *settings*, and return its crawler."""
+
+ class TestSpider(Spider):
+ name = "testspider"
+ start_urls = [mockserver.url("/")]
+
+ def parse(self, response):
+ yield from items
+
+ crawler = get_crawler(TestSpider, settings)
+ await crawler.crawl_async()
+ return crawler