"""Offline tests for scrape_to_csv.py: python3 -m unittest test_scrape_to_csv They run against a trimmed copy of one books.toscrape.com listing page, so they need no network. When you point the starter at another site, paste a trimmed page of that site into SAMPLE and keep the same checks. """ from __future__ import annotations import csv import io import os import tempfile import unittest import urllib.error from email.message import Message from unittest import mock import scrape_to_csv as starter SAMPLE = """
""" LAST_PAGE = SAMPLE.replace('', "").replace( "a-light-in-the-attic_1000", "sharp-objects_997").replace("tipping-the-velvet_999", "soumission_998") def headers(**values: str) -> Message: message = Message() for name, value in values.items(): message[name.replace("_", "-")] = value return message class FakeSite: """Serves pages from a dict, the way get() would, and records every address asked for.""" def __init__(self, pages: dict[str, tuple[int, str]]): self.pages = pages self.asked: list[str] = [] def __call__(self, url, user_agent, through_api=True): self.asked.append(url) status, text = self.pages.get(url, (404, "not found")) return status, headers(Content_Type="text/html; charset=utf-8"), text.encode("utf-8") class ParsePageTest(unittest.TestCase): def test_reads_every_card_and_the_next_page(self): rows, next_url = starter.parse_page(SAMPLE, "https://books.toscrape.com/") self.assertEqual(len(rows), 2) self.assertEqual(rows[0]["title"], "A Light in the Attic") self.assertEqual(rows[0]["price"], "£51.77") self.assertEqual(rows[0]["rating"], "Three") self.assertEqual(rows[0]["in_stock"], "In stock") self.assertEqual(rows[0]["product_url"], "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html") self.assertEqual(next_url, "https://books.toscrape.com/catalogue/page-2.html") def test_last_page_has_no_next(self): _, next_url = starter.parse_page(LAST_PAGE, "https://books.toscrape.com/catalogue/page-2.html") self.assertIsNone(next_url) class CheckRowTest(unittest.TestCase): def raw(self, **changes: str) -> dict[str, str]: row = {"title": "A Light in the Attic", "price": "£51.77", "rating": "Three", "in_stock": "In stock", "product_url": "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html"} row.update(changes) return row def test_types_follow_the_schema(self): row = starter.check_row(self.raw()) self.assertEqual((row["price"], row["currency"], row["rating"], row["in_stock"]), ("51.77", "GBP", "3", "yes")) def test_refuses_a_row_that_does_not_fit(self): for change, field in [({"title": " "}, "title"), ({"price": "call us"}, "price"), ({"rating": "Six"}, "rating"), ({"in_stock": ""}, "stock"), ({"product_url": "catalogue/x.html"}, "product_url")]: with self.subTest(field=field), self.assertRaisesRegex(starter.RowError, field): starter.check_row(self.raw(**change)) def test_names_a_character_set_mistake(self): # What a page sent as UTF-8 looks like when read as Latin-1: the £ arrives as "£". with self.assertRaisesRegex(starter.RowError, "character set"): starter.check_row(self.raw(price="£51.77")) class ScrapeTest(unittest.TestCase): def setUp(self): self.folder = tempfile.TemporaryDirectory() self.out = os.path.join(self.folder.name, "books.csv") def tearDown(self): self.folder.cleanup() def test_follows_pagination_into_one_csv(self): site = FakeSite({ "https://books.toscrape.com/": (200, SAMPLE), "https://books.toscrape.com/catalogue/page-2.html": (200, LAST_PAGE), }) pauses: list[float] = [] result = starter.scrape("https://books.toscrape.com/", self.out, fetch=site, sleep=pauses.append) self.assertEqual(result, {"pages": 2, "rows": 4, "refused": 0}) self.assertEqual(pauses, [starter.DELAY_SECONDS]) # one pause, between the two pages self.assertEqual(site.asked[0], "https://books.toscrape.com/robots.txt") with open(self.out, newline="", encoding="utf-8") as handle: reader = csv.DictReader(handle) self.assertEqual(reader.fieldnames, starter.FIELDS) rows = list(reader) self.assertEqual([r["listing_url"] for r in rows], ["https://books.toscrape.com/"] * 2 + ["https://books.toscrape.com/catalogue/page-2.html"] * 2) self.assertFalse(os.path.exists(self.out + ".part")) def test_obeys_robots_txt(self): site = FakeSite({"https://books.toscrape.com/robots.txt": (200, "User-agent: *\nDisallow: /\n"), "https://books.toscrape.com/": (200, SAMPLE)}) with self.assertRaises(starter.Refused): starter.scrape("https://books.toscrape.com/", self.out, fetch=site, sleep=lambda s: None) self.assertEqual(site.asked, ["https://books.toscrape.com/robots.txt"]) def test_a_longer_crawl_delay_wins(self): site = FakeSite({"https://books.toscrape.com/robots.txt": (200, "User-agent: *\nCrawl-delay: 5\n"), "https://books.toscrape.com/": (200, SAMPLE), "https://books.toscrape.com/catalogue/page-2.html": (200, LAST_PAGE)}) pauses: list[float] = [] starter.scrape("https://books.toscrape.com/", self.out, fetch=site, sleep=pauses.append) self.assertEqual(pauses, [5.0]) def test_stops_loudly_when_the_layout_changes(self): site = FakeSite({"https://books.toscrape.com/": (200, "

