A Light in the ...
£51.77
In stock
"""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 = """
£51.77
In stock
£53.74
In stock
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()