Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

scrapy-spider-metadata support. #75

Merged
merged 7 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion sh_scrapy/commands/shub_image_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,23 @@
def run(self, args, opts):
result = {
'project_type': 'scrapy',
'spiders': sorted(self.crawler_process.spider_loader.list())
'spiders': sorted(self.crawler_process.spider_loader.list()),
}
try:
from scrapy_spider_metadata import get_spider_metadata
except ImportError:
pass

Check warning on line 43 in sh_scrapy/commands/shub_image_info.py

View check run for this annotation

Codecov / codecov/patch

sh_scrapy/commands/shub_image_info.py#L40-L43

Added lines #L40 - L43 were not covered by tests
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems we lack tests on CI which check a case where the library is not installed

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3.6 and 3.7 :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why isn't this line detected as covered?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None of run() is detected as covered: https://app.codecov.io/github/scrapinghub/scrapinghub-entrypoint-scrapy/commit/ebf23f19ff3bc1853a35f001a8b2df7e1b1ec63b/blob/sh_scrapy/commands/shub_image_info.py

Not sure if codecov can detect coverage for code run as a separate process.

else:
result['metadata'] = {}
for spider_name in result['spiders']:
spider_cls = self.crawler_process.spider_loader.load(spider_name)
metadata_dict = get_spider_metadata(spider_cls)
try:

Check warning on line 49 in sh_scrapy/commands/shub_image_info.py

View check run for this annotation

Codecov / codecov/patch

sh_scrapy/commands/shub_image_info.py#L45-L49

Added lines #L45 - L49 were not covered by tests
# make sure it's serializable
json.dumps(metadata_dict)
except (TypeError, ValueError):
continue
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we have a warning here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The command prints a JSON text which some other components read, we could print warnings to stderr but I don't think anything will read them (but I'm not sure).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still, it seems currently it's the only place where the error could be show; without it there is no indication of issue at all. But maybe there is a better place for it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to do that and found that the command explicitly disables logging:

default_settings = {'LOG_ENABLED': False}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might need to find another place to log these errorrs, or document it (in scrapy-spider-metadata?). But it seems this shouldn't block this PR.

result['metadata'][spider_name] = metadata_dict

Check warning on line 54 in sh_scrapy/commands/shub_image_info.py

View check run for this annotation

Codecov / codecov/patch

sh_scrapy/commands/shub_image_info.py#L51-L54

Added lines #L51 - L54 were not covered by tests
if opts.debug:
output = subprocess.check_output(
['bash', '-c', self.IMAGE_INFO_CMD],
Expand Down
66 changes: 64 additions & 2 deletions tests/test_crawl.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import json
import mock
import pytest
import warnings
from scrapy.settings import Settings
from scrapy.exceptions import ScrapyDeprecationWarning

import sh_scrapy.crawl
from sh_scrapy.crawl import _fatalerror
Expand All @@ -18,6 +16,14 @@
from sh_scrapy.crawl import list_spiders
from sh_scrapy.crawl import main
from sh_scrapy.log import HubstorageLogHandler
from tests.utils import create_project, call_command


try:
from scrapy_spider_metadata import get_spider_metadata
SPIDER_METADATA_AVAILABLE = True
except:
SPIDER_METADATA_AVAILABLE = False


@mock.patch.dict(os.environ, {'HWORKER_SENTRY_DSN': 'hw-sentry-dsn',
Expand Down Expand Up @@ -281,3 +287,59 @@ def test_main(mocked_launch, pipe_writer):
# This ensures that pipe is writable even if main program is fininshed -
# e.g. for threads that are not closed yet.
assert not pipe_writer.close.called


def test_image_info(tmp_path):
project_dir = create_project(tmp_path)
out, err = call_command(project_dir, "shub-image-info")
# can't be asserted as it contains a SHScrapyDeprecationWarning
# assert err == ""
data = json.loads(out)
expected = {
"project_type": "scrapy",
"spiders": ["myspider"],
"metadata": {"myspider": {}},
}
if not SPIDER_METADATA_AVAILABLE:
del expected["metadata"]
assert data == expected


def test_image_info_metadata(tmp_path):
project_dir = create_project(tmp_path, spider_text="""
from scrapy import Spider

class MySpider(Spider):
name = "myspider"
metadata = {"foo": 42}
""")
out, _ = call_command(project_dir, "shub-image-info")
data = json.loads(out)
expected = {
"project_type": "scrapy",
"spiders": ["myspider"],
"metadata": {"myspider": {"foo": 42}},
}
if not SPIDER_METADATA_AVAILABLE:
del expected["metadata"]
assert data == expected


def test_image_info_metadata_skip_broken(tmp_path):
project_dir = create_project(tmp_path, spider_text="""
from scrapy import Spider

class MySpider(Spider):
name = "myspider"
metadata = {"foo": Spider}
""")
out, _ = call_command(project_dir, "shub-image-info")
data = json.loads(out)
expected = {
"project_type": "scrapy",
"spiders": ["myspider"],
"metadata": {},
}
if not SPIDER_METADATA_AVAILABLE:
del expected["metadata"]
assert data == expected
36 changes: 36 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import os
import subprocess
import sys
from pathlib import Path
from typing import Tuple, Optional, Union


def call_command(cwd: Union[str, os.PathLike], *args: str) -> Tuple[str, str]:
result = subprocess.run(
args,
cwd=str(cwd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
assert result.returncode == 0, result.stderr
return result.stdout, result.stderr


def call_scrapy_command(cwd: Union[str, os.PathLike], *args: str) -> Tuple[str, str]:
args = (sys.executable, "-m", "scrapy.cmdline") + args
return call_command(cwd, *args)


def create_project(topdir: Path, spider_text: Optional[str] = None) -> Path:
project_name = "foo"
cwd = topdir
call_scrapy_command(str(cwd), "startproject", project_name)
cwd /= project_name
(cwd / project_name / "spiders" / "spider.py").write_text(spider_text or """
from scrapy import Spider

class MySpider(Spider):
name = "myspider"
""")
return cwd
2 changes: 2 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@ deps =
hubstorage
packaging
py36-scrapy16: Scrapy==1.6
scrapy-spider-metadata; python_version >= "3.8"

commands =
pytest --verbose --cov=sh_scrapy --cov-report=term-missing --cov-report=html --cov-report=xml {posargs: sh_scrapy tests}
Loading