Please enable JavaScript

")}) with self.assertRaises(starter.LayoutChanged): starter.scrape("https://books.toscrape.com/", self.out, fetch=site, sleep=lambda s: None) def test_a_block_is_an_error_not_an_empty_file(self): site = FakeSite({"https://books.toscrape.com/": (403, "Forbidden")}) with self.assertRaisesRegex(starter.FetchError, "403"): starter.scrape("https://books.toscrape.com/", self.out, fetch=site, sleep=lambda s: None) self.assertFalse(os.path.exists(self.out)) class FakeResponse(io.BytesIO): def __init__(self, body: bytes, status: int = 200): super().__init__(body) self.status = status self.headers = headers(Content_Type="text/html; charset=utf-8") class GetTest(unittest.TestCase): def opener(self, answers): calls = [] def open_(request, timeout): calls.append(request.full_url) self.sent = dict(request.header_items()) answer = answers.pop(0) if isinstance(answer, Exception): raise answer return answer return open_, calls def test_waits_as_long_as_the_site_asks_then_retries(self): busy = urllib.error.HTTPError("https://example.com/", 503, "busy", headers(Retry_After="7"), io.BytesIO(b"")) open_, calls = self.opener([busy, FakeResponse(b"ok")]) pauses: list[float] = [] status, _, body = starter.get("https://example.com/", "test", opener=open_, sleep=pauses.append) self.assertEqual((status, body, pauses, len(calls)), (200, b"ok", [7.0], 2)) def test_a_missing_page_is_not_retried(self): gone = urllib.error.HTTPError("https://example.com/", 404, "gone", headers(), io.BytesIO(b"")) open_, calls = self.opener([gone]) status, _, _ = starter.get("https://example.com/", "test", opener=open_, sleep=lambda s: None) self.assertEqual((status, len(calls)), (404, 1)) def test_gives_up_after_the_last_attempt(self): open_, calls = self.opener([TimeoutError()] * starter.MAX_ATTEMPTS) with self.assertRaises(starter.FetchError): starter.get("https://example.com/", "test", opener=open_, sleep=lambda s: None) self.assertEqual(len(calls), starter.MAX_ATTEMPTS) def test_stops_when_the_site_asks_for_a_long_pause(self): busy = urllib.error.HTTPError("https://example.com/", 429, "slow down", headers(Retry_After="3600"), io.BytesIO(b"")) open_, _ = self.opener([busy]) with self.assertRaisesRegex(starter.FetchError, "3600 s"): starter.get("https://example.com/", "test", opener=open_, sleep=lambda s: None) def test_an_api_gets_the_page_address_and_logs_never_show_the_key(self): env = {"SCRAPER_API_URL": "https://api.example.com/?api_key={key}&url={url}&render=true", "SCRAPER_API_KEY": "secret"} open_, calls = self.opener([TimeoutError()] * starter.MAX_ATTEMPTS) with mock.patch.dict(os.environ, env), mock.patch.object(starter, "log") as log: with self.assertRaises(starter.FetchError) as raised: starter.get("https://books.toscrape.com/?a=1", "test", opener=open_, sleep=lambda s: None) self.assertEqual(calls[0], "https://api.example.com/?api_key=secret&url=https%3A%2F%2Fbooks.toscrape.com%2F%3Fa%3D1&render=true") logged = " ".join(str(call) for call in log.call_args_list) + str(raised.exception) self.assertNotIn("secret", logged) self.assertNotIn("Authorization", self.sent) def test_an_api_that_wants_the_key_in_a_header_gets_it_there(self): env = {"SCRAPER_API_URL": "https://api.example.com/v1?url={url}", "SCRAPER_API_KEY": "secret"} open_, calls = self.opener([FakeResponse(b"ok")]) with mock.patch.dict(os.environ, env): starter.get("https://books.toscrape.com/", "test", opener=open_, sleep=lambda s: None) self.assertEqual(calls, ["https://api.example.com/v1?url=https%3A%2F%2Fbooks.toscrape.com%2F"]) self.assertEqual(self.sent.get("Authorization"), "Bearer secret") def test_robots_txt_is_read_from_the_site_not_through_the_api(self): env = {"SCRAPER_API_URL": "https://api.example.com/?api_key={key}&url={url}", "SCRAPER_API_KEY": "secret"} open_, calls = self.opener([FakeResponse(b"User-agent: *\nAllow: /\n")]) with mock.patch.dict(os.environ, env): starter.load_robots("https://books.toscrape.com/", "test", lambda u, a, through_api=True: starter.get(u, a, through_api=through_api, opener=open_)) self.assertEqual(calls, ["https://books.toscrape.com/robots.txt"]) if __name__ == "__main__": unittest.main()