Skip to content

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

Split feedexport tests into more files. (#8300)

Andrey Rakhmatullin3fdc64673828
diff --git a/tests/test_feedexport.py b/tests/test_feedexport.py
index 0b0522ec6..e09e2800b 100644
--- a/tests/test_feedexport.py
+++ b/tests/test_feedexport.py
@@ -1,38 +1,21 @@
from __future__ import annotations
-import json
import logging
import tempfile
-from logging import getLogger
from pathlib import Path
-from typing import IO, TYPE_CHECKING, Any
-from unittest import mock
+from typing import TYPE_CHECKING, Any
import pytest
-from w3lib.url import file_uri_to_path
import scrapy
from scrapy import signals
from scrapy.exceptions import NotConfigured
-from scrapy.exporters import CsvItemExporter, JsonItemExporter
-from scrapy.extensions.feedexport import (
- BlockingFeedStorage,
- FeedExporter,
- FeedSlot,
- FileFeedStorage,
- ItemFilter,
- apply_uri_params,
-)
+from scrapy.exporters import CsvItemExporter
+from scrapy.extensions.feedexport import FeedExporter, FileFeedStorage
from scrapy.utils.misc import build_from_crawler
from scrapy.utils.test import get_crawler
-from tests.spiders import ItemSpider
from tests.utils.decorators import coroutine_test
from tests.utils.feedexport import (
- PARSERS,
- MyItem,
- MyItem2,
- crawl_items,
- csv_header,
export_by_format,
path_to_url,
printf_escape,
@@ -40,7 +23,7 @@ from tests.utils.feedexport import (
)
if TYPE_CHECKING:
- from collections.abc import Awaitable, Callable, Iterable
+ from collections.abc import Awaitable, Callable
from tests.mockserver.http import MockServer
@@ -65,1213 +48,30 @@ class FromCrawlerFileFeedStorage(FileFeedStorage, FromCrawlerMixin):
return cls(*args, feed_options=feed_options, **kwargs)
-class DummyBlockingFeedStorage(BlockingFeedStorage):
- def __init__(self, uri, *args, feed_options=None):
- self.path = Path(file_uri_to_path(uri))
-
- def _store_in_thread(self, file):
- dirname = self.path.parent
- if dirname and not dirname.exists():
- dirname.mkdir(parents=True)
- with self.path.open("ab") as output_file:
- output_file.write(file.read())
-
- file.close()
-
-
-class FailingBlockingFeedStorage(DummyBlockingFeedStorage):
- def _store_in_thread(self, file):
- file.close()
- raise OSError("Cannot store")
-
-
-class LogOnStoreFileStorage:
- """
- This storage logs inside `store` method.
- It can be used to make sure `store` method is invoked.
- """
-
- def __init__(self, uri, feed_options=None):
- self.path = file_uri_to_path(uri)
- self.logger = getLogger()
-
- def open(self, spider):
- return tempfile.NamedTemporaryFile(prefix="feed-")
-
- def store(self, file):
- self.logger.info("Storage.store is called")
- file.close()
-
-
-class InstrumentedFeedSlot(FeedSlot):
- """Instrumented FeedSlot subclass for keeping track of calls to
- start_exporting and finish_exporting."""
-
- update_listener: Callable[[str], None]
-
- async def start_exporting(self):
- self.update_listener("start")
- await super().start_exporting()
-
- async def finish_exporting(self):
- self.update_listener("finish")
- await super().finish_exporting()
-
- @classmethod
- def subscribe__listener(cls, listener: IsExportingListener) -> None:
- cls.update_listener = listener.update
-
-
-class IsExportingListener:
- """When subscribed to InstrumentedFeedSlot, keeps track of when
- a call to start_exporting has been made without a closing call to
- finish_exporting and when a call to finish_exporting has been made
- before a call to start_exporting."""
-
- def __init__(self) -> None:
- self.start_without_finish = False
- self.finish_without_start = False
-
- def update(self, method):
- if method == "start":
- self.start_without_finish = True
- elif method == "finish":
- if self.start_without_finish:
- self.start_without_finish = False
- else:
- self.finish_without_start = True
-
-
-class ExceptionJsonItemExporter(JsonItemExporter):
- """JsonItemExporter that throws an exception every time export_item is called."""
-
- def export_item(self, _):
- raise RuntimeError("foo")
-
-
-def split_foo(item):
- for value in item["foo"].split(","):
- yield {"foo": value}
-
-
-def drop_item(item):
- return []
-
-
-async def assert_exported(
- mockserver: MockServer,
- tmp_path: Path,
- fmt: str,
- items: Iterable[Any],
- header: Iterable[str],
- rows: list[dict[str, Any]],
- settings: dict[str, Any] | None = None,
+@coroutine_test
+async def test_init_exporters_storages_with_crawler(
+ mockserver: MockServer, tmp_path: Path
) -> None:
- """Check that exporting *items* as *fmt* with *settings* produces *rows*
- and, for CSV, a *header* line."""
- settings = {**(settings or {}), "FEEDS": {unique_path(tmp_path): {"format": fmt}}}
- data = (await export_by_format(mockserver, items, settings))[fmt]
- assert data is not None
- if fmt == "csv":
- assert csv_header(data) == list(header)
- assert PARSERS[fmt](data) == rows
-
-
-class TestFeedExport:
- @coroutine_test
- async def test_stats_file_success(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEEDS": {
- printf_escape(path_to_url(str(unique_path(tmp_path)))): {
- "format": "json",
- }
- },
- }
- crawler = get_crawler(ItemSpider, settings)
- await crawler.crawl_async(mockserver=mockserver)
- assert "feedexport/success_count/FileFeedStorage" in crawler.stats.get_stats()
- assert crawler.stats.get_value("feedexport/success_count/FileFeedStorage") == 1
-
- @coroutine_test
- async def test_stats_file_failed(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEEDS": {
- printf_escape(path_to_url(str(unique_path(tmp_path)))): {
- "format": "json",
- }
- },
- }
- crawler = get_crawler(ItemSpider, settings)
-
- def store(file: IO[bytes]) -> None:
- file.close()
- raise KeyError("foo")
-
- with mock.patch(
- "scrapy.extensions.feedexport.FileFeedStorage.store",
- side_effect=store,
- ):
- await crawler.crawl_async(mockserver=mockserver)
- assert "feedexport/failed_count/FileFeedStorage" in crawler.stats.get_stats()
- assert crawler.stats.get_value("feedexport/failed_count/FileFeedStorage") == 1
-
- @coroutine_test
- async def test_stats_multiple_file(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEEDS": {
- printf_escape(path_to_url(str(unique_path(tmp_path)))): {
- "format": "json",
- },
- "stdout:": {
- "format": "xml",
- },
- },
- }
- crawler = get_crawler(ItemSpider, settings)
- await crawler.crawl_async(mockserver=mockserver)
- assert "feedexport/success_count/FileFeedStorage" in crawler.stats.get_stats()
- assert "feedexport/success_count/StdoutFeedStorage" in crawler.stats.get_stats()
- assert crawler.stats.get_value("feedexport/success_count/FileFeedStorage") == 1
- assert (
- crawler.stats.get_value("feedexport/success_count/StdoutFeedStorage") == 1
- )
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- # feed exporters use field names from Item
- items = [
- MyItem({"foo": "bar1", "egg": "spam1"}),
- MyItem({"foo": "bar2", "egg": "spam2", "baz": "quux2"}),
- ]
- rows = [
- {"egg": "spam1", "foo": "bar1"},
- {"egg": "spam2", "foo": "bar2", "baz": "quux2"},
- ]
- header = MyItem.fields.keys()
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows)
-
- @coroutine_test
- 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"})]
-
- settings = {
- "FEEDS": {
- feed_dir / "%(time)s.json": {"format": "json"},
- },
- }
- await crawl_items(mockserver, items, settings)
-
- files = list(feed_dir.iterdir())
- assert len(files) == 1
- assert "%(time)s" not in files[0].name
- assert files[0].suffix == ".json"
-
- @coroutine_test
- 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 = tmp_path / "pathlib_spaces_unicode"
- feed_dir.mkdir()
- items = [MyItem({"foo": "bar1", "egg": "spam1"})]
-
- settings = {
- "FEEDS": {
- feed_dir / "out %(name)s ünïcode.json": {"format": "json"},
- },
- }
- 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, 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 = tmp_path / "dir with spaces"
- feed_dir.mkdir()
- items = [MyItem({"foo": "bar1", "egg": "spam1"})]
-
- settings = {
- "FEEDS": {
- f"{feed_dir.as_uri()}/%(time)s.json": {"format": "json"},
- },
- }
- await crawl_items(mockserver, items, settings)
-
- files = list(feed_dir.iterdir())
- assert len(files) == 1
- assert "%(time)s" not in files[0].name
- assert files[0].suffix == ".json"
-
- @coroutine_test
- async def test_export_no_items_not_store_empty(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- for fmt in ("json", "jsonlines", "xml", "csv"):
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": fmt},
- },
- "FEED_STORE_EMPTY": False,
- }
- data = await export_by_format(mockserver, [], settings)
- assert data[fmt] is None
-
- @coroutine_test
- async def test_start_finish_exporting_items(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- MyItem({"foo": "bar1", "egg": "spam1"}),
- ]
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- },
- "FEED_EXPORT_INDENT": None,
- }
-
- listener = IsExportingListener()
- InstrumentedFeedSlot.subscribe__listener(listener)
-
- with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
- await export_by_format(mockserver, items, settings)
- assert not listener.start_without_finish
- assert not listener.finish_without_start
-
- @coroutine_test
- async def test_start_finish_exporting_no_items(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items: list[Any] = []
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- },
- "FEED_EXPORT_INDENT": None,
- }
-
- listener = IsExportingListener()
- InstrumentedFeedSlot.subscribe__listener(listener)
-
- with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
- await export_by_format(mockserver, items, settings)
- assert not listener.start_without_finish
- assert not listener.finish_without_start
-
- @coroutine_test
- async def test_start_finish_exporting_items_exception(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- MyItem({"foo": "bar1", "egg": "spam1"}),
- ]
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- },
- "FEED_EXPORTERS": {"json": ExceptionJsonItemExporter},
- "FEED_EXPORT_INDENT": None,
- }
-
- listener = IsExportingListener()
- InstrumentedFeedSlot.subscribe__listener(listener)
-
- with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
- await export_by_format(mockserver, items, settings)
- assert not listener.start_without_finish
- assert not listener.finish_without_start
-
- @coroutine_test
- async def test_export_item_exception_mentions_item(
- self, caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": {None: "bar"}}]
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- },
- "FEED_EXPORTERS": {"json": ExceptionJsonItemExporter},
- }
- with caplog.at_level(logging.ERROR):
- await export_by_format(mockserver, items, settings)
- assert "RuntimeError: foo" in caplog.text
- assert "Item: {'foo': {None: 'bar'}}" in caplog.text
-
- @coroutine_test
- async def test_start_finish_exporting_no_items_exception(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items: list[Any] = []
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- },
- "FEED_EXPORTERS": {"json": ExceptionJsonItemExporter},
- "FEED_EXPORT_INDENT": None,
- }
-
- listener = IsExportingListener()
- InstrumentedFeedSlot.subscribe__listener(listener)
-
- with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
- await export_by_format(mockserver, items, settings)
- assert not listener.start_without_finish
- assert not listener.finish_without_start
-
- @coroutine_test
- async def test_export_no_items_store_empty(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- formats = (
- ("json", b"[]"),
- ("jsonlines", b""),
- ("xml", b'<?xml version="1.0" encoding="utf-8"?>\n<items></items>'),
- ("csv", b""),
- )
-
- for fmt, expctd in formats:
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": fmt},
- },
- "FEED_STORE_EMPTY": True,
- "FEED_EXPORT_INDENT": None,
- }
- data = await export_by_format(mockserver, [], settings)
- assert expctd == data[fmt]
-
- @coroutine_test
- async def test_export_no_items_multiple_feeds(
- self, caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
- ) -> None:
- """Make sure that `storage.store` is not called."""
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- unique_path(tmp_path): {"format": "xml"},
- unique_path(tmp_path): {"format": "csv"},
- },
- "FEED_STORAGES": {"file": LogOnStoreFileStorage},
- "FEED_STORE_EMPTY": False,
- }
-
- with caplog.at_level(logging.INFO):
- await export_by_format(mockserver, [], settings)
-
- assert caplog.text.count("Storage.store is called") == 0
-
- # by default, Scrapy uses fields of the first Item for CSV and
- # all fields for JSON Lines
- @pytest.mark.parametrize(
- ("fmt", "rows"),
- [
- (
- "csv",
- [
- {"egg": "spam1", "foo": "bar1"},
- {"foo": "bar2"},
- {"egg": "spam3", "foo": "bar3", "baz": "quux3"},
- {"egg": "spam4"},
- ],
- ),
- (
- "jsonlines",
- [
- {"foo": "bar1", "egg": "spam1"},
- {"hello": "world2", "foo": "bar2"},
- {"foo": "bar3", "egg": "spam3", "baz": "quux3"},
- {"hello": "world4", "egg": "spam4"},
- ],
- ),
- ],
- )
- @coroutine_test
- async def test_export_multiple_item_classes(
- self,
- fmt: str,
- rows: list[dict[str, Any]],
- mockserver: MockServer,
- tmp_path: Path,
- ) -> None:
- items = [
- MyItem({"foo": "bar1", "egg": "spam1"}),
- MyItem2({"hello": "world2", "foo": "bar2"}),
- MyItem({"foo": "bar3", "egg": "spam3", "baz": "quux3"}),
- {"hello": "world4", "egg": "spam4"},
- ]
- header = MyItem.fields.keys()
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows)
-
- @pytest.mark.parametrize("fmt", ["csv", "jsonlines"])
- @coroutine_test
- async def test_export_items_empty_field_list(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- # FEED_EXPORT_FIELDS==[] means the same as default None
- items = [{"foo": "bar"}]
- header = ["foo"]
- rows = [{"foo": "bar"}]
- settings: dict[str, Any] = {"FEED_EXPORT_FIELDS": []}
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items_field_list(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "bar"}]
- header = ["foo", "baz"]
- rows = [{"foo": "bar"}]
- settings = {"FEED_EXPORT_FIELDS": header}
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items_comma_separated_field_list(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "bar"}]
- header = ["foo", "baz"]
- rows = [{"foo": "bar"}]
- settings = {"FEED_EXPORT_FIELDS": ",".join(header)}
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items_json_field_list(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "bar"}]
- header = ["foo", "baz"]
- rows = [{"foo": "bar"}]
- settings = {"FEED_EXPORT_FIELDS": json.dumps(header)}
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items_field_names(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "bar"}]
- header = {"foo": "Foo"}
- rows = [{"Foo": "bar"}]
- settings = {"FEED_EXPORT_FIELDS": header}
- await assert_exported(
- mockserver, tmp_path, fmt, items, header.values(), rows, settings
- )
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items_dict_field_names(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "bar"}]
- header = {
- "baz": "Baz",
- "foo": "Foo",
- }
- rows = [{"Foo": "bar"}]
- settings = {"FEED_EXPORT_FIELDS": header}
- await assert_exported(
- mockserver, tmp_path, fmt, items, ["Baz", "Foo"], rows, settings
- )
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_items_json_field_names(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "bar"}]
- header = {"foo": "Foo"}
- rows = [{"Foo": "bar"}]
- settings = {"FEED_EXPORT_FIELDS": json.dumps(header)}
- await assert_exported(
- mockserver, tmp_path, fmt, items, header.values(), rows, settings
- )
-
- @coroutine_test
- async def test_export_based_on_item_classes(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- MyItem({"foo": "bar1", "egg": "spam1"}),
- MyItem2({"hello": "world2", "foo": "bar2"}),
- {"hello": "world3", "egg": "spam3"},
- ]
-
- formats = {
- "csv": b"foo,egg,baz\r\nbar1,spam1,\r\n",
- "json": b'[\n{"foo": "bar2", "hello": "world2"}\n]',
- "jsonlines": (
- b'{"foo": "bar1", "egg": "spam1"}\n{"foo": "bar2", "hello": "world2"}\n'
- ),
- "xml": (
- b'<?xml version="1.0" encoding="utf-8"?>\n<items>\n<item>'
- b"<foo>bar1</foo><egg>spam1</egg></item>\n<item><foo>"
- b"bar2</foo><hello>world2</hello></item>\n<item><hello>world3"
- b"</hello><egg>spam3</egg></item>\n</items>"
- ),
- }
-
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {
- "format": "csv",
- "item_classes": [MyItem],
- },
- unique_path(tmp_path): {
- "format": "json",
- "item_classes": [MyItem2],
- },
- unique_path(tmp_path): {
- "format": "jsonlines",
- "item_classes": [MyItem, MyItem2],
- },
- unique_path(tmp_path): {
- "format": "xml",
- },
- },
- }
-
- data = await export_by_format(mockserver, items, settings)
- for fmt, expected in formats.items():
- assert data[fmt] == expected
-
- @coroutine_test
- async def test_export_based_on_custom_filters(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- MyItem({"foo": "bar1", "egg": "spam1"}),
- MyItem2({"hello": "world2", "foo": "bar2"}),
- {"hello": "world3", "egg": "spam3"},
- ]
-
- class CustomFilter1:
- def __init__(self, feed_options):
- pass
-
- def accepts(self, item):
- return isinstance(item, MyItem)
-
- class CustomFilter2(ItemFilter):
- def accepts(self, item):
- return "foo" in item.fields
-
- class CustomFilter3(ItemFilter):
- def accepts(self, item):
- return (
- isinstance(item, tuple(self.item_classes)) and item["foo"] == "bar1" # type: ignore[index]
- )
-
- formats = {
- "json": b'[\n{"foo": "bar1", "egg": "spam1"}\n]',
- "xml": (
- b'<?xml version="1.0" encoding="utf-8"?>\n<items>\n<item>'
- b"<foo>bar1</foo><egg>spam1</egg></item>\n<item><foo>"
- b"bar2</foo><hello>world2</hello></item>\n</items>"
- ),
- "jsonlines": b'{"foo": "bar1", "egg": "spam1"}\n',
- }
-
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {
- "format": "json",
- "item_filter": CustomFilter1,
- },
- unique_path(tmp_path): {
- "format": "xml",
- "item_filter": CustomFilter2,
- },
- unique_path(tmp_path): {
- "format": "jsonlines",
- "item_classes": [MyItem, MyItem2],
- "item_filter": CustomFilter3,
- },
- },
- }
-
- data = await export_by_format(mockserver, items, settings)
- for fmt, expected in formats.items():
- assert data[fmt] == expected
-
- @coroutine_test
- async def test_export_based_on_item_processors(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- MyItem({"foo": "bar1,bar2"}),
- {"foo": "bar3"},
- ]
-
- formats = {
- "jsonlines": b'{"foo": "bar1"}\n{"foo": "bar2"}\n{"foo": "bar3"}\n',
- "json": b'[\n{"foo": "bar1"},\n{"foo": "bar2"},\n{"foo": "bar3"}\n]',
- "xml": (
- b'<?xml version="1.0" encoding="utf-8"?>\n<items>\n'
- b"<item><foo>bar1</foo></item>\n<item><foo>bar2</foo></item>\n</items>"
- ),
- "csv": b"",
- }
-
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {
- "format": "jsonlines",
- "item_processor": split_foo,
- },
- unique_path(tmp_path): {
- "format": "json",
- "item_processor": "tests.test_feedexport.split_foo",
- },
- unique_path(tmp_path): {
- "format": "xml",
- "item_classes": [MyItem],
- "item_processor": split_foo,
- },
- unique_path(tmp_path): {
- "format": "csv",
- "item_processor": drop_item,
- },
- },
- }
-
- data = await export_by_format(mockserver, items, settings)
- for fmt, expected in formats.items():
- assert data[fmt] == expected
-
- @coroutine_test
- async def test_item_processor_stats(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEEDS": {
- path_to_url(unique_path(tmp_path)): {
- "format": "jsonlines",
- "item_processor": split_foo,
- },
- },
- }
- crawler = await crawl_items(mockserver, [{"foo": "bar1,bar2"}], settings)
-
- assert crawler.stats.get_value("item_scraped_count") == 1
- assert crawler.stats.get_value("feedexport/item_count/FileFeedStorage") == 2
-
- # When dicts are used, only keys from the first row are used as
- # a header for CSV, and all fields are used for JSON Lines.
- @pytest.mark.parametrize(
- ("fmt", "rows"),
- [
- ("csv", [{"egg": "spam", "foo": "bar"}, {"egg": "spam", "foo": "bar"}]),
- (
- "jsonlines",
- [
- {"foo": "bar", "egg": "spam"},
- {"foo": "bar", "egg": "spam", "baz": "quux"},
- ],
- ),
- ],
- )
- @coroutine_test
- async def test_export_dicts(
- self,
- fmt: str,
- rows: list[dict[str, Any]],
- mockserver: MockServer,
- tmp_path: Path,
- ) -> None:
- items = [
- {"foo": "bar", "egg": "spam"},
- {"foo": "bar", "egg": "spam", "baz": "quux"},
- ]
- header = ["foo", "egg"]
- await assert_exported(mockserver, tmp_path, fmt, items, header, rows)
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_tuple(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- {"foo": "bar1", "egg": "spam1"},
- {"foo": "bar2", "egg": "spam2", "baz": "quux"},
- ]
-
- settings = {"FEED_EXPORT_FIELDS": ("foo", "baz")}
- rows = [{"foo": "bar1"}, {"foo": "bar2", "baz": "quux"}]
- await assert_exported(
- mockserver, tmp_path, fmt, items, ["foo", "baz"], rows, settings
- )
-
- @pytest.mark.parametrize("fmt", list(PARSERS))
- @coroutine_test
- async def test_export_feed_export_fields(
- self, fmt: str, mockserver: MockServer, tmp_path: Path
- ) -> None:
- # FEED_EXPORT_FIELDS option allows to order export fields
- # and to select a subset of fields to export, both for Items and dicts.
-
- for item_cls in [MyItem, dict]:
- items = [
- item_cls({"foo": "bar1", "egg": "spam1"}),
- item_cls({"foo": "bar2", "egg": "spam2", "baz": "quux2"}),
- ]
-
- # export all columns
- settings = {"FEED_EXPORT_FIELDS": "foo,baz,egg"}
- rows = [
- {"egg": "spam1", "foo": "bar1"},
- {"egg": "spam2", "foo": "bar2", "baz": "quux2"},
- ]
- await assert_exported(
- mockserver, tmp_path, fmt, items, ["foo", "baz", "egg"], rows, settings
- )
-
- # export a subset of columns
- settings = {"FEED_EXPORT_FIELDS": "egg,baz"}
- rows = [{"egg": "spam1"}, {"egg": "spam2", "baz": "quux2"}]
- await assert_exported(
- mockserver, tmp_path, fmt, items, ["egg", "baz"], rows, settings
- )
-
- @coroutine_test
- async def test_export_encoding(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "Test\xd6"}]
-
- formats = {
- "json": b'[{"foo": "Test\\u00d6"}]',
- "jsonlines": b'{"foo": "Test\\u00d6"}\n',
- "xml": (
- '<?xml version="1.0" encoding="utf-8"?>\n'
- "<items><item><foo>Test\xd6</foo></item></items>"
- ).encode(),
- "csv": "foo\r\nTest\xd6\r\n".encode(),
- }
-
- for fmt, expected in formats.items():
- settings: dict[str, Any] = {
- "FEEDS": {
- unique_path(tmp_path): {"format": fmt},
- },
- "FEED_EXPORT_INDENT": None,
- }
- data = await export_by_format(mockserver, items, settings)
- assert data[fmt] == expected
-
- formats = {
- "json": b'[{"foo": "Test\xd6"}]',
- "jsonlines": b'{"foo": "Test\xd6"}\n',
- "xml": (
- b'<?xml version="1.0" encoding="latin-1"?>\n'
- b"<items><item><foo>Test\xd6</foo></item></items>"
- ),
- "csv": b"foo\r\nTest\xd6\r\n",
- }
-
- for fmt, expected in formats.items():
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": fmt},
- },
- "FEED_EXPORT_INDENT": None,
- "FEED_EXPORT_ENCODING": "latin-1",
- }
- data = await export_by_format(mockserver, items, settings)
- assert data[fmt] == expected
-
- @coroutine_test
- async def test_export_multiple_configs(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [{"foo": "FOO", "bar": "BAR"}]
-
- formats = {
- "json": b'[\n{"bar": "BAR"}\n]',
- "xml": (
- b'<?xml version="1.0" encoding="latin-1"?>\n'
- b"<items>\n <item>\n <foo>FOO</foo>\n </item>\n</items>"
- ),
- "csv": b"bar,foo\r\nBAR,FOO\r\n",
- }
-
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {
- "format": "json",
- "indent": 0,
- "fields": ["bar"],
- "encoding": "utf-8",
- },
- unique_path(tmp_path): {
- "format": "xml",
- "indent": 2,
- "fields": ["foo"],
- "encoding": "latin-1",
- },
- unique_path(tmp_path): {
- "format": "csv",
- "indent": None,
- "fields": ["bar", "foo"],
- "encoding": "utf-8",
- },
- },
- }
-
- data = await export_by_format(mockserver, items, settings)
- for fmt, expected in formats.items():
- assert data[fmt] == expected
-
- @coroutine_test
- async def test_export_indentation(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- items = [
- {"foo": ["bar"]},
- {"key": "value"},
- ]
-
- test_cases: list[dict[str, Any]] = [
- # JSON
- {
- "format": "json",
- "indent": None,
- "expected": b'[{"foo": ["bar"]},{"key": "value"}]',
- },
- {
- "format": "json",
- "indent": -1,
- "expected": b"""[
-{"foo": ["bar"]},
-{"key": "value"}
-]""",
- },
- {
- "format": "json",
- "indent": 0,
- "expected": b"""[
-{"foo": ["bar"]},
-{"key": "value"}
-]""",
- },
- {
- "format": "json",
- "indent": 2,
- "expected": b"""[
-{
- "foo": [
- "bar"
- ]
-},
-{
- "key": "value"
-}
-]""",
- },
- {
- "format": "json",
- "indent": 4,
- "expected": b"""[
-{
- "foo": [
- "bar"
- ]
-},
-{
- "key": "value"
-}
-]""",
- },
- {
- "format": "json",
- "indent": 5,
- "expected": b"""[
-{
- "foo": [
- "bar"
- ]
-},
-{
- "key": "value"
-}
-]""",
- },
- # XML
- {
- "format": "xml",
- "indent": None,
- "expected": b"""<?xml version="1.0" encoding="utf-8"?>
-<items><item><foo><value>bar</value></foo></item><item><key>value</key></item></items>""",
- },
- {
- "format": "xml",
- "indent": -1,
- "expected": b"""<?xml version="1.0" encoding="utf-8"?>
-<items>
-<item><foo><value>bar</value></foo></item>
-<item><key>value</key></item>
-</items>""",
- },
- {
- "format": "xml",
- "indent": 0,
- "expected": b"""<?xml version="1.0" encoding="utf-8"?>
-<items>
-<item><foo><value>bar</value></foo></item>
-<item><key>value</key></item>
-</items>""",
- },
- {
- "format": "xml",
- "indent": 2,
- "expected": b"""<?xml version="1.0" encoding="utf-8"?>
-<items>
- <item>
- <foo>
- <value>bar</value>
- </foo>
- </item>
- <item>
- <key>value</key>
- </item>
-</items>""",
- },
- {
- "format": "xml",
- "indent": 4,
- "expected": b"""<?xml version="1.0" encoding="utf-8"?>
-<items>
- <item>
- <foo>
- <value>bar</value>
- </foo>
- </item>
- <item>
- <key>value</key>
- </item>
-</items>""",
- },
- {
- "format": "xml",
- "indent": 5,
- "expected": b"""<?xml version="1.0" encoding="utf-8"?>
-<items>
- <item>
- <foo>
- <value>bar</value>
- </foo>
- </item>
- <item>
- <key>value</key>
- </item>
-</items>""",
- },
- ]
-
- for row in test_cases:
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {
- "format": row["format"],
- "indent": row["indent"],
- },
- },
- }
- data = await export_by_format(mockserver, items, settings)
- assert data[row["format"]] == row["expected"]
-
- @coroutine_test
- async def test_init_exporters_storages_with_crawler(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEED_EXPORTERS": {"csv": FromCrawlerCsvItemExporter},
- "FEED_STORAGES": {"file": FromCrawlerFileFeedStorage},
- "FEEDS": {
- unique_path(tmp_path): {"format": "csv"},
- },
- }
- await export_by_format(mockserver, [], settings)
- assert FromCrawlerCsvItemExporter.init_with_crawler
- assert FromCrawlerFileFeedStorage.init_with_crawler
-
- @coroutine_test
- async def test_str_uri(self, mockserver: MockServer, tmp_path: Path) -> None:
- settings = {
- "FEED_STORE_EMPTY": True,
- "FEEDS": {str(unique_path(tmp_path)): {"format": "csv"}},
- }
- data = await export_by_format(mockserver, [], settings)
- assert data["csv"] == b""
-
- @coroutine_test
- async def test_multiple_feeds_success_logs_blocking_feed_storage(
- self, caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- unique_path(tmp_path): {"format": "xml"},
- unique_path(tmp_path): {"format": "csv"},
- },
- "FEED_STORAGES": {"file": DummyBlockingFeedStorage},
- }
- items = [
- {"foo": "bar1", "baz": ""},
- {"foo": "bar2", "baz": "quux"},
- ]
- with caplog.at_level(logging.DEBUG):
- await export_by_format(mockserver, items, settings)
-
- for fmt in ["json", "xml", "csv"]:
- assert f"Stored {fmt} feed (2 items)" in caplog.text
-
- @coroutine_test
- async def test_multiple_feeds_failing_logs_blocking_feed_storage(
- self, caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
- ) -> None:
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {"format": "json"},
- unique_path(tmp_path): {"format": "xml"},
- unique_path(tmp_path): {"format": "csv"},
- },
- "FEED_STORAGES": {"file": FailingBlockingFeedStorage},
- }
- items = [
- {"foo": "bar1", "baz": ""},
- {"foo": "bar2", "baz": "quux"},
- ]
- with caplog.at_level(logging.DEBUG):
- await export_by_format(mockserver, items, settings)
-
- for fmt in ["json", "xml", "csv"]:
- assert f"Error storing {fmt} feed (2 items)" in caplog.text
-
- @coroutine_test
- async def test_extend_kwargs(self, mockserver: MockServer, tmp_path: Path) -> None:
- items = [{"foo": "FOO", "bar": "BAR"}]
-
- expected_with_title_csv = b"foo,bar\r\nFOO,BAR\r\n"
- expected_without_title_csv = b"FOO,BAR\r\n"
- test_cases: list[dict[str, Any]] = [
- # with title
- {
- "options": {
- "format": "csv",
- "item_export_kwargs": {"include_headers_line": True},
- },
- "expected": expected_with_title_csv,
- },
- # without title
- {
- "options": {
- "format": "csv",
- "item_export_kwargs": {"include_headers_line": False},
- },
- "expected": expected_without_title_csv,
- },
- ]
-
- for row in test_cases:
- feed_options = row["options"]
- settings = {
- "FEEDS": {
- unique_path(tmp_path): feed_options,
- },
- "FEED_EXPORT_INDENT": None,
- }
-
- data = await export_by_format(mockserver, items, settings)
- assert data[feed_options["format"]] == row["expected"]
-
- @coroutine_test
- async def test_storage_file_no_postprocessing(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- class Storage:
- open_file: IO[bytes]
- store_file: IO[bytes]
-
- def __init__(self, uri, *, feed_options=None):
- pass
-
- def open(self, spider):
- Storage.open_file = tempfile.NamedTemporaryFile(prefix="feed-")
- return Storage.open_file
-
- def store(self, file):
- Storage.store_file = file
- file.close()
-
- settings = {
- "FEEDS": {unique_path(tmp_path): {"format": "jsonlines"}},
- "FEED_STORAGES": {"file": Storage},
- }
- await export_by_format(mockserver, [], settings)
- assert Storage.open_file is Storage.store_file
-
- @coroutine_test
- async def test_storage_file_postprocessing(
- self, mockserver: MockServer, tmp_path: Path
- ) -> None:
- class Storage:
- open_file: IO[bytes]
- store_file: IO[bytes]
- file_was_closed: bool
-
- def __init__(self, uri, *, feed_options=None):
- pass
-
- def open(self, spider):
- Storage.open_file = tempfile.NamedTemporaryFile(prefix="feed-")
- return Storage.open_file
+ settings = {
+ "FEED_EXPORTERS": {"csv": FromCrawlerCsvItemExporter},
+ "FEED_STORAGES": {"file": FromCrawlerFileFeedStorage},
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "csv"},
+ },
+ }
+ await export_by_format(mockserver, [], settings)
+ assert FromCrawlerCsvItemExporter.init_with_crawler
+ assert FromCrawlerFileFeedStorage.init_with_crawler
- def store(self, file):
- Storage.store_file = file
- Storage.file_was_closed = file.closed
- file.close()
- settings = {
- "FEEDS": {
- unique_path(tmp_path): {
- "format": "jsonlines",
- "postprocessing": [
- "scrapy.extensions.postprocessing.GzipPlugin",
- ],
- },
- },
- "FEED_STORAGES": {"file": Storage},
- }
- await export_by_format(mockserver, [], settings)
- assert Storage.open_file is Storage.store_file
- assert not Storage.file_was_closed
+@coroutine_test
+async def test_str_uri(mockserver: MockServer, tmp_path: Path) -> None:
+ settings = {
+ "FEED_STORE_EMPTY": True,
+ "FEEDS": {str(unique_path(tmp_path)): {"format": "csv"}},
+ }
+ data = await export_by_format(mockserver, [], settings)
+ assert data["csv"] == b""
# Test that the FeedExporer sends the feed_exporter_closed and feed_slot_closed signals
@@ -1348,35 +148,6 @@ class TestFeedExporterSignals:
assert self.feed_exporter_closed_received
-class TestFeedExporterOpenSpider:
- @coroutine_test
- async def test_bad_uri_placeholder_skips_only_that_feed(
- self, caplog: pytest.LogCaptureFixture
- ) -> None:
- with tempfile.NamedTemporaryFile(suffix="json") as tmp:
- settings = {
- "FEEDS": {
- printf_escape(path_to_url(tmp.name)): {"format": "json"},
- "file:///nonexistent/%(undefined_attr)s.json": {"format": "json"},
- },
- }
- crawler = get_crawler(settings_dict=settings)
- feed_exporter = build_from_crawler(FeedExporter, crawler)
- spider = scrapy.Spider.from_crawler(crawler, "default")
- with caplog.at_level(logging.ERROR):
- feed_exporter.open_spider(spider)
- assert len(feed_exporter.slots) == 1
- assert "undefined_attr" in caplog.text
- await feed_exporter.close_spider(spider)
-
-
-class TestItemFilter:
- def test_no_feed_options(self):
- item_filter = ItemFilter(None)
- assert item_filter.item_classes == ()
- assert item_filter.accepts(MyItem({"foo": "bar"}))
-
-
class TestFeedExportInit:
def test_unsupported_storage(self):
settings: dict[str, Any] = {
@@ -1465,34 +236,3 @@ class TestFeedExportInit:
crawler = get_crawler(settings_dict=settings)
exporter = build_from_crawler(FeedExporter, crawler)
assert isinstance(exporter, FeedExporter)
-
-
-class TestApplyUriParams:
- params = {
- "name": "myspider",
- "time": "2020-01-01T00-00-00",
- "batch_id": 2,
- "batch_time": "2020-01-01T00-00-00",
- }
-
- @pytest.mark.parametrize(
- ("uri_template", "expected"),
- [
- # Placeholders are substituted, including width/flags.
- ("/data/%(name)s/%(time)s.json", "/data/myspider/2020-01-01T00-00-00.json"),
- ("/data/%(batch_id)05d.json", "/data/00002.json"),
- # Percent-encoding is kept verbatim (#6425, #5794).
- (
- "file:///path%20with%20spaces/%(name)s.json",
- "file:///path%20with%20spaces/myspider.json",
- ),
- (
- "ftp://user:2%23um25%21M%[email protected]/%(name)s.csv",
- "ftp://user:2%23um25%21M%[email protected]/myspider.csv",
- ),
- # A lone percent character next to a placeholder stays literal.
- ("/100%/%(name)s.json", "/100%/myspider.json"),
- ],
- )
- def test_apply_uri_params(self, uri_template: str, expected: str) -> None:
- assert apply_uri_params(uri_template, self.params) == expected
diff --git a/tests/test_feedexport_empty.py b/tests/test_feedexport_empty.py
new file mode 100644
index 000000000..5121a4b69
--- /dev/null
+++ b/tests/test_feedexport_empty.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+import logging
+import tempfile
+from logging import getLogger
+from typing import TYPE_CHECKING
+
+from w3lib.url import file_uri_to_path
+
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import export_by_format, unique_path
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ import pytest
+
+ from tests.mockserver.http import MockServer
+
+
+class LogOnStoreFileStorage:
+ """
+ This storage logs inside `store` method.
+ It can be used to make sure `store` method is invoked.
+ """
+
+ def __init__(self, uri, feed_options=None):
+ self.path = file_uri_to_path(uri)
+ self.logger = getLogger()
+
+ def open(self, spider):
+ return tempfile.NamedTemporaryFile(prefix="feed-")
+
+ def store(self, file):
+ self.logger.info("Storage.store is called")
+ file.close()
+
+
+@coroutine_test
+async def test_export_no_items_not_store_empty(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ for fmt in ("json", "jsonlines", "xml", "csv"):
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": fmt},
+ },
+ "FEED_STORE_EMPTY": False,
+ }
+ data = await export_by_format(mockserver, [], settings)
+ assert data[fmt] is None
+
+
+@coroutine_test
+async def test_export_no_items_store_empty(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ formats = (
+ ("json", b"[]"),
+ ("jsonlines", b""),
+ ("xml", b'<?xml version="1.0" encoding="utf-8"?>\n<items></items>'),
+ ("csv", b""),
+ )
+
+ for fmt, expctd in formats:
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": fmt},
+ },
+ "FEED_STORE_EMPTY": True,
+ "FEED_EXPORT_INDENT": None,
+ }
+ data = await export_by_format(mockserver, [], settings)
+ assert expctd == data[fmt]
+
+
+@coroutine_test
+async def test_export_no_items_multiple_feeds(
+ caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
+) -> None:
+ """Make sure that `storage.store` is not called."""
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ unique_path(tmp_path): {"format": "xml"},
+ unique_path(tmp_path): {"format": "csv"},
+ },
+ "FEED_STORAGES": {"file": LogOnStoreFileStorage},
+ "FEED_STORE_EMPTY": False,
+ }
+
+ with caplog.at_level(logging.INFO):
+ await export_by_format(mockserver, [], settings)
+
+ assert caplog.text.count("Storage.store is called") == 0
diff --git a/tests/test_feedexport_fields.py b/tests/test_feedexport_fields.py
new file mode 100644
index 000000000..5cf74497f
--- /dev/null
+++ b/tests/test_feedexport_fields.py
@@ -0,0 +1,227 @@
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import PARSERS, MyItem, MyItem2, assert_exported
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from tests.mockserver.http import MockServer
+
+
[email protected]("fmt", ["csv", "jsonlines"])
+@coroutine_test
+async def test_export_items_empty_field_list(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ # FEED_EXPORT_FIELDS==[] means the same as default None
+ items = [{"foo": "bar"}]
+ header = ["foo"]
+ rows = [{"foo": "bar"}]
+ settings: dict[str, Any] = {"FEED_EXPORT_FIELDS": []}
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items_field_list(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": "bar"}]
+ header = ["foo", "baz"]
+ rows = [{"foo": "bar"}]
+ settings = {"FEED_EXPORT_FIELDS": header}
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items_comma_separated_field_list(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": "bar"}]
+ header = ["foo", "baz"]
+ rows = [{"foo": "bar"}]
+ settings = {"FEED_EXPORT_FIELDS": ",".join(header)}
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items_json_field_list(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": "bar"}]
+ header = ["foo", "baz"]
+ rows = [{"foo": "bar"}]
+ settings = {"FEED_EXPORT_FIELDS": json.dumps(header)}
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows, settings)
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items_field_names(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": "bar"}]
+ header = {"foo": "Foo"}
+ rows = [{"Foo": "bar"}]
+ settings = {"FEED_EXPORT_FIELDS": header}
+ await assert_exported(
+ mockserver, tmp_path, fmt, items, header.values(), rows, settings
+ )
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items_dict_field_names(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": "bar"}]
+ header = {
+ "baz": "Baz",
+ "foo": "Foo",
+ }
+ rows = [{"Foo": "bar"}]
+ settings = {"FEED_EXPORT_FIELDS": header}
+ await assert_exported(
+ mockserver, tmp_path, fmt, items, ["Baz", "Foo"], rows, settings
+ )
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items_json_field_names(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": "bar"}]
+ header = {"foo": "Foo"}
+ rows = [{"Foo": "bar"}]
+ settings = {"FEED_EXPORT_FIELDS": json.dumps(header)}
+ await assert_exported(
+ mockserver, tmp_path, fmt, items, header.values(), rows, settings
+ )
+
+
+# When dicts are used, only keys from the first row are used as
+# a header for CSV, and all fields are used for JSON Lines.
+ ("fmt", "rows"),
+ [
+ ("csv", [{"egg": "spam", "foo": "bar"}, {"egg": "spam", "foo": "bar"}]),
+ (
+ "jsonlines",
+ [
+ {"foo": "bar", "egg": "spam"},
+ {"foo": "bar", "egg": "spam", "baz": "quux"},
+ ],
+ ),
+ ],
+)
+@coroutine_test
+async def test_export_dicts(
+ fmt: str,
+ rows: list[dict[str, Any]],
+ mockserver: MockServer,
+ tmp_path: Path,
+) -> None:
+ items = [
+ {"foo": "bar", "egg": "spam"},
+ {"foo": "bar", "egg": "spam", "baz": "quux"},
+ ]
+ header = ["foo", "egg"]
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows)
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_tuple(fmt: str, mockserver: MockServer, tmp_path: Path) -> None:
+ items = [
+ {"foo": "bar1", "egg": "spam1"},
+ {"foo": "bar2", "egg": "spam2", "baz": "quux"},
+ ]
+
+ settings = {"FEED_EXPORT_FIELDS": ("foo", "baz")}
+ rows = [{"foo": "bar1"}, {"foo": "bar2", "baz": "quux"}]
+ await assert_exported(
+ mockserver, tmp_path, fmt, items, ["foo", "baz"], rows, settings
+ )
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_feed_export_fields(
+ fmt: str, mockserver: MockServer, tmp_path: Path
+) -> None:
+ # FEED_EXPORT_FIELDS option allows to order export fields
+ # and to select a subset of fields to export, both for Items and dicts.
+
+ for item_cls in [MyItem, dict]:
+ items = [
+ item_cls({"foo": "bar1", "egg": "spam1"}),
+ item_cls({"foo": "bar2", "egg": "spam2", "baz": "quux2"}),
+ ]
+
+ # export all columns
+ settings = {"FEED_EXPORT_FIELDS": "foo,baz,egg"}
+ rows = [
+ {"egg": "spam1", "foo": "bar1"},
+ {"egg": "spam2", "foo": "bar2", "baz": "quux2"},
+ ]
+ await assert_exported(
+ mockserver, tmp_path, fmt, items, ["foo", "baz", "egg"], rows, settings
+ )
+
+ # export a subset of columns
+ settings = {"FEED_EXPORT_FIELDS": "egg,baz"}
+ rows = [{"egg": "spam1"}, {"egg": "spam2", "baz": "quux2"}]
+ await assert_exported(
+ mockserver, tmp_path, fmt, items, ["egg", "baz"], rows, settings
+ )
+
+
+# by default, Scrapy uses fields of the first Item for CSV and
+# all fields for JSON Lines
+ ("fmt", "rows"),
+ [
+ (
+ "csv",
+ [
+ {"egg": "spam1", "foo": "bar1"},
+ {"foo": "bar2"},
+ {"egg": "spam3", "foo": "bar3", "baz": "quux3"},
+ {"egg": "spam4"},
+ ],
+ ),
+ (
+ "jsonlines",
+ [
+ {"foo": "bar1", "egg": "spam1"},
+ {"hello": "world2", "foo": "bar2"},
+ {"foo": "bar3", "egg": "spam3", "baz": "quux3"},
+ {"hello": "world4", "egg": "spam4"},
+ ],
+ ),
+ ],
+)
+@coroutine_test
+async def test_export_multiple_item_classes(
+ fmt: str,
+ rows: list[dict[str, Any]],
+ mockserver: MockServer,
+ tmp_path: Path,
+) -> None:
+ items = [
+ MyItem({"foo": "bar1", "egg": "spam1"}),
+ MyItem2({"hello": "world2", "foo": "bar2"}),
+ MyItem({"foo": "bar3", "egg": "spam3", "baz": "quux3"}),
+ {"hello": "world4", "egg": "spam4"},
+ ]
+ header = MyItem.fields.keys()
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows)
diff --git a/tests/test_feedexport_filters_processors.py b/tests/test_feedexport_filters_processors.py
new file mode 100644
index 000000000..eb77abede
--- /dev/null
+++ b/tests/test_feedexport_filters_processors.py
@@ -0,0 +1,206 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from scrapy.extensions.feedexport import ItemFilter
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import (
+ MyItem,
+ MyItem2,
+ crawl_items,
+ export_by_format,
+ path_to_url,
+ unique_path,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from tests.mockserver.http import MockServer
+
+
+@coroutine_test
+async def test_export_based_on_item_classes(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [
+ MyItem({"foo": "bar1", "egg": "spam1"}),
+ MyItem2({"hello": "world2", "foo": "bar2"}),
+ {"hello": "world3", "egg": "spam3"},
+ ]
+
+ formats = {
+ "csv": b"foo,egg,baz\r\nbar1,spam1,\r\n",
+ "json": b'[\n{"foo": "bar2", "hello": "world2"}\n]',
+ "jsonlines": (
+ b'{"foo": "bar1", "egg": "spam1"}\n{"foo": "bar2", "hello": "world2"}\n'
+ ),
+ "xml": (
+ b'<?xml version="1.0" encoding="utf-8"?>\n<items>\n<item>'
+ b"<foo>bar1</foo><egg>spam1</egg></item>\n<item><foo>"
+ b"bar2</foo><hello>world2</hello></item>\n<item><hello>world3"
+ b"</hello><egg>spam3</egg></item>\n</items>"
+ ),
+ }
+
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {
+ "format": "csv",
+ "item_classes": [MyItem],
+ },
+ unique_path(tmp_path): {
+ "format": "json",
+ "item_classes": [MyItem2],
+ },
+ unique_path(tmp_path): {
+ "format": "jsonlines",
+ "item_classes": [MyItem, MyItem2],
+ },
+ unique_path(tmp_path): {
+ "format": "xml",
+ },
+ },
+ }
+
+ data = await export_by_format(mockserver, items, settings)
+ for fmt, expected in formats.items():
+ assert data[fmt] == expected
+
+
+@coroutine_test
+async def test_export_based_on_custom_filters(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [
+ MyItem({"foo": "bar1", "egg": "spam1"}),
+ MyItem2({"hello": "world2", "foo": "bar2"}),
+ {"hello": "world3", "egg": "spam3"},
+ ]
+
+ class CustomFilter1:
+ def __init__(self, feed_options):
+ pass
+
+ def accepts(self, item):
+ return isinstance(item, MyItem)
+
+ class CustomFilter2(ItemFilter):
+ def accepts(self, item):
+ return "foo" in item.fields
+
+ class CustomFilter3(ItemFilter):
+ def accepts(self, item):
+ return (
+ isinstance(item, tuple(self.item_classes)) and item["foo"] == "bar1" # type: ignore[index]
+ )
+
+ formats = {
+ "json": b'[\n{"foo": "bar1", "egg": "spam1"}\n]',
+ "xml": (
+ b'<?xml version="1.0" encoding="utf-8"?>\n<items>\n<item>'
+ b"<foo>bar1</foo><egg>spam1</egg></item>\n<item><foo>"
+ b"bar2</foo><hello>world2</hello></item>\n</items>"
+ ),
+ "jsonlines": b'{"foo": "bar1", "egg": "spam1"}\n',
+ }
+
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {
+ "format": "json",
+ "item_filter": CustomFilter1,
+ },
+ unique_path(tmp_path): {
+ "format": "xml",
+ "item_filter": CustomFilter2,
+ },
+ unique_path(tmp_path): {
+ "format": "jsonlines",
+ "item_classes": [MyItem, MyItem2],
+ "item_filter": CustomFilter3,
+ },
+ },
+ }
+
+ data = await export_by_format(mockserver, items, settings)
+ for fmt, expected in formats.items():
+ assert data[fmt] == expected
+
+
+class TestItemFilter:
+ def test_no_feed_options(self):
+ item_filter = ItemFilter(None)
+ assert item_filter.item_classes == ()
+ assert item_filter.accepts(MyItem({"foo": "bar"}))
+
+
+def split_foo(item):
+ for value in item["foo"].split(","):
+ yield {"foo": value}
+
+
+def drop_item(item):
+ return []
+
+
+@coroutine_test
+async def test_export_based_on_item_processors(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [
+ MyItem({"foo": "bar1,bar2"}),
+ {"foo": "bar3"},
+ ]
+
+ formats = {
+ "jsonlines": b'{"foo": "bar1"}\n{"foo": "bar2"}\n{"foo": "bar3"}\n',
+ "json": b'[\n{"foo": "bar1"},\n{"foo": "bar2"},\n{"foo": "bar3"}\n]',
+ "xml": (
+ b'<?xml version="1.0" encoding="utf-8"?>\n<items>\n'
+ b"<item><foo>bar1</foo></item>\n<item><foo>bar2</foo></item>\n</items>"
+ ),
+ "csv": b"",
+ }
+
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {
+ "format": "jsonlines",
+ "item_processor": split_foo,
+ },
+ unique_path(tmp_path): {
+ "format": "json",
+ "item_processor": "tests.test_feedexport_filters_processors.split_foo",
+ },
+ unique_path(tmp_path): {
+ "format": "xml",
+ "item_classes": [MyItem],
+ "item_processor": split_foo,
+ },
+ unique_path(tmp_path): {
+ "format": "csv",
+ "item_processor": drop_item,
+ },
+ },
+ }
+
+ data = await export_by_format(mockserver, items, settings)
+ for fmt, expected in formats.items():
+ assert data[fmt] == expected
+
+
+@coroutine_test
+async def test_item_processor_stats(mockserver: MockServer, tmp_path: Path) -> None:
+ settings = {
+ "FEEDS": {
+ path_to_url(unique_path(tmp_path)): {
+ "format": "jsonlines",
+ "item_processor": split_foo,
+ },
+ },
+ }
+ crawler = await crawl_items(mockserver, [{"foo": "bar1,bar2"}], settings)
+
+ assert crawler.stats.get_value("item_scraped_count") == 1
+ assert crawler.stats.get_value("feedexport/item_count/FileFeedStorage") == 2
diff --git a/tests/test_feedexport_formats.py b/tests/test_feedexport_formats.py
new file mode 100644
index 000000000..bef423b0c
--- /dev/null
+++ b/tests/test_feedexport_formats.py
@@ -0,0 +1,317 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import (
+ PARSERS,
+ MyItem,
+ assert_exported,
+ export_by_format,
+ unique_path,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from tests.mockserver.http import MockServer
+
+
[email protected]("fmt", list(PARSERS))
+@coroutine_test
+async def test_export_items(fmt: str, mockserver: MockServer, tmp_path: Path) -> None:
+ # feed exporters use field names from Item
+ items = [
+ MyItem({"foo": "bar1", "egg": "spam1"}),
+ MyItem({"foo": "bar2", "egg": "spam2", "baz": "quux2"}),
+ ]
+ rows = [
+ {"egg": "spam1", "foo": "bar1"},
+ {"egg": "spam2", "foo": "bar2", "baz": "quux2"},
+ ]
+ header = MyItem.fields.keys()
+ await assert_exported(mockserver, tmp_path, fmt, items, header, rows)
+
+
+@coroutine_test
+async def test_export_encoding(mockserver: MockServer, tmp_path: Path) -> None:
+ items = [{"foo": "Test\xd6"}]
+
+ formats = {
+ "json": b'[{"foo": "Test\\u00d6"}]',
+ "jsonlines": b'{"foo": "Test\\u00d6"}\n',
+ "xml": (
+ '<?xml version="1.0" encoding="utf-8"?>\n'
+ "<items><item><foo>Test\xd6</foo></item></items>"
+ ).encode(),
+ "csv": "foo\r\nTest\xd6\r\n".encode(),
+ }
+
+ for fmt, expected in formats.items():
+ settings: dict[str, Any] = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": fmt},
+ },
+ "FEED_EXPORT_INDENT": None,
+ }
+ data = await export_by_format(mockserver, items, settings)
+ assert data[fmt] == expected
+
+ formats = {
+ "json": b'[{"foo": "Test\xd6"}]',
+ "jsonlines": b'{"foo": "Test\xd6"}\n',
+ "xml": (
+ b'<?xml version="1.0" encoding="latin-1"?>\n'
+ b"<items><item><foo>Test\xd6</foo></item></items>"
+ ),
+ "csv": b"foo\r\nTest\xd6\r\n",
+ }
+
+ for fmt, expected in formats.items():
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": fmt},
+ },
+ "FEED_EXPORT_INDENT": None,
+ "FEED_EXPORT_ENCODING": "latin-1",
+ }
+ data = await export_by_format(mockserver, items, settings)
+ assert data[fmt] == expected
+
+
+@coroutine_test
+async def test_export_multiple_configs(mockserver: MockServer, tmp_path: Path) -> None:
+ items = [{"foo": "FOO", "bar": "BAR"}]
+
+ formats = {
+ "json": b'[\n{"bar": "BAR"}\n]',
+ "xml": (
+ b'<?xml version="1.0" encoding="latin-1"?>\n'
+ b"<items>\n <item>\n <foo>FOO</foo>\n </item>\n</items>"
+ ),
+ "csv": b"bar,foo\r\nBAR,FOO\r\n",
+ }
+
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {
+ "format": "json",
+ "indent": 0,
+ "fields": ["bar"],
+ "encoding": "utf-8",
+ },
+ unique_path(tmp_path): {
+ "format": "xml",
+ "indent": 2,
+ "fields": ["foo"],
+ "encoding": "latin-1",
+ },
+ unique_path(tmp_path): {
+ "format": "csv",
+ "indent": None,
+ "fields": ["bar", "foo"],
+ "encoding": "utf-8",
+ },
+ },
+ }
+
+ data = await export_by_format(mockserver, items, settings)
+ for fmt, expected in formats.items():
+ assert data[fmt] == expected
+
+
+@coroutine_test
+async def test_export_indentation(mockserver: MockServer, tmp_path: Path) -> None:
+ items = [
+ {"foo": ["bar"]},
+ {"key": "value"},
+ ]
+
+ test_cases: list[dict[str, Any]] = [
+ # JSON
+ {
+ "format": "json",
+ "indent": None,
+ "expected": b'[{"foo": ["bar"]},{"key": "value"}]',
+ },
+ {
+ "format": "json",
+ "indent": -1,
+ "expected": b"""[
+{"foo": ["bar"]},
+{"key": "value"}
+]""",
+ },
+ {
+ "format": "json",
+ "indent": 0,
+ "expected": b"""[
+{"foo": ["bar"]},
+{"key": "value"}
+]""",
+ },
+ {
+ "format": "json",
+ "indent": 2,
+ "expected": b"""[
+{
+ "foo": [
+ "bar"
+ ]
+},
+{
+ "key": "value"
+}
+]""",
+ },
+ {
+ "format": "json",
+ "indent": 4,
+ "expected": b"""[
+{
+ "foo": [
+ "bar"
+ ]
+},
+{
+ "key": "value"
+}
+]""",
+ },
+ {
+ "format": "json",
+ "indent": 5,
+ "expected": b"""[
+{
+ "foo": [
+ "bar"
+ ]
+},
+{
+ "key": "value"
+}
+]""",
+ },
+ # XML
+ {
+ "format": "xml",
+ "indent": None,
+ "expected": b"""<?xml version="1.0" encoding="utf-8"?>
+<items><item><foo><value>bar</value></foo></item><item><key>value</key></item></items>""",
+ },
+ {
+ "format": "xml",
+ "indent": -1,
+ "expected": b"""<?xml version="1.0" encoding="utf-8"?>
+<items>
+<item><foo><value>bar</value></foo></item>
+<item><key>value</key></item>
+</items>""",
+ },
+ {
+ "format": "xml",
+ "indent": 0,
+ "expected": b"""<?xml version="1.0" encoding="utf-8"?>
+<items>
+<item><foo><value>bar</value></foo></item>
+<item><key>value</key></item>
+</items>""",
+ },
+ {
+ "format": "xml",
+ "indent": 2,
+ "expected": b"""<?xml version="1.0" encoding="utf-8"?>
+<items>
+ <item>
+ <foo>
+ <value>bar</value>
+ </foo>
+ </item>
+ <item>
+ <key>value</key>
+ </item>
+</items>""",
+ },
+ {
+ "format": "xml",
+ "indent": 4,
+ "expected": b"""<?xml version="1.0" encoding="utf-8"?>
+<items>
+ <item>
+ <foo>
+ <value>bar</value>
+ </foo>
+ </item>
+ <item>
+ <key>value</key>
+ </item>
+</items>""",
+ },
+ {
+ "format": "xml",
+ "indent": 5,
+ "expected": b"""<?xml version="1.0" encoding="utf-8"?>
+<items>
+ <item>
+ <foo>
+ <value>bar</value>
+ </foo>
+ </item>
+ <item>
+ <key>value</key>
+ </item>
+</items>""",
+ },
+ ]
+
+ for row in test_cases:
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {
+ "format": row["format"],
+ "indent": row["indent"],
+ },
+ },
+ }
+ data = await export_by_format(mockserver, items, settings)
+ assert data[row["format"]] == row["expected"]
+
+
+@coroutine_test
+async def test_extend_kwargs(mockserver: MockServer, tmp_path: Path) -> None:
+ items = [{"foo": "FOO", "bar": "BAR"}]
+
+ expected_with_title_csv = b"foo,bar\r\nFOO,BAR\r\n"
+ expected_without_title_csv = b"FOO,BAR\r\n"
+ test_cases: list[dict[str, Any]] = [
+ # with title
+ {
+ "options": {
+ "format": "csv",
+ "item_export_kwargs": {"include_headers_line": True},
+ },
+ "expected": expected_with_title_csv,
+ },
+ # without title
+ {
+ "options": {
+ "format": "csv",
+ "item_export_kwargs": {"include_headers_line": False},
+ },
+ "expected": expected_without_title_csv,
+ },
+ ]
+
+ for row in test_cases:
+ feed_options = row["options"]
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): feed_options,
+ },
+ "FEED_EXPORT_INDENT": None,
+ }
+
+ data = await export_by_format(mockserver, items, settings)
+ assert data[feed_options["format"]] == row["expected"]
diff --git a/tests/test_feedexport_lifecycle.py b/tests/test_feedexport_lifecycle.py
new file mode 100644
index 000000000..1a42f9531
--- /dev/null
+++ b/tests/test_feedexport_lifecycle.py
@@ -0,0 +1,171 @@
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+from unittest import mock
+
+from scrapy.exporters import JsonItemExporter
+from scrapy.extensions.feedexport import FeedSlot
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import MyItem, export_by_format, unique_path
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from pathlib import Path
+
+ import pytest
+
+ from tests.mockserver.http import MockServer
+
+
+class InstrumentedFeedSlot(FeedSlot):
+ """Instrumented FeedSlot subclass for keeping track of calls to
+ start_exporting and finish_exporting."""
+
+ update_listener: Callable[[str], None]
+
+ async def start_exporting(self):
+ self.update_listener("start")
+ await super().start_exporting()
+
+ async def finish_exporting(self):
+ self.update_listener("finish")
+ await super().finish_exporting()
+
+ @classmethod
+ def subscribe__listener(cls, listener: IsExportingListener) -> None:
+ cls.update_listener = listener.update
+
+
+class IsExportingListener:
+ """When subscribed to InstrumentedFeedSlot, keeps track of when
+ a call to start_exporting has been made without a closing call to
+ finish_exporting and when a call to finish_exporting has been made
+ before a call to start_exporting."""
+
+ def __init__(self) -> None:
+ self.start_without_finish = False
+ self.finish_without_start = False
+
+ def update(self, method):
+ if method == "start":
+ self.start_without_finish = True
+ elif method == "finish":
+ if self.start_without_finish:
+ self.start_without_finish = False
+ else:
+ self.finish_without_start = True
+
+
+class ExceptionJsonItemExporter(JsonItemExporter):
+ """JsonItemExporter that throws an exception every time export_item is called."""
+
+ def export_item(self, _):
+ raise RuntimeError("foo")
+
+
+@coroutine_test
+async def test_start_finish_exporting_items(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [
+ MyItem({"foo": "bar1", "egg": "spam1"}),
+ ]
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ },
+ "FEED_EXPORT_INDENT": None,
+ }
+
+ listener = IsExportingListener()
+ InstrumentedFeedSlot.subscribe__listener(listener)
+
+ with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
+ await export_by_format(mockserver, items, settings)
+ assert not listener.start_without_finish
+ assert not listener.finish_without_start
+
+
+@coroutine_test
+async def test_start_finish_exporting_no_items(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items: list[Any] = []
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ },
+ "FEED_EXPORT_INDENT": None,
+ }
+
+ listener = IsExportingListener()
+ InstrumentedFeedSlot.subscribe__listener(listener)
+
+ with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
+ await export_by_format(mockserver, items, settings)
+ assert not listener.start_without_finish
+ assert not listener.finish_without_start
+
+
+@coroutine_test
+async def test_start_finish_exporting_items_exception(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [
+ MyItem({"foo": "bar1", "egg": "spam1"}),
+ ]
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ },
+ "FEED_EXPORTERS": {"json": ExceptionJsonItemExporter},
+ "FEED_EXPORT_INDENT": None,
+ }
+
+ listener = IsExportingListener()
+ InstrumentedFeedSlot.subscribe__listener(listener)
+
+ with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
+ await export_by_format(mockserver, items, settings)
+ assert not listener.start_without_finish
+ assert not listener.finish_without_start
+
+
+@coroutine_test
+async def test_export_item_exception_mentions_item(
+ caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
+) -> None:
+ items = [{"foo": {None: "bar"}}]
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ },
+ "FEED_EXPORTERS": {"json": ExceptionJsonItemExporter},
+ }
+ with caplog.at_level(logging.ERROR):
+ await export_by_format(mockserver, items, settings)
+ assert "RuntimeError: foo" in caplog.text
+ assert "Item: {'foo': {None: 'bar'}}" in caplog.text
+
+
+@coroutine_test
+async def test_start_finish_exporting_no_items_exception(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ items: list[Any] = []
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ },
+ "FEED_EXPORTERS": {"json": ExceptionJsonItemExporter},
+ "FEED_EXPORT_INDENT": None,
+ }
+
+ listener = IsExportingListener()
+ InstrumentedFeedSlot.subscribe__listener(listener)
+
+ with mock.patch("scrapy.extensions.feedexport.FeedSlot", InstrumentedFeedSlot):
+ await export_by_format(mockserver, items, settings)
+ assert not listener.start_without_finish
+ assert not listener.finish_without_start
diff --git a/tests/test_feedexport_postprocess.py b/tests/test_feedexport_postprocess.py
index 94e6160a2..f56b4a5f7 100644
--- a/tests/test_feedexport_postprocess.py
+++ b/tests/test_feedexport_postprocess.py
@@ -6,14 +6,15 @@ import lzma
import marshal
import pickle
import sys
+import tempfile
from io import BytesIO
-from typing import TYPE_CHECKING
+from typing import IO, TYPE_CHECKING
import pytest
from scrapy.extensions.postprocessing import PostProcessingManager
from tests.utils.decorators import coroutine_test
-from tests.utils.feedexport import export_by_path
+from tests.utils.feedexport import export_by_format, export_by_path, unique_path
if TYPE_CHECKING:
from pathlib import Path
@@ -526,3 +527,67 @@ class TestFeedPostProcessedExports:
assert data[path] == expected
assert pickle.loads(data[tmp_path / "pickle"]) == self.items[0]
assert marshal.loads(data[tmp_path / "marshal"]) == self.items[0]
+
+
+@coroutine_test
+async def test_storage_file_no_postprocessing(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ class Storage:
+ open_file: IO[bytes]
+ store_file: IO[bytes]
+
+ def __init__(self, uri, *, feed_options=None):
+ pass
+
+ def open(self, spider):
+ Storage.open_file = tempfile.NamedTemporaryFile(prefix="feed-")
+ return Storage.open_file
+
+ def store(self, file):
+ Storage.store_file = file
+ file.close()
+
+ settings = {
+ "FEEDS": {unique_path(tmp_path): {"format": "jsonlines"}},
+ "FEED_STORAGES": {"file": Storage},
+ }
+ await export_by_format(mockserver, [], settings)
+ assert Storage.open_file is Storage.store_file
+
+
+@coroutine_test
+async def test_storage_file_postprocessing(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ class Storage:
+ open_file: IO[bytes]
+ store_file: IO[bytes]
+ file_was_closed: bool
+
+ def __init__(self, uri, *, feed_options=None):
+ pass
+
+ def open(self, spider):
+ Storage.open_file = tempfile.NamedTemporaryFile(prefix="feed-")
+ return Storage.open_file
+
+ def store(self, file):
+ Storage.store_file = file
+ Storage.file_was_closed = file.closed
+ file.close()
+
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {
+ "format": "jsonlines",
+ "postprocessing": [
+ "scrapy.extensions.postprocessing.GzipPlugin",
+ ],
+ },
+ },
+ "FEED_STORAGES": {"file": Storage},
+ }
+ await export_by_format(mockserver, [], settings)
+ assert Storage.open_file is Storage.store_file
+ assert not Storage.file_was_closed
diff --git a/tests/test_feedexport_reporting.py b/tests/test_feedexport_reporting.py
new file mode 100644
index 000000000..21ce3db7c
--- /dev/null
+++ b/tests/test_feedexport_reporting.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import IO, TYPE_CHECKING
+from unittest import mock
+
+from w3lib.url import file_uri_to_path
+
+from scrapy.extensions.feedexport import BlockingFeedStorage
+from scrapy.utils.test import get_crawler
+from tests.spiders import ItemSpider
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import (
+ export_by_format,
+ path_to_url,
+ printf_escape,
+ unique_path,
+)
+
+if TYPE_CHECKING:
+ import pytest
+
+ from tests.mockserver.http import MockServer
+
+
+class DummyBlockingFeedStorage(BlockingFeedStorage):
+ def __init__(self, uri, *args, feed_options=None):
+ self.path = Path(file_uri_to_path(uri))
+
+ def _store_in_thread(self, file):
+ dirname = self.path.parent
+ if dirname and not dirname.exists():
+ dirname.mkdir(parents=True)
+ with self.path.open("ab") as output_file:
+ output_file.write(file.read())
+
+ file.close()
+
+
+class FailingBlockingFeedStorage(DummyBlockingFeedStorage):
+ def _store_in_thread(self, file):
+ file.close()
+ raise OSError("Cannot store")
+
+
+@coroutine_test
+async def test_stats_file_success(mockserver: MockServer, tmp_path: Path) -> None:
+ settings = {
+ "FEEDS": {
+ printf_escape(path_to_url(str(unique_path(tmp_path)))): {
+ "format": "json",
+ }
+ },
+ }
+ crawler = get_crawler(ItemSpider, settings)
+ await crawler.crawl_async(mockserver=mockserver)
+ assert "feedexport/success_count/FileFeedStorage" in crawler.stats.get_stats()
+ assert crawler.stats.get_value("feedexport/success_count/FileFeedStorage") == 1
+
+
+@coroutine_test
+async def test_stats_file_failed(mockserver: MockServer, tmp_path: Path) -> None:
+ settings = {
+ "FEEDS": {
+ printf_escape(path_to_url(str(unique_path(tmp_path)))): {
+ "format": "json",
+ }
+ },
+ }
+ crawler = get_crawler(ItemSpider, settings)
+
+ def store(file: IO[bytes]) -> None:
+ file.close()
+ raise KeyError("foo")
+
+ with mock.patch(
+ "scrapy.extensions.feedexport.FileFeedStorage.store",
+ side_effect=store,
+ ):
+ await crawler.crawl_async(mockserver=mockserver)
+ assert "feedexport/failed_count/FileFeedStorage" in crawler.stats.get_stats()
+ assert crawler.stats.get_value("feedexport/failed_count/FileFeedStorage") == 1
+
+
+@coroutine_test
+async def test_stats_multiple_file(mockserver: MockServer, tmp_path: Path) -> None:
+ settings = {
+ "FEEDS": {
+ printf_escape(path_to_url(str(unique_path(tmp_path)))): {
+ "format": "json",
+ },
+ "stdout:": {
+ "format": "xml",
+ },
+ },
+ }
+ crawler = get_crawler(ItemSpider, settings)
+ await crawler.crawl_async(mockserver=mockserver)
+ assert "feedexport/success_count/FileFeedStorage" in crawler.stats.get_stats()
+ assert "feedexport/success_count/StdoutFeedStorage" in crawler.stats.get_stats()
+ assert crawler.stats.get_value("feedexport/success_count/FileFeedStorage") == 1
+ assert crawler.stats.get_value("feedexport/success_count/StdoutFeedStorage") == 1
+
+
+@coroutine_test
+async def test_multiple_feeds_success_logs_blocking_feed_storage(
+ caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
+) -> None:
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ unique_path(tmp_path): {"format": "xml"},
+ unique_path(tmp_path): {"format": "csv"},
+ },
+ "FEED_STORAGES": {"file": DummyBlockingFeedStorage},
+ }
+ items = [
+ {"foo": "bar1", "baz": ""},
+ {"foo": "bar2", "baz": "quux"},
+ ]
+ with caplog.at_level(logging.DEBUG):
+ await export_by_format(mockserver, items, settings)
+
+ for fmt in ["json", "xml", "csv"]:
+ assert f"Stored {fmt} feed (2 items)" in caplog.text
+
+
+@coroutine_test
+async def test_multiple_feeds_failing_logs_blocking_feed_storage(
+ caplog: pytest.LogCaptureFixture, mockserver: MockServer, tmp_path: Path
+) -> None:
+ settings = {
+ "FEEDS": {
+ unique_path(tmp_path): {"format": "json"},
+ unique_path(tmp_path): {"format": "xml"},
+ unique_path(tmp_path): {"format": "csv"},
+ },
+ "FEED_STORAGES": {"file": FailingBlockingFeedStorage},
+ }
+ items = [
+ {"foo": "bar1", "baz": ""},
+ {"foo": "bar2", "baz": "quux"},
+ ]
+ with caplog.at_level(logging.DEBUG):
+ await export_by_format(mockserver, items, settings)
+
+ for fmt in ["json", "xml", "csv"]:
+ assert f"Error storing {fmt} feed (2 items)" in caplog.text
diff --git a/tests/test_feedexport_uri_params.py b/tests/test_feedexport_uri_params.py
index 16d115a60..3dc527efd 100644
--- a/tests/test_feedexport_uri_params.py
+++ b/tests/test_feedexport_uri_params.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import logging
+import tempfile
import warnings
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any
@@ -9,13 +10,18 @@ import pytest
import scrapy
from scrapy.exceptions import ScrapyDeprecationWarning
-from scrapy.extensions.feedexport import FeedExporter
+from scrapy.extensions.feedexport import FeedExporter, apply_uri_params
+from scrapy.utils.misc import build_from_crawler
from scrapy.utils.test import get_crawler
+from tests.utils.decorators import coroutine_test
+from tests.utils.feedexport import MyItem, crawl_items, path_to_url, printf_escape
if TYPE_CHECKING:
from collections.abc import Callable
+ from pathlib import Path
from scrapy.crawler import Crawler
+ from tests.mockserver.http import MockServer
class TestURIParams(ABC):
@@ -160,3 +166,125 @@ class TestURIParamsFeedOption(TestURIParams):
uri: options,
},
}
+
+
+class TestApplyUriParams:
+ params = {
+ "name": "myspider",
+ "time": "2020-01-01T00-00-00",
+ "batch_id": 2,
+ "batch_time": "2020-01-01T00-00-00",
+ }
+
+ @pytest.mark.parametrize(
+ ("uri_template", "expected"),
+ [
+ # Placeholders are substituted, including width/flags.
+ ("/data/%(name)s/%(time)s.json", "/data/myspider/2020-01-01T00-00-00.json"),
+ ("/data/%(batch_id)05d.json", "/data/00002.json"),
+ # Percent-encoding is kept verbatim (#6425, #5794).
+ (
+ "file:///path%20with%20spaces/%(name)s.json",
+ "file:///path%20with%20spaces/myspider.json",
+ ),
+ (
+ "ftp://user:2%23um25%21M%[email protected]/%(name)s.csv",
+ "ftp://user:2%23um25%21M%[email protected]/myspider.csv",
+ ),
+ # A lone percent character next to a placeholder stays literal.
+ ("/100%/%(name)s.json", "/100%/myspider.json"),
+ ],
+ )
+ def test_apply_uri_params(self, uri_template: str, expected: str) -> None:
+ assert apply_uri_params(uri_template, self.params) == expected
+
+
+@coroutine_test
+async def test_pathlib_uri_with_placeholders(
+ mockserver: MockServer, tmp_path: Path
+) -> None:
+ feed_dir = tmp_path / "pathlib_placeholders"
+ feed_dir.mkdir()
+ items = [MyItem({"foo": "bar1", "egg": "spam1"})]
+
+ settings = {
+ "FEEDS": {
+ feed_dir / "%(time)s.json": {"format": "json"},
+ },
+ }
+ await crawl_items(mockserver, items, settings)
+
+ files = list(feed_dir.iterdir())
+ assert len(files) == 1
+ assert "%(time)s" not in files[0].name
+ assert files[0].suffix == ".json"
+
+
+@coroutine_test
+async def test_pathlib_uri_with_spaces_and_unicode(
+ 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 = tmp_path / "pathlib_spaces_unicode"
+ feed_dir.mkdir()
+ items = [MyItem({"foo": "bar1", "egg": "spam1"})]
+
+ settings = {
+ "FEEDS": {
+ feed_dir / "out %(name)s ünïcode.json": {"format": "json"},
+ },
+ }
+ 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(
+ 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 = tmp_path / "dir with spaces"
+ feed_dir.mkdir()
+ items = [MyItem({"foo": "bar1", "egg": "spam1"})]
+
+ settings = {
+ "FEEDS": {
+ f"{feed_dir.as_uri()}/%(time)s.json": {"format": "json"},
+ },
+ }
+ await crawl_items(mockserver, items, settings)
+
+ files = list(feed_dir.iterdir())
+ assert len(files) == 1
+ assert "%(time)s" not in files[0].name
+ assert files[0].suffix == ".json"
+
+
+@coroutine_test
+async def test_bad_uri_placeholder_skips_only_that_feed(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ with tempfile.NamedTemporaryFile(suffix="json") as tmp:
+ settings = {
+ "FEEDS": {
+ printf_escape(path_to_url(tmp.name)): {"format": "json"},
+ "file:///nonexistent/%(undefined_attr)s.json": {"format": "json"},
+ },
+ }
+ crawler = get_crawler(settings_dict=settings)
+ feed_exporter = build_from_crawler(FeedExporter, crawler)
+ spider = scrapy.Spider.from_crawler(crawler, "default")
+ with caplog.at_level(logging.ERROR):
+ feed_exporter.open_spider(spider)
+ assert len(feed_exporter.slots) == 1
+ assert "undefined_attr" in caplog.text
+ await feed_exporter.close_spider(spider)
diff --git a/tests/utils/feedexport.py b/tests/utils/feedexport.py
index 748e7c9c1..62927acba 100644
--- a/tests/utils/feedexport.py
+++ b/tests/utils/feedexport.py
@@ -142,3 +142,22 @@ PARSERS: dict[str, Callable[[bytes], list[Any]]] = {
"pickle": _parse_pickle,
"marshal": _parse_marshal,
}
+
+
+async def assert_exported(
+ mockserver: MockServer,
+ tmp_path: Path,
+ fmt: str,
+ items: Iterable[Any],
+ header: Iterable[str],
+ rows: list[dict[str, Any]],
+ settings: dict[str, Any] | None = None,
+) -> None:
+ """Check that exporting *items* as *fmt* with *settings* produces *rows*
+ and, for CSV, a *header* line."""
+ settings = {**(settings or {}), "FEEDS": {unique_path(tmp_path): {"format": fmt}}}
+ data = (await export_by_format(mockserver, items, settings))[fmt]
+ assert data is not None
+ if fmt == "csv":
+ assert csv_header(data) == list(header)
+ assert PARSERS[fmt](data) == rows