Add tests for the Wikipedia picture downloader
This commit is contained in:
1 parent
83da0011fa
commit
7ca2394312
1 file changed
+364
@@ -0,0 +1,364 @@
|
|||||||
|
"""Tests for download_saint_pictures.py.
|
||||||
|
|
||||||
|
No test here touches the network or the real pics/ folder. Wikipedia is
|
||||||
|
replaced by FakeWikipedia, which answers the same API queries with the same
|
||||||
|
JSON shapes the real one returns, and the script's files are moved into a
|
||||||
|
temporary folder.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import download_saint_pictures as downloader
|
||||||
|
|
||||||
|
CSV_HEADER = "Date,Saint Name,French Name,Notes\n"
|
||||||
|
API_URL = "https://en.wikipedia.org/w/api.php"
|
||||||
|
COMMONS = "https://upload.wikimedia.org/wikipedia/commons"
|
||||||
|
|
||||||
|
|
||||||
|
# --- Fake Wikipedia --------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, status_code, json_data=None, content=b""):
|
||||||
|
self.status_code = status_code
|
||||||
|
self._json_data = json_data
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
if self.status_code >= 400:
|
||||||
|
raise requests.HTTPError(f"{self.status_code} Client Error")
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._json_data
|
||||||
|
|
||||||
|
|
||||||
|
class FakeWikipedia:
|
||||||
|
"""Stands in for the Wikipedia API and the Wikimedia image server.
|
||||||
|
|
||||||
|
Tests describe the pages that exist with add_page(). Like the real
|
||||||
|
servers, it refuses requests without a descriptive User-Agent, reports
|
||||||
|
unknown pages as missing, and only returns a resized 'thumburl' when the
|
||||||
|
request asks for a width.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.page_images = {} # article title -> image file name
|
||||||
|
self.image_info = {} # image file name -> imageinfo dict
|
||||||
|
self.image_bytes = {} # image URL -> file contents
|
||||||
|
self.titles_requested = []
|
||||||
|
self.unreachable = False
|
||||||
|
|
||||||
|
def add_page(self, title, image_name=None, thumb_url=None, original_url=None):
|
||||||
|
self.page_images[title] = image_name
|
||||||
|
if image_name:
|
||||||
|
info = {"url": original_url, "descriptionurl": f"{COMMONS}/{image_name}"}
|
||||||
|
if thumb_url:
|
||||||
|
info |= {"thumburl": thumb_url, "thumbwidth": 500}
|
||||||
|
self.image_info[image_name] = info
|
||||||
|
self.image_bytes[thumb_url or original_url] = f"<{image_name}>".encode()
|
||||||
|
|
||||||
|
def get(self, session, url, params=None, headers=None, timeout=None):
|
||||||
|
if self.unreachable:
|
||||||
|
raise requests.ConnectionError("Failed to establish a new connection")
|
||||||
|
if not session.headers.get("User-Agent", "").startswith(
|
||||||
|
"SaintsPictureDownloader/"
|
||||||
|
):
|
||||||
|
return FakeResponse(403)
|
||||||
|
if url == API_URL and params["prop"] == "pageimages":
|
||||||
|
return FakeResponse(200, self._page_query(params["titles"]))
|
||||||
|
if url == API_URL and params["prop"] == "imageinfo":
|
||||||
|
return FakeResponse(200, self._file_query(params))
|
||||||
|
if url in self.image_bytes:
|
||||||
|
return FakeResponse(200, content=self.image_bytes[url])
|
||||||
|
return FakeResponse(404)
|
||||||
|
|
||||||
|
def _page_query(self, title):
|
||||||
|
self.titles_requested.append(title)
|
||||||
|
if title not in self.page_images:
|
||||||
|
return {
|
||||||
|
"query": {"pages": {"-1": {"ns": 0, "title": title, "missing": ""}}}
|
||||||
|
}
|
||||||
|
page = {"pageid": 4242, "ns": 0, "title": title}
|
||||||
|
if self.page_images[title]:
|
||||||
|
page["pageimage"] = self.page_images[title]
|
||||||
|
return {"batchcomplete": "", "query": {"pages": {"4242": page}}}
|
||||||
|
|
||||||
|
def _file_query(self, params):
|
||||||
|
image_name = params["titles"].removeprefix("File:")
|
||||||
|
info = dict(self.image_info[image_name])
|
||||||
|
if "iiurlwidth" not in params:
|
||||||
|
info.pop("thumburl", None)
|
||||||
|
info.pop("thumbwidth", None)
|
||||||
|
# Commons files show as "missing" (-1) from English Wikipedia.
|
||||||
|
page = {
|
||||||
|
"ns": 6,
|
||||||
|
"title": params["titles"],
|
||||||
|
"missing": "",
|
||||||
|
"known": "",
|
||||||
|
"imagerepository": "shared",
|
||||||
|
"imageinfo": [info],
|
||||||
|
}
|
||||||
|
return {"query": {"pages": {"-1": page}}}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def wikipedia(monkeypatch):
|
||||||
|
"""Route every requests.Session.get call to a FakeWikipedia."""
|
||||||
|
wiki = FakeWikipedia()
|
||||||
|
|
||||||
|
def fake_get(session, url, **kwargs):
|
||||||
|
return wiki.get(session, url, **kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(requests.Session, "get", fake_get)
|
||||||
|
return wiki
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def project_dir(tmp_path, monkeypatch):
|
||||||
|
"""Make the script read its CSV and write pics/ inside tmp_path."""
|
||||||
|
monkeypatch.setattr(
|
||||||
|
downloader, "__file__", str(tmp_path / "download_saint_pictures.py")
|
||||||
|
)
|
||||||
|
(tmp_path / "pics").mkdir()
|
||||||
|
return tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def no_waiting(monkeypatch):
|
||||||
|
"""Skip the polite pauses between requests so tests run instantly."""
|
||||||
|
monkeypatch.setattr(downloader.time, "sleep", lambda seconds: None)
|
||||||
|
|
||||||
|
|
||||||
|
def write_csv(project_dir, rows):
|
||||||
|
(project_dir / "saints_days_france.csv").write_text(
|
||||||
|
CSV_HEADER + "".join(row + "\n" for row in rows), encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def thumb(name):
|
||||||
|
return f"{COMMONS}/thumb/a/ab/{name}/500px-{name}"
|
||||||
|
|
||||||
|
|
||||||
|
# --- get_all_saints --------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_saints_are_unique_sorted_and_exclude_feast_days(project_dir):
|
||||||
|
write_csv(
|
||||||
|
project_dir,
|
||||||
|
[
|
||||||
|
"January 21,Agnes,Sainte Agnès,",
|
||||||
|
"January 6,Epiphany,Épiphanie,Solemnity",
|
||||||
|
"January 20,Sebastian,Saint Sébastien,",
|
||||||
|
"January 20,Fabian,Saint Fabien,",
|
||||||
|
"December 21,Agnes,Sainte Agnès,",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert downloader.get_all_saints() == ["Agnes", "Fabian", "Sebastian"]
|
||||||
|
|
||||||
|
|
||||||
|
# --- get_wikipedia_image_url -----------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_url_is_500px_thumbnail_of_page_image(wikipedia):
|
||||||
|
wikipedia.add_page(
|
||||||
|
"Agnes of Rome",
|
||||||
|
image_name="Saint_Agnes.jpg",
|
||||||
|
thumb_url=thumb("Saint_Agnes.jpg"),
|
||||||
|
original_url=f"{COMMONS}/a/ab/Saint_Agnes.jpg",
|
||||||
|
)
|
||||||
|
|
||||||
|
image_url = downloader.get_wikipedia_image_url(
|
||||||
|
downloader.create_session(), "Agnes of Rome"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert image_url == f"{COMMONS}/thumb/a/ab/Saint_Agnes.jpg/500px-Saint_Agnes.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_url_falls_back_to_original_when_no_thumbnail(wikipedia):
|
||||||
|
wikipedia.add_page(
|
||||||
|
"Bede",
|
||||||
|
image_name="Bede.jpg",
|
||||||
|
original_url=f"{COMMONS}/b/bb/Bede.jpg",
|
||||||
|
)
|
||||||
|
|
||||||
|
image_url = downloader.get_wikipedia_image_url(downloader.create_session(), "Bede")
|
||||||
|
|
||||||
|
assert image_url == f"{COMMONS}/b/bb/Bede.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_url_is_none_when_page_does_not_exist(wikipedia):
|
||||||
|
image_url = downloader.get_wikipedia_image_url(
|
||||||
|
downloader.create_session(), "No Such Saint"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert image_url is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_url_is_none_when_page_has_no_image(wikipedia):
|
||||||
|
wikipedia.add_page("Agnes") # e.g. a disambiguation page
|
||||||
|
|
||||||
|
image_url = downloader.get_wikipedia_image_url(downloader.create_session(), "Agnes")
|
||||||
|
|
||||||
|
assert image_url is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_url_is_none_when_wikipedia_is_unreachable(wikipedia, capsys):
|
||||||
|
wikipedia.unreachable = True
|
||||||
|
|
||||||
|
image_url = downloader.get_wikipedia_image_url(downloader.create_session(), "Bede")
|
||||||
|
|
||||||
|
assert image_url is None
|
||||||
|
assert "Error fetching Wikipedia API" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_url_is_none_when_wikipedia_refuses_request(wikipedia):
|
||||||
|
# A plain session has no User-Agent, so the fake refuses it with a 403.
|
||||||
|
image_url = downloader.get_wikipedia_image_url(requests.Session(), "Bede")
|
||||||
|
|
||||||
|
assert image_url is None
|
||||||
|
|
||||||
|
|
||||||
|
# --- download_image --------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_download_saves_image_bytes_to_file(wikipedia, tmp_path):
|
||||||
|
wikipedia.add_page("Bede", image_name="Bede.jpg", thumb_url=thumb("Bede.jpg"))
|
||||||
|
filepath = tmp_path / "Bede.jpg"
|
||||||
|
|
||||||
|
saved = downloader.download_image(
|
||||||
|
downloader.create_session(), thumb("Bede.jpg"), filepath
|
||||||
|
)
|
||||||
|
|
||||||
|
assert saved is True
|
||||||
|
assert filepath.read_bytes() == b"<Bede.jpg>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_download_writes_nothing_when_image_is_missing(wikipedia, tmp_path, capsys):
|
||||||
|
filepath = tmp_path / "Bede.jpg"
|
||||||
|
|
||||||
|
saved = downloader.download_image(
|
||||||
|
downloader.create_session(), thumb("Gone.jpg"), filepath
|
||||||
|
)
|
||||||
|
|
||||||
|
assert saved is False
|
||||||
|
assert not filepath.exists()
|
||||||
|
assert "Error downloading image: 404" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
# --- main (running the script) ---------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_script_saves_each_saints_picture_named_after_saint(
|
||||||
|
project_dir, wikipedia, no_waiting
|
||||||
|
):
|
||||||
|
write_csv(project_dir, ["January 13,Hilary of Poitiers,Saint Hilaire,"])
|
||||||
|
wikipedia.add_page(
|
||||||
|
"Hilary of Poitiers", image_name="Hilary.jpg", thumb_url=thumb("Hilary.jpg")
|
||||||
|
)
|
||||||
|
|
||||||
|
downloader.main()
|
||||||
|
|
||||||
|
picture = project_dir / "pics" / "Hilary_of_Poitiers.jpg"
|
||||||
|
assert picture.read_bytes() == b"<Hilary.jpg>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_script_skips_saints_that_already_have_a_picture(
|
||||||
|
project_dir, wikipedia, no_waiting
|
||||||
|
):
|
||||||
|
write_csv(project_dir, ["January 13,Hilary of Poitiers,Saint Hilaire,"])
|
||||||
|
(project_dir / "pics" / "Hilary_of_Poitiers.png").write_bytes(b"my own picture")
|
||||||
|
|
||||||
|
downloader.main()
|
||||||
|
|
||||||
|
assert wikipedia.titles_requested == []
|
||||||
|
assert (project_dir / "pics" / "Hilary_of_Poitiers.png").read_bytes() == (
|
||||||
|
b"my own picture"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_script_tries_alternate_titles_and_stops_at_first_with_image(
|
||||||
|
project_dir, wikipedia, no_waiting, monkeypatch
|
||||||
|
):
|
||||||
|
write_csv(project_dir, ["June 29,Peter and Paul,Saints Pierre et Paul,"])
|
||||||
|
monkeypatch.setattr(
|
||||||
|
downloader,
|
||||||
|
"ALTERNATE_TITLES",
|
||||||
|
{"Peter and Paul": ["Saint Peter", "Paul the Apostle"]},
|
||||||
|
)
|
||||||
|
wikipedia.add_page(
|
||||||
|
"Saint Peter", image_name="Peter.jpg", thumb_url=thumb("Peter.jpg")
|
||||||
|
)
|
||||||
|
wikipedia.add_page(
|
||||||
|
"Paul the Apostle", image_name="Paul.jpg", thumb_url=thumb("Paul.jpg")
|
||||||
|
)
|
||||||
|
|
||||||
|
downloader.main()
|
||||||
|
|
||||||
|
assert wikipedia.titles_requested == ["Peter and Paul", "Saint Peter"]
|
||||||
|
picture = project_dir / "pics" / "Peter_and_Paul.jpg"
|
||||||
|
assert picture.read_bytes() == b"<Peter.jpg>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_script_reports_saint_with_no_image_anywhere(
|
||||||
|
project_dir, wikipedia, no_waiting, capsys
|
||||||
|
):
|
||||||
|
write_csv(project_dir, ["November 23,Clement I,Saint Clément Ier,"])
|
||||||
|
|
||||||
|
downloader.main()
|
||||||
|
|
||||||
|
assert list((project_dir / "pics").iterdir()) == []
|
||||||
|
assert " No image found on Wikipedia\n" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_script_summary_counts_downloaded_skipped_and_failed(
|
||||||
|
project_dir, wikipedia, no_waiting, capsys
|
||||||
|
):
|
||||||
|
write_csv(
|
||||||
|
project_dir,
|
||||||
|
[
|
||||||
|
"January 13,Hilary of Poitiers,Saint Hilaire,",
|
||||||
|
"January 20,Fabian,Saint Fabien,",
|
||||||
|
"January 21,Agnes,Sainte Agnès,",
|
||||||
|
"November 23,Clement I,Saint Clément Ier,",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
(project_dir / "pics" / "Agnes.jpg").write_bytes(b"already here")
|
||||||
|
wikipedia.add_page(
|
||||||
|
"Hilary of Poitiers", image_name="Hilary.jpg", thumb_url=thumb("Hilary.jpg")
|
||||||
|
)
|
||||||
|
wikipedia.add_page("Fabian", image_name="Fabian.jpg", thumb_url=thumb("Fabian.jpg"))
|
||||||
|
|
||||||
|
downloader.main()
|
||||||
|
|
||||||
|
last_line = capsys.readouterr().out.splitlines()[-1]
|
||||||
|
assert last_line == "Done! Downloaded: 2, Skipped: 1, Failed: 1"
|
||||||
|
|
||||||
|
|
||||||
|
# `parametrize` runs the same test once per row below, so each URL shape
|
||||||
|
# gets its own pass/fail line in the report.
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"image_url, expected_file",
|
||||||
|
[
|
||||||
|
(f"{COMMONS}/thumb/a/ab/Bede.png/500px-Bede.png", "Bede.png"),
|
||||||
|
(f"{COMMONS}/thumb/a/ab/Bede.jpeg/500px-Bede.jpeg", "Bede.jpeg"),
|
||||||
|
# Thumbnails of SVGs are PNGs.
|
||||||
|
(f"{COMMONS}/thumb/a/ab/Bede.svg/500px-Bede.svg.png", "Bede.png"),
|
||||||
|
# Upper-case extensions are saved lower-case, because the daily
|
||||||
|
# script only looks for lower-case ones.
|
||||||
|
(f"{COMMONS}/a/ab/Bede.JPG", "Bede.jpg"),
|
||||||
|
# Anything unrecognised falls back to .jpg.
|
||||||
|
(f"{COMMONS}/a/ab/Bede.tiff", "Bede.jpg"),
|
||||||
|
],
|
||||||
|
ids=["png", "jpeg", "svg-thumbnail", "upper-case-jpg", "unknown-tiff"],
|
||||||
|
)
|
||||||
|
def test_script_names_picture_file_with_extension_from_image_url(
|
||||||
|
project_dir, wikipedia, no_waiting, image_url, expected_file
|
||||||
|
):
|
||||||
|
write_csv(project_dir, ["May 25,Bede,Saint Bède le Vénérable,"])
|
||||||
|
wikipedia.add_page("Bede", image_name="Bede", original_url=image_url)
|
||||||
|
|
||||||
|
downloader.main()
|
||||||
|
|
||||||
|
assert [p.name for p in (project_dir / "pics").iterdir()] == [expected_file]
|
||||||
Reference in new issue
Block a user