mocklet-pytest 0.1.0__tar.gz
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.
- mocklet_pytest-0.1.0/LICENSE +21 -0
- mocklet_pytest-0.1.0/PKG-INFO +99 -0
- mocklet_pytest-0.1.0/README.md +81 -0
- mocklet_pytest-0.1.0/mocklet_pytest/__init__.py +19 -0
- mocklet_pytest-0.1.0/mocklet_pytest/plugin.py +30 -0
- mocklet_pytest-0.1.0/mocklet_pytest/runtime.py +176 -0
- mocklet_pytest-0.1.0/mocklet_pytest.egg-info/PKG-INFO +99 -0
- mocklet_pytest-0.1.0/mocklet_pytest.egg-info/SOURCES.txt +14 -0
- mocklet_pytest-0.1.0/mocklet_pytest.egg-info/dependency_links.txt +1 -0
- mocklet_pytest-0.1.0/mocklet_pytest.egg-info/entry_points.txt +2 -0
- mocklet_pytest-0.1.0/mocklet_pytest.egg-info/requires.txt +1 -0
- mocklet_pytest-0.1.0/mocklet_pytest.egg-info/top_level.txt +1 -0
- mocklet_pytest-0.1.0/pyproject.toml +38 -0
- mocklet_pytest-0.1.0/setup.cfg +4 -0
- mocklet_pytest-0.1.0/tests/test_integration.py +34 -0
- mocklet_pytest-0.1.0/tests/test_runtime.py +151 -0
|
@@ -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,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,81 @@
|
|
|
1
|
+
# mocklet-pytest
|
|
2
|
+
|
|
3
|
+
pytest plugin that replays a recorded HAR file and fails a test when a live API
|
|
4
|
+
response drifts from it. It runs on the
|
|
5
|
+
[Mocklet CLI](https://gitlab.com/keystr0ke/mocklet_cli), the same engine that
|
|
6
|
+
powers `mocklet drift check` in CI and the Insomnia plugin, so a drift report
|
|
7
|
+
reads the same everywhere:
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
DRIFT DETECTED
|
|
11
|
+
endpoint: GET /users/1
|
|
12
|
+
- response.body.email: expected string
|
|
13
|
+
+ response.body.email: missing
|
|
14
|
+
- response.body.id: expected integer
|
|
15
|
+
+ response.body.id: actual string
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```shell
|
|
21
|
+
pip install mocklet-pytest
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The plugin registers itself with pytest. Put `mocklet` 0.3.0 or newer on
|
|
25
|
+
`PATH`, or point `MOCKLET_CLI` at it. In CI:
|
|
26
|
+
|
|
27
|
+
```shell
|
|
28
|
+
VERSION=0.3.0
|
|
29
|
+
curl -fsSL "https://gitlab.com/keystr0ke/mocklet_cli/-/releases/v${VERSION}/downloads/mocklet_${VERSION}_linux_amd64.tar.gz" \
|
|
30
|
+
| tar -xz -C /usr/local/bin mocklet
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Builds for Linux, macOS and Windows (amd64 and arm64) and their
|
|
34
|
+
`checksums.txt` are on the [releases page](https://gitlab.com/keystr0ke/mocklet_cli/-/releases).
|
|
35
|
+
|
|
36
|
+
## Use
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import requests
|
|
40
|
+
|
|
41
|
+
import mocklet_pytest as mocklet
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@mocklet.baseline("checkout.har")
|
|
45
|
+
def test_checkout(mocklet):
|
|
46
|
+
# The recording is replayed on a free loopback port.
|
|
47
|
+
replayed = requests.get(f"{mocklet.url}/checkout?currency=EUR")
|
|
48
|
+
assert replayed.status_code == 200
|
|
49
|
+
|
|
50
|
+
# Check a live response against the same recording.
|
|
51
|
+
live = requests.get("https://staging.example.test/checkout?currency=EUR")
|
|
52
|
+
mocklet.assert_no_drift(live)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`assert_no_drift` accepts a `requests` or `httpx` response and takes the
|
|
56
|
+
method, URL and status from it. For a plain body pass them explicitly:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
mocklet.assert_no_drift(body, method="GET", url="/users/1", status=200)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Drift fails the test with the report above; a broken HAR or a missing CLI is a
|
|
63
|
+
usage error, so it is not mistaken for drift. The HAR may hold many endpoints:
|
|
64
|
+
the response is compared with the recordings of the same method and path plus
|
|
65
|
+
query, ignoring the host. The shape is inferred from every recording of that
|
|
66
|
+
endpoint, so optional fields and varying values do not raise false alarms.
|
|
67
|
+
|
|
68
|
+
Without the marker call `mocklet.baseline(path)` inside the test. The replay
|
|
69
|
+
server is stopped after every test, including failed ones.
|
|
70
|
+
|
|
71
|
+
## Development
|
|
72
|
+
|
|
73
|
+
```shell
|
|
74
|
+
pip install -e . ruff build
|
|
75
|
+
pytest # unit tests
|
|
76
|
+
MOCKLET_CLI=/path/to/mocklet pytest # plus tests against the real CLI
|
|
77
|
+
ruff check . && ruff format --check .
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Releases are published to PyPI by CI from `vX.Y.Z` tags through PyPI Trusted
|
|
81
|
+
Publishing.
|
|
@@ -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,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
mocklet_pytest/__init__.py
|
|
5
|
+
mocklet_pytest/plugin.py
|
|
6
|
+
mocklet_pytest/runtime.py
|
|
7
|
+
mocklet_pytest.egg-info/PKG-INFO
|
|
8
|
+
mocklet_pytest.egg-info/SOURCES.txt
|
|
9
|
+
mocklet_pytest.egg-info/dependency_links.txt
|
|
10
|
+
mocklet_pytest.egg-info/entry_points.txt
|
|
11
|
+
mocklet_pytest.egg-info/requires.txt
|
|
12
|
+
mocklet_pytest.egg-info/top_level.txt
|
|
13
|
+
tests/test_integration.py
|
|
14
|
+
tests/test_runtime.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pytest>=7
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mocklet_pytest
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mocklet-pytest"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "HAR replay and response-drift assertions for pytest"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
dependencies = ["pytest>=7"]
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
keywords = ["pytest", "har", "contract-testing", "api-drift", "mocklet"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Framework :: Pytest",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Software Development :: Testing",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://gitlab.com/keystr0ke/mocklet-pytest"
|
|
23
|
+
Issues = "https://gitlab.com/keystr0ke/mocklet-pytest/-/issues"
|
|
24
|
+
"Mocklet CLI" = "https://gitlab.com/keystr0ke/mocklet_cli"
|
|
25
|
+
|
|
26
|
+
[project.entry-points.pytest11]
|
|
27
|
+
mocklet = "mocklet_pytest.plugin"
|
|
28
|
+
|
|
29
|
+
[tool.pytest.ini_options]
|
|
30
|
+
addopts = "-ra"
|
|
31
|
+
testpaths = ["tests"]
|
|
32
|
+
|
|
33
|
+
[tool.ruff]
|
|
34
|
+
line-length = 120
|
|
35
|
+
target-version = "py39"
|
|
36
|
+
|
|
37
|
+
[tool.ruff.lint]
|
|
38
|
+
select = ["E4", "E7", "E9", "F", "I"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Tests against a real mocklet binary: MOCKLET_CLI=/path/to/mocklet pytest"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import urllib.request
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
import mocklet_pytest as mocklet
|
|
10
|
+
|
|
11
|
+
BASELINE = Path(__file__).parent / "fixtures" / "users.har"
|
|
12
|
+
|
|
13
|
+
pytestmark = pytest.mark.skipif(
|
|
14
|
+
not os.environ.get("MOCKLET_CLI"),
|
|
15
|
+
reason="set MOCKLET_CLI to run against a real mocklet binary",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@mocklet.baseline(BASELINE)
|
|
20
|
+
def test_replay_matches_baseline(mocklet):
|
|
21
|
+
with urllib.request.urlopen(f"{mocklet.url}/users/1") as response:
|
|
22
|
+
body = response.read()
|
|
23
|
+
status = response.status
|
|
24
|
+
assert status == 200
|
|
25
|
+
mocklet.assert_no_drift(body, method="GET", url=f"{mocklet.url}/users/1", status=status)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@mocklet.baseline(BASELINE)
|
|
29
|
+
def test_drift_fails_with_json_paths(mocklet):
|
|
30
|
+
with pytest.raises(pytest.fail.Exception) as failure:
|
|
31
|
+
mocklet.assert_no_drift({"id": "1"}, method="GET", url="/users/1", status=200)
|
|
32
|
+
report = str(failure.value)
|
|
33
|
+
assert "response.body.id: actual string" in report
|
|
34
|
+
assert "response.body.email: missing" in report
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import subprocess
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
import mocklet_pytest as mocklet
|
|
9
|
+
from mocklet_pytest.runtime import Mocklet
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FakeProcess:
|
|
13
|
+
def __init__(self, line='{"url":"http://127.0.0.1:43123"}\n'):
|
|
14
|
+
self.stdout = io.StringIO(line)
|
|
15
|
+
self.stderr = io.StringIO("")
|
|
16
|
+
self.returncode = None
|
|
17
|
+
self.terminated = False
|
|
18
|
+
|
|
19
|
+
def poll(self):
|
|
20
|
+
return self.returncode
|
|
21
|
+
|
|
22
|
+
def terminate(self):
|
|
23
|
+
self.terminated = True
|
|
24
|
+
self.returncode = 0
|
|
25
|
+
|
|
26
|
+
def kill(self):
|
|
27
|
+
self.returncode = -9
|
|
28
|
+
|
|
29
|
+
def wait(self, timeout=None):
|
|
30
|
+
return self.returncode
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_baseline_marker_has_plugin_marker_name():
|
|
34
|
+
marker = mocklet.baseline("checkout.har")
|
|
35
|
+
assert marker.name == "mocklet_baseline"
|
|
36
|
+
assert marker.args == ("checkout.har",)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_baseline_starts_on_ephemeral_loopback_and_closes(monkeypatch, tmp_path):
|
|
40
|
+
har = tmp_path / "checkout.har"
|
|
41
|
+
har.write_text("{}")
|
|
42
|
+
process = FakeProcess()
|
|
43
|
+
commands = []
|
|
44
|
+
|
|
45
|
+
def fake_popen(command, **kwargs):
|
|
46
|
+
commands.append((command, kwargs))
|
|
47
|
+
return process
|
|
48
|
+
|
|
49
|
+
monkeypatch.setattr(subprocess, "Popen", fake_popen)
|
|
50
|
+
runtime = Mocklet(executable="mocklet")
|
|
51
|
+
|
|
52
|
+
assert runtime.baseline(har) == "http://127.0.0.1:43123"
|
|
53
|
+
assert commands[0][0] == [
|
|
54
|
+
"mocklet",
|
|
55
|
+
"mock",
|
|
56
|
+
"serve",
|
|
57
|
+
str(har.resolve()),
|
|
58
|
+
"--listen",
|
|
59
|
+
"127.0.0.1:0",
|
|
60
|
+
"--output",
|
|
61
|
+
"json",
|
|
62
|
+
]
|
|
63
|
+
runtime.close()
|
|
64
|
+
assert process.terminated
|
|
65
|
+
assert runtime.url is None
|
|
66
|
+
assert runtime.baseline_path is None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_baseline_rejects_invalid_readiness_output_and_stops_process(monkeypatch, tmp_path):
|
|
70
|
+
har = tmp_path / "checkout.har"
|
|
71
|
+
har.write_text("{}")
|
|
72
|
+
process = FakeProcess('{"url":"not-an-http-url"}\n')
|
|
73
|
+
monkeypatch.setattr(subprocess, "Popen", lambda *args, **kwargs: process)
|
|
74
|
+
runtime = Mocklet(executable="mocklet")
|
|
75
|
+
|
|
76
|
+
with pytest.raises(pytest.UsageError, match="Invalid readiness output"):
|
|
77
|
+
runtime.baseline(har)
|
|
78
|
+
|
|
79
|
+
assert process.terminated
|
|
80
|
+
assert runtime.baseline_path is None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_assert_no_drift_passes_response_metadata_and_removes_tempfile(monkeypatch, tmp_path):
|
|
84
|
+
baseline = tmp_path / "checkout.har"
|
|
85
|
+
baseline.write_text("{}")
|
|
86
|
+
runtime = Mocklet(executable="drift")
|
|
87
|
+
runtime.baseline_path = baseline
|
|
88
|
+
seen = {}
|
|
89
|
+
|
|
90
|
+
def fake_run(command, **kwargs):
|
|
91
|
+
seen["command"] = command
|
|
92
|
+
actual_path = Path(command[command.index("--actual") + 1])
|
|
93
|
+
seen["body"] = actual_path.read_bytes()
|
|
94
|
+
seen["path"] = actual_path
|
|
95
|
+
return SimpleNamespace(returncode=0, stdout="No drift detected.\n", stderr="")
|
|
96
|
+
|
|
97
|
+
monkeypatch.setattr(subprocess, "run", fake_run)
|
|
98
|
+
response = SimpleNamespace(
|
|
99
|
+
content=b'{"ok":true}',
|
|
100
|
+
status_code=200,
|
|
101
|
+
url="https://api.test/checkout",
|
|
102
|
+
request=SimpleNamespace(method="GET"),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
runtime.assert_no_drift(response)
|
|
106
|
+
|
|
107
|
+
assert seen["body"] == b'{"ok":true}'
|
|
108
|
+
assert seen["command"][1:3] == ["drift", "check"]
|
|
109
|
+
assert seen["command"][-6:] == [
|
|
110
|
+
"--method",
|
|
111
|
+
"GET",
|
|
112
|
+
"--url",
|
|
113
|
+
"https://api.test/checkout",
|
|
114
|
+
"--status",
|
|
115
|
+
"200",
|
|
116
|
+
]
|
|
117
|
+
assert not seen["path"].exists()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_assert_no_drift_turns_exit_three_into_clean_pytest_failure(monkeypatch, tmp_path):
|
|
121
|
+
baseline = tmp_path / "checkout.har"
|
|
122
|
+
baseline.write_text("{}")
|
|
123
|
+
runtime = Mocklet(executable="drift")
|
|
124
|
+
runtime.baseline_path = baseline
|
|
125
|
+
monkeypatch.setattr(
|
|
126
|
+
subprocess,
|
|
127
|
+
"run",
|
|
128
|
+
lambda *args, **kwargs: SimpleNamespace(
|
|
129
|
+
returncode=3,
|
|
130
|
+
stdout="DRIFT DETECTED\n- response.body.id: expected integer\n+ response.body.id: actual string\n",
|
|
131
|
+
stderr="",
|
|
132
|
+
),
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
with pytest.raises(pytest.fail.Exception, match="response.body.id"):
|
|
136
|
+
runtime.assert_no_drift({"id": "oops"}, method="GET", url="/checkout", status=200)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_assert_no_drift_surfaces_cli_runtime_errors(monkeypatch, tmp_path):
|
|
140
|
+
baseline = tmp_path / "checkout.har"
|
|
141
|
+
baseline.write_text("{}")
|
|
142
|
+
runtime = Mocklet(executable="drift")
|
|
143
|
+
runtime.baseline_path = baseline
|
|
144
|
+
monkeypatch.setattr(
|
|
145
|
+
subprocess,
|
|
146
|
+
"run",
|
|
147
|
+
lambda *args, **kwargs: SimpleNamespace(returncode=2, stdout="", stderr="invalid HAR"),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
with pytest.raises(pytest.UsageError, match="invalid HAR"):
|
|
151
|
+
runtime.assert_no_drift(b"{}")
|