Debian Codegraph @

tests/dcs_helpers.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Test harness for the codesearch CLI scripts under ``scripts/``.
18
19 Two facilities the codesearch-script tests share:
20
21 * ``load_script`` loads a script whose filename has hyphens (so it cannot be
22 imported by module name) via ``importlib``, keeping that boilerplate in one
23 place.
24 * ``FakeTransport`` / ``FakeResponse`` / ``make_http_error`` stand in for
25 ``urllib.request.urlopen`` so a test can exercise the network/retry/cache
26 paths offline - returning canned bytes or raising a chosen error, and
27 recording how many times it was called.
28
29 This module is support code, not a test module (its name matches neither
30 pytest ``test_*``/``*_test`` pattern), so pytest does not collect it.
31 """
32
33 from __future__ import annotations
34
35 import email.message
36 import importlib.util
37 import io
38 import sys
39 import urllib.error
40 from pathlib import Path
41 from types import ModuleType, TracebackType
42 from typing import Self
43
44 SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
45
46
47 def load_script(filename: str) -> ModuleType:
48 """Import a ``scripts/`` module whose filename has hyphens.
49
50 The module is registered in ``sys.modules`` under a name with hyphens
51 turned into underscores, then executed - which runs the script's own
52 ``sys.path`` bootstrap so its ``decopy`` / sibling imports resolve.
53 """
54 path = SCRIPTS_DIR / filename
55 mod_name = path.stem.replace("-", "_")
56 spec = importlib.util.spec_from_file_location(mod_name, path)
57 if spec is None or spec.loader is None:
58 msg = f"cannot build an import spec for {path}"
59 raise ImportError(msg)
60 module = importlib.util.module_from_spec(spec)
61 sys.modules[mod_name] = module
62 spec.loader.exec_module(module)
63 return module
64
65
66 class FakeResponse:
67 """Context-manager stand-in for a ``urlopen`` response."""
68
69 def __init__(self, data: bytes) -> None:
70 self._data = data
71
72 def __enter__(self) -> Self:
73 return self
74
75 def __exit__(
76 self,
77 exc_type: type[BaseException] | None,
78 exc: BaseException | None,
79 tb: TracebackType | None,
80 ) -> None:
81 return
82
83 def read(self, amt: int | None = None) -> bytes:
84 return self._data if amt is None else self._data[:amt]
85
86
87 class FakeTransport:
88 """Callable stand-in for ``urllib.request.urlopen``.
89
90 Configured with a list of steps consumed in order; each step is either
91 ``bytes`` (returned as a ``FakeResponse``) or an exception instance
92 (raised). When ``repeat`` is set the last step is reused once the list is
93 exhausted (handy for "always raises 503" retry tests); otherwise a further
94 call is a test error. ``calls`` records how many times it ran.
95 """
96
97 def __init__(
98 self, steps: list[bytes | BaseException], *, repeat: bool = False
99 ) -> None:
100 self._steps = list(steps)
101 self._repeat = repeat
102 self._last: bytes | BaseException | None = None
103 self.calls = 0
104
105 def __call__(self, req: object, timeout: float | None = None) -> FakeResponse:
106 self.calls += 1
107 if self._steps:
108 self._last = self._steps.pop(0)
109 elif not (self._repeat and self._last is not None):
110 msg = f"FakeTransport called {self.calls} times, more than configured"
111 raise AssertionError(msg)
112 step = self._last
113 if isinstance(step, BaseException):
114 raise step
115 assert step is not None
116 return FakeResponse(step)
117
118
119 def make_http_error(
120 code: int, *, retry_after: float | None = None, body: bytes = b""
121 ) -> urllib.error.HTTPError:
122 """Build an ``HTTPError`` with a chosen status, Retry-After and body."""
123 hdrs = email.message.Message()
124 if retry_after is not None:
125 hdrs["Retry-After"] = str(retry_after)
126 return urllib.error.HTTPError(
127 "https://codesearch.debian.net/api/v1/search",
128 code,
129 "test-induced error",
130 hdrs,
131 io.BytesIO(body),
132 )