|
| 1 | +"""Recording a site once so a spec can be tested without it. |
| 2 | +
|
| 3 | +A fixture turns spec repair into a deterministic loop: the same bytes every run, no network, no |
| 4 | +rate limit, and a diff that means the spec changed rather than the site did. That is what makes |
| 5 | +CI able to say a pull request broke something. |
| 6 | +
|
| 7 | +It is deliberately **not** a substitute for testing against the live site. A recorded page |
| 8 | +eventually stops resembling the real one, so a green fixture suite can mask a dead source. |
| 9 | +Fixtures test the spec; only a live run tests the site. |
| 10 | +
|
| 11 | +RFC-0001 leaves this format to the implementation, so it is one gzipped JSON document per host: |
| 12 | +the responses, and the result they produced when the spec was known good. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import gzip |
| 18 | +import json |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any, Dict, List, Optional, Tuple |
| 21 | + |
| 22 | +from sourcelib.fetch import Fetched, Fetcher |
| 23 | +from sourcelib.trial import COMPARED |
| 24 | + |
| 25 | +__all__ = [ |
| 26 | + "FIXTURE_NAME", |
| 27 | + "Recording", |
| 28 | + "RecordingFetcher", |
| 29 | + "ReplayFetcher", |
| 30 | + "compare", |
| 31 | + "hosts", |
| 32 | + "load", |
| 33 | + "path_for", |
| 34 | + "replay", |
| 35 | + "save", |
| 36 | +] |
| 37 | + |
| 38 | +#: One file per host. Gzipped because a recorded page is mostly repetitive markup. |
| 39 | +FIXTURE_NAME = "recording.json.gz" |
| 40 | + |
| 41 | + |
| 42 | +class Recording: |
| 43 | + """Responses captured from one host, and the result the spec produced from them.""" |
| 44 | + |
| 45 | + __slots__ = ("url", "pages", "expected") |
| 46 | + |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + url: str = "", |
| 50 | + pages: Optional[Dict[str, Dict[str, Any]]] = None, |
| 51 | + expected: Optional[Dict[str, Any]] = None, |
| 52 | + ) -> None: |
| 53 | + self.url = url |
| 54 | + self.pages = pages or {} |
| 55 | + self.expected = expected or {} |
| 56 | + |
| 57 | + def to_dict(self) -> Dict[str, Any]: |
| 58 | + return {"url": self.url, "pages": self.pages, "expected": self.expected} |
| 59 | + |
| 60 | + def fetcher(self) -> "ReplayFetcher": |
| 61 | + return ReplayFetcher(self.pages) |
| 62 | + |
| 63 | + |
| 64 | +class RecordingFetcher: |
| 65 | + """Wraps a Fetcher and keeps everything it retrieved.""" |
| 66 | + |
| 67 | + def __init__(self, inner: Fetcher) -> None: |
| 68 | + self.inner = inner |
| 69 | + self.pages: Dict[str, Dict[str, Any]] = {} |
| 70 | + |
| 71 | + def fetch(self, method: str, url: str, **options: Any) -> Fetched: |
| 72 | + response = self.inner.fetch(method, url, **options) |
| 73 | + self._keep(method, url, response) |
| 74 | + return response |
| 75 | + |
| 76 | + def render(self, url: str, *, wait_for: Optional[str] = None) -> Fetched: |
| 77 | + response = self.inner.render(url, wait_for=wait_for) |
| 78 | + self._keep("RENDER", url, response) |
| 79 | + return response |
| 80 | + |
| 81 | + def _keep(self, method: str, url: str, response: Fetched) -> None: |
| 82 | + # Keyed by the requested URL rather than the final one, because replay looks up what |
| 83 | + # the spec asked for, not where a redirect landed. |
| 84 | + self.pages[url] = { |
| 85 | + "method": method, |
| 86 | + "final_url": response.url, |
| 87 | + "status": response.status, |
| 88 | + "headers": dict(response.headers), |
| 89 | + "text": response.text, |
| 90 | + } |
| 91 | + |
| 92 | + |
| 93 | +class ReplayFetcher: |
| 94 | + """Answers from a recording, and says plainly when a spec asks for something unrecorded.""" |
| 95 | + |
| 96 | + def __init__(self, pages: Dict[str, Dict[str, Any]]) -> None: |
| 97 | + self.pages = pages |
| 98 | + self.missing: List[str] = [] |
| 99 | + |
| 100 | + def fetch(self, method: str, url: str, **options: Any) -> Fetched: |
| 101 | + entry = self.pages.get(url) |
| 102 | + if entry is None: |
| 103 | + self.missing.append(url) |
| 104 | + # A spec reaching a URL the recording does not hold usually means the spec changed |
| 105 | + # its request, which is worth reporting rather than silently passing. |
| 106 | + from sourcelib.fetch import FetchError |
| 107 | + |
| 108 | + raise FetchError( |
| 109 | + f"not in the recording: {url}. Re-record if the spec changed on purpose" |
| 110 | + ) |
| 111 | + return Fetched( |
| 112 | + url=entry.get("final_url") or url, |
| 113 | + text=entry.get("text", ""), |
| 114 | + headers=entry.get("headers") or {}, |
| 115 | + status=int(entry.get("status", 200)), |
| 116 | + ) |
| 117 | + |
| 118 | + def render(self, url: str, *, wait_for: Optional[str] = None) -> Fetched: |
| 119 | + return self.fetch("GET", url) |
| 120 | + |
| 121 | + |
| 122 | +def path_for(root: Path, host: str) -> Path: |
| 123 | + return Path(root) / "fixtures" / host / FIXTURE_NAME |
| 124 | + |
| 125 | + |
| 126 | +def save(root: Path, host: str, recording: Recording) -> Path: |
| 127 | + target = path_for(root, host) |
| 128 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 129 | + payload = json.dumps(recording.to_dict(), ensure_ascii=False, sort_keys=True).encode("utf-8") |
| 130 | + # mtime=0 so re-recording identical bytes produces an identical file rather than a diff. |
| 131 | + with gzip.GzipFile(filename=str(target), mode="wb", mtime=0) as handle: |
| 132 | + handle.write(payload) |
| 133 | + return target |
| 134 | + |
| 135 | + |
| 136 | +def load(root: Path, host: str) -> Recording: |
| 137 | + target = path_for(root, host) |
| 138 | + with gzip.open(target, "rb") as handle: |
| 139 | + data = json.loads(handle.read().decode("utf-8")) |
| 140 | + return Recording( |
| 141 | + url=data.get("url", ""), |
| 142 | + pages=data.get("pages") or {}, |
| 143 | + expected=data.get("expected") or {}, |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def hosts(root: Path) -> List[str]: |
| 148 | + """Every host with a recording, in order.""" |
| 149 | + folder = Path(root) / "fixtures" |
| 150 | + if not folder.is_dir(): |
| 151 | + return [] |
| 152 | + return sorted(p.parent.name for p in folder.glob(f"*/{FIXTURE_NAME}")) |
| 153 | + |
| 154 | + |
| 155 | +def compare(expected: Dict[str, Any], actual: Dict[str, Any]) -> List[str]: |
| 156 | + """Every difference between a recorded result and a fresh one, as readable lines.""" |
| 157 | + differences: List[str] = [] |
| 158 | + |
| 159 | + for name in (*COMPARED, "chapters", "volumes", "first_chapter", "last_chapter"): |
| 160 | + if name not in expected: |
| 161 | + continue |
| 162 | + was, now = expected[name], actual.get(name) |
| 163 | + if was != now: |
| 164 | + differences.append(f"{name}: expected {_short(was)}, got {_short(now)}") |
| 165 | + |
| 166 | + for was, now in zip(expected.get("bodies") or [], actual.get("bodies") or []): |
| 167 | + if was.get("characters") != now.get("characters"): |
| 168 | + differences.append( |
| 169 | + f"chapter {was.get('id')}: body was {was.get('characters')} characters, " |
| 170 | + f"now {now.get('characters')}" |
| 171 | + ) |
| 172 | + return differences |
| 173 | + |
| 174 | + |
| 175 | +def _short(value: Any) -> str: |
| 176 | + text = json.dumps(value, ensure_ascii=False) if not isinstance(value, str) else repr(value) |
| 177 | + return text if len(text) <= 60 else text[:59] + "…" |
| 178 | + |
| 179 | + |
| 180 | +def replay(root: Path, host: str, spec_path: Path, sample: int = 3) -> Tuple[bool, List[str]]: |
| 181 | + """Run a spec against its recording and report what differs.""" |
| 182 | + from sourcelib.trial import run_trial |
| 183 | + |
| 184 | + recording = load(root, host) |
| 185 | + trial = run_trial(spec_path, recording.url, recording.fetcher(), root=root, sample=sample) |
| 186 | + if trial.error: |
| 187 | + return False, [trial.error] |
| 188 | + differences = compare(recording.expected, trial.summary) |
| 189 | + return not differences, differences |
0 commit comments