pytest-openapi-contract 0.1.6__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.
- pytest_openapi_contract/__init__.py +0 -0
- pytest_openapi_contract/cli.py +324 -0
- pytest_openapi_contract/helpers.py +875 -0
- pytest_openapi_contract/plugin.py +985 -0
- pytest_openapi_contract/runner.py +203 -0
- pytest_openapi_contract-0.1.6.dist-info/METADATA +249 -0
- pytest_openapi_contract-0.1.6.dist-info/RECORD +11 -0
- pytest_openapi_contract-0.1.6.dist-info/WHEEL +5 -0
- pytest_openapi_contract-0.1.6.dist-info/entry_points.txt +5 -0
- pytest_openapi_contract-0.1.6.dist-info/licenses/LICENSE +21 -0
- pytest_openapi_contract-0.1.6.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import requests
|
|
3
|
+
import json
|
|
4
|
+
from .plugin import ALL_LOADED_SPECS
|
|
5
|
+
from . import cli
|
|
6
|
+
from .helpers import (
|
|
7
|
+
validate_response_by_content_type,
|
|
8
|
+
validate_expected_response_values,
|
|
9
|
+
validate_response_headers,
|
|
10
|
+
validate_sla_latency,
|
|
11
|
+
format_as_curl,
|
|
12
|
+
inject_dynamic_variables,
|
|
13
|
+
dict_to_xml_string
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
pytestmark = pytest.mark.api
|
|
17
|
+
|
|
18
|
+
def test_generated_api_endpoint(request, api_endpoint_meta, auth_headers, http_session, created_resource_ids):
|
|
19
|
+
suite_name = api_endpoint_meta.get("suite_name")
|
|
20
|
+
active_spec = ALL_LOADED_SPECS.get(suite_name, {})
|
|
21
|
+
suite_vars = created_resource_ids.get(suite_name, {})
|
|
22
|
+
env_security = api_endpoint_meta.get("env_security", {})
|
|
23
|
+
|
|
24
|
+
# 1. Inject dynamic setup variables into URL, query params, and payload
|
|
25
|
+
url = inject_dynamic_variables(api_endpoint_meta["url"], suite_vars)
|
|
26
|
+
query_params = inject_dynamic_variables(api_endpoint_meta.get("query_params", {}), suite_vars)
|
|
27
|
+
payload = inject_dynamic_variables(api_endpoint_meta["payload"], suite_vars)
|
|
28
|
+
|
|
29
|
+
method = api_endpoint_meta["method"]
|
|
30
|
+
content_type = api_endpoint_meta.get("content_type", "application/json")
|
|
31
|
+
expected_status = api_endpoint_meta["expected_status"]
|
|
32
|
+
response_content_type = api_endpoint_meta.get("response_content_type")
|
|
33
|
+
response_schema = api_endpoint_meta.get("response_schema")
|
|
34
|
+
test_type = api_endpoint_meta.get("test_type", "HAPPY_PATH")
|
|
35
|
+
|
|
36
|
+
# 2. Build Request Headers & Authentication
|
|
37
|
+
headers = {}
|
|
38
|
+
if response_content_type:
|
|
39
|
+
headers["Accept"] = response_content_type
|
|
40
|
+
else:
|
|
41
|
+
headers["Accept"] = "application/json, application/xml;q=0.9, */*;q=0.8"
|
|
42
|
+
|
|
43
|
+
if payload is not None and content_type:
|
|
44
|
+
headers["Content-Type"] = content_type
|
|
45
|
+
|
|
46
|
+
secrets_to_mask = []
|
|
47
|
+
if api_endpoint_meta["requires_auth"]:
|
|
48
|
+
headers.update(auth_headers)
|
|
49
|
+
sec_headers = inject_dynamic_variables(env_security.get("headers", {}), suite_vars)
|
|
50
|
+
sec_query = inject_dynamic_variables(env_security.get("query_params", {}), suite_vars)
|
|
51
|
+
|
|
52
|
+
headers.update(sec_headers)
|
|
53
|
+
query_params.update(sec_query)
|
|
54
|
+
|
|
55
|
+
secrets_to_mask.extend(sec_headers.values())
|
|
56
|
+
secrets_to_mask.extend(sec_query.values())
|
|
57
|
+
|
|
58
|
+
secrets_to_mask = [str(s) for s in secrets_to_mask if isinstance(s, (str, int, float)) and s]
|
|
59
|
+
|
|
60
|
+
# 3. Serialize Request Payload by Content-Type
|
|
61
|
+
req_kwargs = {
|
|
62
|
+
"method": method,
|
|
63
|
+
"url": url,
|
|
64
|
+
"headers": headers,
|
|
65
|
+
"params": query_params if query_params else None,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if payload is not None:
|
|
69
|
+
ct_lower = content_type.lower()
|
|
70
|
+
if "json" in ct_lower:
|
|
71
|
+
req_kwargs["json"] = payload
|
|
72
|
+
elif "xml" in ct_lower:
|
|
73
|
+
req_schema = api_endpoint_meta.get("request_schema")
|
|
74
|
+
xml_body = dict_to_xml_string(payload, schema=req_schema, full_spec=active_spec)
|
|
75
|
+
req_kwargs["data"] = xml_body.encode("utf-8")
|
|
76
|
+
elif "x-www-form-urlencoded" in ct_lower:
|
|
77
|
+
req_kwargs["data"] = payload
|
|
78
|
+
elif "multipart/form-data" in ct_lower:
|
|
79
|
+
headers.pop("Content-Type", None)
|
|
80
|
+
req_kwargs["files"] = {k: (None, str(v)) for k, v in payload.items()} if isinstance(payload, dict) else {}
|
|
81
|
+
elif "text/plain" in ct_lower:
|
|
82
|
+
text_body = json.dumps(payload) if isinstance(payload, (dict, list)) else str(payload)
|
|
83
|
+
req_kwargs["data"] = text_body.encode("utf-8")
|
|
84
|
+
else:
|
|
85
|
+
req_kwargs["data"] = str(payload)
|
|
86
|
+
|
|
87
|
+
# 4. Prepare Request, Log Masked cURL, and Send
|
|
88
|
+
req = requests.Request(**req_kwargs)
|
|
89
|
+
prepared_req = http_session.prepare_request(req)
|
|
90
|
+
curl_cmd = format_as_curl(prepared_req, masked_values=secrets_to_mask)
|
|
91
|
+
|
|
92
|
+
# Store cURL immediately so it appears in the HTML report even on connection errors
|
|
93
|
+
request.node.api_curl = curl_cmd
|
|
94
|
+
request.node.api_response_info = "No response received (Request timed out or failed to connect)."
|
|
95
|
+
|
|
96
|
+
print(f"\n--- cURL [{test_type}] ---\n{curl_cmd}\n")
|
|
97
|
+
|
|
98
|
+
response = http_session.send(prepared_req, timeout=15)
|
|
99
|
+
elapsed_ms = response.elapsed.total_seconds() * 1000.0
|
|
100
|
+
|
|
101
|
+
# Save status code and response snippet for the HTML report
|
|
102
|
+
request.node.api_response_info = (
|
|
103
|
+
f"Status Code: {response.status_code}\n"
|
|
104
|
+
f"Latency: {elapsed_ms:.2f} ms\n"
|
|
105
|
+
f"Content-Type: {response.headers.get('Content-Type', 'N/A')}\n\n"
|
|
106
|
+
f"{response.text[:2000]}"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# 5. Global 5xx Crash Guard + Error Contract Validation
|
|
110
|
+
if response.status_code >= 500 and expected_status < 500:
|
|
111
|
+
err_500_schema = api_endpoint_meta.get("err_500_schema")
|
|
112
|
+
err_500_ct = api_endpoint_meta.get("err_500_ct")
|
|
113
|
+
schema_note = "No 500 schema documented."
|
|
114
|
+
|
|
115
|
+
if err_500_schema:
|
|
116
|
+
try:
|
|
117
|
+
validate_response_by_content_type(response, err_500_ct, err_500_schema, active_spec)
|
|
118
|
+
schema_note = "Response body matches documented 500 error schema."
|
|
119
|
+
except ValueError as e:
|
|
120
|
+
schema_note = f"Response body ALSO violated 500 error schema: {e}"
|
|
121
|
+
|
|
122
|
+
pytest.fail(
|
|
123
|
+
f"CRITICAL SERVER CRASH ({response.status_code}) [{test_type}]: {method} {url}\n"
|
|
124
|
+
f"Contract Check: {schema_note}\n"
|
|
125
|
+
f"Reproduce with cURL:\n{curl_cmd}\n"
|
|
126
|
+
f"Server Output:\n{response.text[:1000]}"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# 6. Assert Expected HTTP Status Code
|
|
130
|
+
assert response.status_code == expected_status, (
|
|
131
|
+
f"HTTP Status Mismatch [{test_type}]: {method} {url}\n"
|
|
132
|
+
f"Expected Code: {expected_status} | Received Code: {response.status_code}\n"
|
|
133
|
+
f"Reproduce with cURL:\n{curl_cmd}\n"
|
|
134
|
+
f"Server Output: {response.text[:500]}"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# SLA Latency Check
|
|
138
|
+
max_ms = api_endpoint_meta.get("max_response_time_ms")
|
|
139
|
+
if max_ms is not None:
|
|
140
|
+
try:
|
|
141
|
+
validate_sla_latency(elapsed_ms, max_ms)
|
|
142
|
+
except ValueError as sla_err:
|
|
143
|
+
pytest.fail(
|
|
144
|
+
f"SLA Performance Failure [{test_type}] on {method} {url}:\n"
|
|
145
|
+
f"Reason: {str(sla_err)}\n"
|
|
146
|
+
f"Reproduce with cURL:\n{curl_cmd}"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Response Headers Contract & Custom Rules Check
|
|
150
|
+
openapi_headers_for_status = api_endpoint_meta.get("openapi_resp_headers", {}).get(str(expected_status), {})
|
|
151
|
+
custom_headers_for_status = inject_dynamic_variables(
|
|
152
|
+
api_endpoint_meta.get("expected_headers", {}).get(str(expected_status), {}),
|
|
153
|
+
suite_vars
|
|
154
|
+
)
|
|
155
|
+
if openapi_headers_for_status or custom_headers_for_status:
|
|
156
|
+
try:
|
|
157
|
+
validate_response_headers(
|
|
158
|
+
response_headers=response.headers,
|
|
159
|
+
openapi_headers_spec=openapi_headers_for_status,
|
|
160
|
+
expected_headers=custom_headers_for_status,
|
|
161
|
+
full_spec=active_spec
|
|
162
|
+
)
|
|
163
|
+
except ValueError as hdr_err:
|
|
164
|
+
pytest.fail(
|
|
165
|
+
f"Response Header Contract Failure [{expected_status}] on {method} {url}:\n"
|
|
166
|
+
f"Reason: {str(hdr_err)}\n"
|
|
167
|
+
f"Reproduce with cURL:\n{curl_cmd}\n"
|
|
168
|
+
f"Actual Headers:\n{dict(response.headers)}"
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# 7. Validate Response Schema (JSON or XML)
|
|
172
|
+
if response_schema:
|
|
173
|
+
try:
|
|
174
|
+
validate_response_by_content_type(
|
|
175
|
+
response=response,
|
|
176
|
+
response_content_type=response_content_type,
|
|
177
|
+
response_schema=response_schema,
|
|
178
|
+
full_spec=active_spec
|
|
179
|
+
)
|
|
180
|
+
except ValueError as schema_err:
|
|
181
|
+
pytest.fail(
|
|
182
|
+
f"Response Schema Contract Violation [{test_type}] on {method} {url}:\n"
|
|
183
|
+
f"Reason: {str(schema_err)}\n"
|
|
184
|
+
f"Reproduce with cURL:\n{curl_cmd}\n"
|
|
185
|
+
f"Actual Response Body:\n{response.text[:500]}"
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
# 8. Validate Specific Expected Response Values for This Status Code
|
|
189
|
+
all_expected_responses = api_endpoint_meta.get("expected_response", {})
|
|
190
|
+
status_expected_values = all_expected_responses.get(str(expected_status), {})
|
|
191
|
+
resolved_expected_values = inject_dynamic_variables(status_expected_values, suite_vars)
|
|
192
|
+
|
|
193
|
+
if resolved_expected_values:
|
|
194
|
+
actual_resp_ct = response.headers.get("Content-Type", response_content_type or "")
|
|
195
|
+
try:
|
|
196
|
+
validate_expected_response_values(response, resolved_expected_values, actual_resp_ct)
|
|
197
|
+
except ValueError as val_err:
|
|
198
|
+
pytest.fail(
|
|
199
|
+
f"Response Data Assertion Failure [{expected_status}] on {method} {url}:\n"
|
|
200
|
+
f"Reason: {str(val_err)}\n"
|
|
201
|
+
f"Reproduce with cURL:\n{curl_cmd}\n"
|
|
202
|
+
f"Actual Response Body:\n{response.text[:500]}"
|
|
203
|
+
)
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytest-openapi-contract
|
|
3
|
+
Version: 0.1.6
|
|
4
|
+
Summary: Dynamic OpenAPI 3.0/3.1 contract, functional, and negative API testing plugin for Pytest
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 Jeorge Concepcion
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
|
|
27
|
+
Classifier: Framework :: Pytest
|
|
28
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
29
|
+
Classifier: Programming Language :: Python :: 3
|
|
30
|
+
Classifier: Topic :: Software Development :: Testing
|
|
31
|
+
Requires-Python: >=3.9
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
License-File: LICENSE
|
|
34
|
+
Requires-Dist: pytest>=7.0.0
|
|
35
|
+
Requires-Dist: requests>=2.31.0
|
|
36
|
+
Requires-Dist: pytest-html>=4.1.0
|
|
37
|
+
Requires-Dist: filelock>=3.12.0
|
|
38
|
+
Dynamic: license-file
|
|
39
|
+
|
|
40
|
+
# pytest-openapi-contract
|
|
41
|
+
|
|
42
|
+
A **Pytest plugin** and **CLI scaffolding tool** for automated, data-driven OpenAPI 3.0/3.1 contract, functional, performance, and negative API testing.
|
|
43
|
+
|
|
44
|
+
Install the package via `pip`, scaffold your test directory with one CLI command (`openapi-contract init-project`), validate your configs offline (`openapi-contract validate`), and run `pytest` (sequentially or in parallel via `pytest -n auto`) to generate test cases, validate JSON, XML, `text/plain`, and header contracts, enforce SLA latency limits, chain stateful setup/teardown workflows, detect spec drift, and produce self-contained HTML reports with masked cURL commands.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Features
|
|
49
|
+
|
|
50
|
+
* **One-Command Project Scaffolding:** Instantly creates `pytest.ini`, `requirements.txt`, `reports/`, `tests/conftest.py`, a starter `specs/<service_name>/test_data.json` template, and an optional GitHub Actions CI workflow (`--with-ci`).
|
|
51
|
+
* **Offline Config & Spec Validator (`openapi-contract validate`):** Validates JSON syntax, broken `$ref` pointers, regex patterns, and undefined `{{variables}}` before firing live HTTP requests.
|
|
52
|
+
* **Zero-Boilerplate Pytest Plugin:** Automatically discovers OpenAPI specs inside your project's `specs/` folder—no custom test runner code needed.
|
|
53
|
+
* **Automated Positive & Negative Test Generation:** Generates Happy Path (`2xx`) and 6 Negative test scenarios (`400 Bad Data`, `400 Invalid Enum`, `400 Missing Required Query`, `401 Unauthorized`, and `5xx` Server Crash guards) per endpoint.
|
|
54
|
+
* **SLA Performance Latency Assertions:** Enforces global and per-endpoint `max_response_time_ms` thresholds and logs response latency in HTML reports.
|
|
55
|
+
* **Response Header Contract & Rule Validation:** Validates OpenAPI `responses.<status>.headers` types/required rules plus custom `expected_headers` assertions (`not_empty`, `contains:`, `regex:`, `gte:`).
|
|
56
|
+
* **Parallel Execution Safety (`pytest-xdist`):** Uses worker-aware file locking (`filelock`) so `pytest -n auto` executes `setup_resources` and `teardown_resources` once safely across parallel workers.
|
|
57
|
+
* **Multi-Suite & Multi-Environment Execution:** Test multiple microservices simultaneously or target specific runs using `--suite` and `--env`.
|
|
58
|
+
* **Live Spec Download & Drift Detection:** Downloads live OpenAPI JSON specs per environment, compares them against local baselines, logs added/removed/modified routes and schemas, and preserves baselines unless `--update-spec` is passed.
|
|
59
|
+
* **Stateful Resource Chaining:** Executes `setup_resources` (`POST`) before tests run, extracts live IDs (`{{petId}}`, `{{orderId}}`), injects them across dependent requests, and cleans up via `teardown_resources` (`DELETE`) after execution.
|
|
60
|
+
* **JSON, XML & Plain-Text Support:** Serializes request payloads (JSON, XML, Form-Urlencoded, Multipart, `text/plain`) and validates response schemas (`allOf`, `oneOf`, `anyOf`, `nullable`, `enum`, `required`, `pattern`, `minLength`) plus custom value assertions.
|
|
61
|
+
* **Security Masking & HTML Reporting:** Automatically masks sensitive headers, query parameters, URL paths, and request bodies in console logs and `pytest-html` reports, with an `--unmask` flag for local debugging.
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Installation
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install pytest-openapi-contract
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Requirements:** Python 3.9+
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Quick Start
|
|
76
|
+
|
|
77
|
+
### 1. Initialize Your Test Project
|
|
78
|
+
In your project directory, run the CLI scaffolding command:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
openapi-contract init-project --suite=petstore_service --with-ci
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
This creates the required project structure:
|
|
85
|
+
|
|
86
|
+
```text
|
|
87
|
+
your-project/
|
|
88
|
+
├── .github/
|
|
89
|
+
│ └── workflows/
|
|
90
|
+
│ └── api-contract-tests.yml # Generated when --with-ci is passed
|
|
91
|
+
├── pytest.ini # Pre-configured with -m api and HTML report output
|
|
92
|
+
├── requirements.txt # Project dependencies
|
|
93
|
+
├── reports/
|
|
94
|
+
│ └── .gitkeep # Output directory for report.html
|
|
95
|
+
├── specs/
|
|
96
|
+
│ └── petstore_service/
|
|
97
|
+
│ └── test_data.json # Starter environment, auth, SLA, and assertion config
|
|
98
|
+
└── tests/
|
|
99
|
+
└── conftest.py # Hook file for any custom project-level fixtures
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
#### CLI Scaffolding & Validation Options
|
|
103
|
+
|
|
104
|
+
| Command | Description |
|
|
105
|
+
| :--- | :--- |
|
|
106
|
+
| `openapi-contract init-project` | Scaffold folders and starter template files in the current directory. |
|
|
107
|
+
| `--path <dir>` | Target directory where files and folders will be created (default: `.`). |
|
|
108
|
+
| `--suite <name>` | Name of the initial starter service folder inside `specs/` (default: `sample_service`). |
|
|
109
|
+
| `--with-ci` | Also generate `.github/workflows/api-contract-tests.yml` for GitHub Actions. |
|
|
110
|
+
| `--force` | Overwrite existing template files if they already exist. |
|
|
111
|
+
| `openapi-contract validate` | Validate all `openapi.json` and `test_data.json` files offline (`--specs-dir` optional). |
|
|
112
|
+
|
|
113
|
+
### 2. Validate & Run Your Tests
|
|
114
|
+
Edit `specs/petstore_service/test_data.json` with your API's `spec_url` and `server_url`, validate your config, and run `pytest`:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
openapi-contract validate
|
|
118
|
+
pytest
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Pytest CLI Options
|
|
124
|
+
|
|
125
|
+
| Command | Description |
|
|
126
|
+
| :--- | :--- |
|
|
127
|
+
| `pytest` | Run all live API suites across all configured environments in `specs/`. |
|
|
128
|
+
| `pytest -n auto` | Run tests in parallel across CPU cores safely (`pytest-xdist` compatible). |
|
|
129
|
+
| `pytest --suite=petstore_service` | Run tests only for `specs/petstore_service/`. |
|
|
130
|
+
| `pytest --env=sandbox` | Run tests only against the `sandbox` environment. |
|
|
131
|
+
| `pytest --suite=petstore_service --env=local` | Run a specific service against a specific environment. |
|
|
132
|
+
| `pytest --update-spec` | Overwrite local baseline `openapi.json` files when live spec drift is detected (disabled by default). |
|
|
133
|
+
| `pytest --unmask` | Reveal masked tokens, API keys, and passwords in cURL logs and HTML reports for local debugging. |
|
|
134
|
+
| `pytest -k "GET_ and HAPPY"` | Filter tests by keyword (HTTP method, path, or test type). |
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Configuration (`test_data.json`)
|
|
139
|
+
|
|
140
|
+
Place a `test_data.json` file inside `specs/<service_name>/` to define SLA thresholds, environments, credentials, stateful setup/teardown workflows, parameter overrides, header checks, and response assertions.
|
|
141
|
+
|
|
142
|
+
```json
|
|
143
|
+
{
|
|
144
|
+
"max_response_time_ms": 2000,
|
|
145
|
+
"environments": {
|
|
146
|
+
"sandbox": {
|
|
147
|
+
"spec_url": "https://swagger.io",
|
|
148
|
+
"server_url": "https://swagger.io",
|
|
149
|
+
"security": {
|
|
150
|
+
"headers": {
|
|
151
|
+
"api_key": "special-key"
|
|
152
|
+
},
|
|
153
|
+
"query_params": {}
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
"local": {
|
|
157
|
+
"spec_url": "http://localhost:8080/api/v3/openapi.json",
|
|
158
|
+
"server_url": "http://localhost:8080/api/v3",
|
|
159
|
+
"security": {
|
|
160
|
+
"headers": {
|
|
161
|
+
"Authorization": "Bearer local_dev_token"
|
|
162
|
+
},
|
|
163
|
+
"query_params": {}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
"setup_resources": [
|
|
168
|
+
{
|
|
169
|
+
"method": "POST",
|
|
170
|
+
"url": "https://swagger.io/pet",
|
|
171
|
+
"payload": {
|
|
172
|
+
"id": 998877,
|
|
173
|
+
"name": "Buddy",
|
|
174
|
+
"photoUrls": ["https://example.com"],
|
|
175
|
+
"status": "available"
|
|
176
|
+
},
|
|
177
|
+
"extract": {
|
|
178
|
+
"petId": "id"
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
],
|
|
182
|
+
"teardown_resources": [
|
|
183
|
+
{
|
|
184
|
+
"method": "DELETE",
|
|
185
|
+
"url": "https://swagger.io/pet/{{petId}}"
|
|
186
|
+
}
|
|
187
|
+
],
|
|
188
|
+
"global_params": {
|
|
189
|
+
"username": "user1",
|
|
190
|
+
"petId": "{{petId}}",
|
|
191
|
+
"status": "available"
|
|
192
|
+
},
|
|
193
|
+
"endpoints": {
|
|
194
|
+
"GET /pet/{petId}": {
|
|
195
|
+
"max_response_time_ms": 800,
|
|
196
|
+
"path_params": {
|
|
197
|
+
"petId": "{{petId}}"
|
|
198
|
+
},
|
|
199
|
+
"expected_headers": {
|
|
200
|
+
"Content-Type": "contains:application/json"
|
|
201
|
+
},
|
|
202
|
+
"expected_response": {
|
|
203
|
+
"200": {
|
|
204
|
+
"id": "{{petId}}",
|
|
205
|
+
"name": ["not_empty", "contains:Buddy"],
|
|
206
|
+
"status": "available"
|
|
207
|
+
},
|
|
208
|
+
"400": {
|
|
209
|
+
"message": "contains:Invalid"
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
"GET /user/login": {
|
|
214
|
+
"expected_response": {
|
|
215
|
+
"200": {
|
|
216
|
+
"$body": ["not_empty", "contains:logged in user session"]
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
## Response Body & Header Assertion Rules
|
|
227
|
+
|
|
228
|
+
Inside `expected_response.<status_code>` or `expected_headers.<status_code>`, validate exact values or stack multiple dynamic rules in a list using dot notation (`"category.name"`, `"items.0.id"`), or `"$body"` for `text/plain` responses:
|
|
229
|
+
|
|
230
|
+
| Rule Syntax | Example | Behavior |
|
|
231
|
+
| :--- | :--- | :--- |
|
|
232
|
+
| **Exact Match** | `"status": "available"` | Verifies exact value and data type (`int`, `str`, `bool`). |
|
|
233
|
+
| **Plain-Text Body** | `"$body": ["not_empty", "contains:session"]` | Validates `text/plain` response bodies directly. |
|
|
234
|
+
| **Dynamic Variable** | `"id": "{{petId}}"` | Injects captured setup variable while preserving its type. |
|
|
235
|
+
| **`not_empty`** | `"token": "not_empty"` | Fails if value is `null`, `""`, `[]`, or `{}`. |
|
|
236
|
+
| **`contains:<text>`** | `"message": "contains:Success"` | Fails if `<text>` is not found in the response value. |
|
|
237
|
+
| **`not_contains:<text>`** | `"error": "not_contains:Exception"` | Fails if unwanted text appears in the response value. |
|
|
238
|
+
| **`regex:<pattern>`** | `"date": "regex:^\\d{4}-\\d{2}-\\d{2}"` | Validates string against a regular expression. |
|
|
239
|
+
| **`gt:` / `gte:` / `lt:` / `lte:`** | `"id": ["not_empty", "gt:0"]` | Performs numeric comparisons on integers or floats. |
|
|
240
|
+
| **`exact:<json>`** | `"tags": "exact:[\"tag1\", \"tag2\"]"` | Forces an exact list/object match instead of treating a list as multiple rules. |
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## Security & Sensitive Data Masking
|
|
245
|
+
|
|
246
|
+
* **Automatic Redaction:** Headers, query parameters, URL path values, JSON keys, and XML tags matching sensitive keywords (`authorization`, `api_key`, `token`, `password`, `secret`, `cookie`) are automatically replaced with `***MASKED***` in console output and `reports/report.html`.
|
|
247
|
+
* **Debug Override (`--unmask`):** Passing `pytest --unmask` disables redaction for local troubleshooting and injects a high-visibility **SECURITY WARNING** banner at the top of `reports/report.html` so unmasked reports are never accidentally shared or committed.
|
|
248
|
+
|
|
249
|
+
---
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
pytest_openapi_contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
pytest_openapi_contract/cli.py,sha256=lAAp2zTrotFfXZ9qMrsf-GeW_iyMgY5enGAVTQysiXo,11207
|
|
3
|
+
pytest_openapi_contract/helpers.py,sha256=QzN8TkXNWBa2LIRfNRWqgosC8VzYn6AQGDLCYGDaR3I,36144
|
|
4
|
+
pytest_openapi_contract/plugin.py,sha256=Qk3t2UyeHkSGnQS3_qh50ybe1fkRlGCK1R4obdZdFbY,47376
|
|
5
|
+
pytest_openapi_contract/runner.py,sha256=dUNtbh3Qq0O0q1w5MSD8pxjIYrUNoz4jL4xUQyMP9w0,8751
|
|
6
|
+
pytest_openapi_contract-0.1.6.dist-info/licenses/LICENSE,sha256=oowz9vPuKas5I3YQjz-NHCDcBdyCE36p4yxV1nRXCRg,1074
|
|
7
|
+
pytest_openapi_contract-0.1.6.dist-info/METADATA,sha256=pWP_tznl47nnO85K3ZOJRzmoy-SKB0BHdvyhlbwCgCw,11805
|
|
8
|
+
pytest_openapi_contract-0.1.6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
pytest_openapi_contract-0.1.6.dist-info/entry_points.txt,sha256=lgcBp2cSASNSY5c8vGf7NSiXgB4nTB9503HjOJRkVAw,132
|
|
10
|
+
pytest_openapi_contract-0.1.6.dist-info/top_level.txt,sha256=1-OkShGqtEMnjQl1BOXMJlC1oiEZ1KbLbpZ8EZtO1os,24
|
|
11
|
+
pytest_openapi_contract-0.1.6.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jeorge Concepcion
|
|
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
|
+
pytest_openapi_contract
|