mocklet-pytest 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ """Public helpers for the Mocklet pytest plugin."""
2
+
3
+ from pathlib import Path
4
+ from typing import Union
5
+
6
+ import pytest
7
+
8
+ from .runtime import Mocklet
9
+
10
+ PathLike = Union[str, Path]
11
+
12
+
13
+ def baseline(har_path: PathLike) -> pytest.MarkDecorator:
14
+ """Mark a test to start its Mocklet HAR baseline before the fixture runs."""
15
+
16
+ return pytest.mark.mocklet_baseline(str(har_path))
17
+
18
+
19
+ __all__ = ["Mocklet", "baseline"]
@@ -0,0 +1,30 @@
1
+ """Pytest registration and fixture lifecycle."""
2
+
3
+ from collections.abc import Generator
4
+
5
+ import pytest
6
+
7
+ from .runtime import Mocklet
8
+
9
+
10
+ def pytest_configure(config: pytest.Config) -> None:
11
+ config.addinivalue_line(
12
+ "markers",
13
+ "mocklet_baseline(path): replay responses from a HAR baseline for this test",
14
+ )
15
+
16
+
17
+ @pytest.fixture
18
+ def mocklet(request: pytest.FixtureRequest) -> Generator[Mocklet, None, None]:
19
+ """Start, expose, and reliably stop a HAR-backed Mocklet server."""
20
+
21
+ client = Mocklet()
22
+ marker = request.node.get_closest_marker("mocklet_baseline")
23
+ if marker is not None:
24
+ if len(marker.args) != 1 or marker.kwargs:
25
+ raise pytest.UsageError("@mocklet.baseline requires exactly one HAR path")
26
+ client.baseline(marker.args[0])
27
+ try:
28
+ yield client
29
+ finally:
30
+ client.close()
@@ -0,0 +1,176 @@
1
+ """Process adapter around the Mocklet CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import queue
8
+ import subprocess
9
+ import tempfile
10
+ import threading
11
+ from pathlib import Path
12
+ from typing import Any, Optional
13
+ from urllib.parse import urlparse
14
+
15
+ import pytest
16
+
17
+ # `mocklet drift check` exits 3 when the response drifted from the baseline.
18
+ EXIT_DRIFT = 3
19
+
20
+
21
+ class Mocklet:
22
+ """Manage one HAR replay process and validate observed responses."""
23
+
24
+ def __init__(self, executable: Optional[str] = None, timeout: float = 10.0) -> None:
25
+ self.executable = executable or os.environ.get("MOCKLET_CLI", "mocklet")
26
+ self.timeout = timeout
27
+ self.baseline_path: Optional[Path] = None
28
+ self.url: Optional[str] = None
29
+ self._process: Optional[subprocess.Popen[str]] = None
30
+
31
+ def baseline(self, har_path: os.PathLike[str] | str) -> str:
32
+ """Start replaying *har_path* and return the isolated server URL."""
33
+
34
+ self.close()
35
+ path = Path(har_path).expanduser().resolve()
36
+ if not path.is_file():
37
+ raise pytest.UsageError(f"Mocklet HAR baseline does not exist: {path}")
38
+ command = [
39
+ self.executable,
40
+ "mock",
41
+ "serve",
42
+ str(path),
43
+ "--listen",
44
+ "127.0.0.1:0",
45
+ "--output",
46
+ "json",
47
+ ]
48
+ try:
49
+ process = subprocess.Popen(
50
+ command,
51
+ stdout=subprocess.PIPE,
52
+ stderr=subprocess.PIPE,
53
+ text=True,
54
+ bufsize=1,
55
+ )
56
+ except FileNotFoundError as error:
57
+ raise pytest.UsageError(
58
+ f"Mocklet CLI {self.executable!r} was not found; "
59
+ "install mocklet (https://gitlab.com/keystr0ke/mocklet_cli/-/releases) or set MOCKLET_CLI"
60
+ ) from error
61
+ self._process = process
62
+ line = self._readline(process)
63
+ if not line:
64
+ self.close()
65
+ stderr = process.stderr.read().strip() if process.stderr else ""
66
+ raise pytest.UsageError(f"Mocklet replay server failed to start: {stderr or 'no readiness output'}")
67
+ try:
68
+ ready = json.loads(line)
69
+ ready_url = ready["url"]
70
+ parsed_url = urlparse(ready_url) if isinstance(ready_url, str) else None
71
+ if parsed_url is None or parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc:
72
+ raise ValueError("readiness URL must be an absolute HTTP URL")
73
+ self.url = ready_url
74
+ except (ValueError, KeyError, TypeError) as error:
75
+ self.close()
76
+ raise pytest.UsageError(f"Invalid readiness output from mocklet mock serve: {line.strip()}") from error
77
+ self.baseline_path = path
78
+ return self.url
79
+
80
+ def assert_no_drift(
81
+ self,
82
+ actual_response: Any,
83
+ *,
84
+ method: Optional[str] = None,
85
+ url: Optional[str] = None,
86
+ status: Optional[int] = None,
87
+ ) -> None:
88
+ """Fail the current test with the CLI's path-oriented drift report."""
89
+
90
+ if self.baseline_path is None:
91
+ raise pytest.UsageError("Call mocklet.baseline(path) or use @mocklet.baseline(path) first")
92
+ body, method, url, status = self._response_parts(actual_response, method, url, status)
93
+ file_descriptor, actual_path = tempfile.mkstemp(prefix="mocklet-actual-", suffix=".json")
94
+ try:
95
+ with os.fdopen(file_descriptor, "wb") as actual_file:
96
+ actual_file.write(body)
97
+ command = [
98
+ self.executable,
99
+ "drift",
100
+ "check",
101
+ "--baseline",
102
+ str(self.baseline_path),
103
+ "--actual",
104
+ actual_path,
105
+ "--non-interactive",
106
+ "--no-color",
107
+ ]
108
+ self._append_option(command, "--method", method)
109
+ self._append_option(command, "--url", url)
110
+ self._append_option(command, "--status", status)
111
+ try:
112
+ result = subprocess.run(command, capture_output=True, text=True, timeout=self.timeout, check=False)
113
+ except FileNotFoundError as error:
114
+ raise pytest.UsageError(f"Mocklet CLI {self.executable!r} was not found") from error
115
+ except subprocess.TimeoutExpired as error:
116
+ raise pytest.UsageError(f"Mocklet drift check exceeded {self.timeout:g}s") from error
117
+ if result.returncode == EXIT_DRIFT:
118
+ pytest.fail(result.stdout.strip() or "Mocklet detected response drift", pytrace=False)
119
+ if result.returncode != 0:
120
+ detail = result.stderr.strip() or result.stdout.strip() or "unknown error"
121
+ raise pytest.UsageError(f"mocklet drift check failed (exit {result.returncode}): {detail}")
122
+ finally:
123
+ Path(actual_path).unlink(missing_ok=True)
124
+
125
+ def close(self) -> None:
126
+ """Stop the replay child process. Calling this repeatedly is safe."""
127
+
128
+ process, self._process = self._process, None
129
+ self.url = None
130
+ self.baseline_path = None
131
+ if process is None or process.poll() is not None:
132
+ return
133
+ process.terminate()
134
+ try:
135
+ process.wait(timeout=5)
136
+ except subprocess.TimeoutExpired:
137
+ process.kill()
138
+ process.wait(timeout=5)
139
+
140
+ def _readline(self, process: subprocess.Popen[str]) -> str:
141
+ if process.stdout is None:
142
+ return ""
143
+ output: queue.Queue[str] = queue.Queue(maxsize=1)
144
+ reader = threading.Thread(target=lambda: output.put(process.stdout.readline()), daemon=True)
145
+ reader.start()
146
+ try:
147
+ return output.get(timeout=self.timeout)
148
+ except queue.Empty as error:
149
+ self.close()
150
+ raise pytest.UsageError(f"Mocklet replay server did not become ready within {self.timeout:g}s") from error
151
+
152
+ @staticmethod
153
+ def _append_option(command: list[str], option: str, value: Any) -> None:
154
+ if value is not None:
155
+ command.extend((option, str(value)))
156
+
157
+ @staticmethod
158
+ def _response_parts(
159
+ response: Any,
160
+ method: Optional[str],
161
+ url: Optional[str],
162
+ status: Optional[int],
163
+ ) -> tuple[bytes, Optional[str], Optional[str], Optional[int]]:
164
+ if hasattr(response, "content"):
165
+ content = response.content
166
+ body = content if isinstance(content, bytes) else str(content).encode()
167
+ status = status if status is not None else getattr(response, "status_code", None)
168
+ url = url or getattr(response, "url", None)
169
+ request = getattr(response, "request", None)
170
+ method = method or getattr(request, "method", None)
171
+ return body, method, url, status
172
+ if isinstance(response, bytes):
173
+ return response, method, url, status
174
+ if isinstance(response, str):
175
+ return response.encode(), method, url, status
176
+ return json.dumps(response, separators=(",", ":")).encode(), method, url, status
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: mocklet-pytest
3
+ Version: 0.1.0
4
+ Summary: HAR replay and response-drift assertions for pytest
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://gitlab.com/keystr0ke/mocklet-pytest
7
+ Project-URL: Issues, https://gitlab.com/keystr0ke/mocklet-pytest/-/issues
8
+ Project-URL: Mocklet CLI, https://gitlab.com/keystr0ke/mocklet_cli
9
+ Keywords: pytest,har,contract-testing,api-drift,mocklet
10
+ Classifier: Framework :: Pytest
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Testing
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pytest>=7
17
+ Dynamic: license-file
18
+
19
+ # mocklet-pytest
20
+
21
+ pytest plugin that replays a recorded HAR file and fails a test when a live API
22
+ response drifts from it. It runs on the
23
+ [Mocklet CLI](https://gitlab.com/keystr0ke/mocklet_cli), the same engine that
24
+ powers `mocklet drift check` in CI and the Insomnia plugin, so a drift report
25
+ reads the same everywhere:
26
+
27
+ ```text
28
+ DRIFT DETECTED
29
+ endpoint: GET /users/1
30
+ - response.body.email: expected string
31
+ + response.body.email: missing
32
+ - response.body.id: expected integer
33
+ + response.body.id: actual string
34
+ ```
35
+
36
+ ## Install
37
+
38
+ ```shell
39
+ pip install mocklet-pytest
40
+ ```
41
+
42
+ The plugin registers itself with pytest. Put `mocklet` 0.3.0 or newer on
43
+ `PATH`, or point `MOCKLET_CLI` at it. In CI:
44
+
45
+ ```shell
46
+ VERSION=0.3.0
47
+ curl -fsSL "https://gitlab.com/keystr0ke/mocklet_cli/-/releases/v${VERSION}/downloads/mocklet_${VERSION}_linux_amd64.tar.gz" \
48
+ | tar -xz -C /usr/local/bin mocklet
49
+ ```
50
+
51
+ Builds for Linux, macOS and Windows (amd64 and arm64) and their
52
+ `checksums.txt` are on the [releases page](https://gitlab.com/keystr0ke/mocklet_cli/-/releases).
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ import requests
58
+
59
+ import mocklet_pytest as mocklet
60
+
61
+
62
+ @mocklet.baseline("checkout.har")
63
+ def test_checkout(mocklet):
64
+ # The recording is replayed on a free loopback port.
65
+ replayed = requests.get(f"{mocklet.url}/checkout?currency=EUR")
66
+ assert replayed.status_code == 200
67
+
68
+ # Check a live response against the same recording.
69
+ live = requests.get("https://staging.example.test/checkout?currency=EUR")
70
+ mocklet.assert_no_drift(live)
71
+ ```
72
+
73
+ `assert_no_drift` accepts a `requests` or `httpx` response and takes the
74
+ method, URL and status from it. For a plain body pass them explicitly:
75
+
76
+ ```python
77
+ mocklet.assert_no_drift(body, method="GET", url="/users/1", status=200)
78
+ ```
79
+
80
+ Drift fails the test with the report above; a broken HAR or a missing CLI is a
81
+ usage error, so it is not mistaken for drift. The HAR may hold many endpoints:
82
+ the response is compared with the recordings of the same method and path plus
83
+ query, ignoring the host. The shape is inferred from every recording of that
84
+ endpoint, so optional fields and varying values do not raise false alarms.
85
+
86
+ Without the marker call `mocklet.baseline(path)` inside the test. The replay
87
+ server is stopped after every test, including failed ones.
88
+
89
+ ## Development
90
+
91
+ ```shell
92
+ pip install -e . ruff build
93
+ pytest # unit tests
94
+ MOCKLET_CLI=/path/to/mocklet pytest # plus tests against the real CLI
95
+ ruff check . && ruff format --check .
96
+ ```
97
+
98
+ Releases are published to PyPI by CI from `vX.Y.Z` tags through PyPI Trusted
99
+ Publishing.
@@ -0,0 +1,9 @@
1
+ mocklet_pytest/__init__.py,sha256=aZBbkOMuT3R-40orcJl54st0o4oP2b9VqT4sRpWT2Qg,410
2
+ mocklet_pytest/plugin.py,sha256=56nKwsaRBC-2HBtjjKQj1GxfBINjG1NuXikbRjxQofA,857
3
+ mocklet_pytest/runtime.py,sha256=8lO5zkgssqFxIQN4LD-tt542NVNVoRXly_6eQC9HMoI,7139
4
+ mocklet_pytest-0.1.0.dist-info/licenses/LICENSE,sha256=CJHy4H5rVGoiD_bWT8AG1Hn6sUgXSyreAwNde9BRzrg,1064
5
+ mocklet_pytest-0.1.0.dist-info/METADATA,sha256=UxQjGMl5yMQjv7emHbtNZu9e7zjHg71EU_RrJ0X43_E,3254
6
+ mocklet_pytest-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ mocklet_pytest-0.1.0.dist-info/entry_points.txt,sha256=z4EaqZnsu3BpCigdiqsfzSHg5r-alzfj5OpkydFneZc,43
8
+ mocklet_pytest-0.1.0.dist-info/top_level.txt,sha256=XPKlJQ907vISURxwCBv8_qSK3Gnov5MZSCKhr39gX14,15
9
+ mocklet_pytest-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ mocklet = mocklet_pytest.plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mocklet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ mocklet_pytest