pytest-openapi-contract 0.1.6__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.
- pytest_openapi_contract-0.1.6/LICENSE +21 -0
- pytest_openapi_contract-0.1.6/PKG-INFO +249 -0
- pytest_openapi_contract-0.1.6/README.md +248 -0
- pytest_openapi_contract-0.1.6/plugin-setup.md +210 -0
- pytest_openapi_contract-0.1.6/pyproject.toml +32 -0
- pytest_openapi_contract-0.1.6/setup.cfg +4 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract/__init__.py +0 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract/cli.py +324 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract/helpers.py +875 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract/plugin.py +985 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract/runner.py +203 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract.egg-info/PKG-INFO +249 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract.egg-info/SOURCES.txt +16 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract.egg-info/dependency_links.txt +1 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract.egg-info/entry_points.txt +5 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract.egg-info/requires.txt +4 -0
- pytest_openapi_contract-0.1.6/src/pytest_openapi_contract.egg-info/top_level.txt +1 -0
- pytest_openapi_contract-0.1.6/tests/test_framework_unit.py +647 -0
|
@@ -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,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,248 @@
|
|
|
1
|
+
# pytest-openapi-contract
|
|
2
|
+
|
|
3
|
+
A reusable **Pytest plugin** and **CLI scaffolding tool** for automated, data-driven OpenAPI 3.0/3.1 contract, functional, performance, and negative API testing.
|
|
4
|
+
|
|
5
|
+
Once installed via `pip`, you can initialize a complete API test suite in any repository with a single command (`openapi-contract init-project`), validate configurations offline (`openapi-contract validate`), generate positive and negative test cases from OpenAPI specs, validate JSON, XML, `text/plain`, and header contracts, enforce SLA latency limits, chain stateful setup/teardown workflows safely in parallel (`pytest -n auto`), detect spec drift, and generate self-contained HTML reports with masked cURL commands.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
* **One-Command Project Scaffolding (`openapi-contract init-project`):** Generates `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`).
|
|
12
|
+
* **Offline Config & Spec Validator (`openapi-contract validate`):** Validates JSON syntax, broken `$ref` pointers, regex patterns, and undefined `{{variables}}` before firing live HTTP requests.
|
|
13
|
+
* **Zero-Boilerplate Pytest Plugin (`pytest11`):** Automatically discovers OpenAPI specs inside `specs/` when running `pytest`—no custom test runner boilerplate required in consumer repositories.
|
|
14
|
+
* **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.
|
|
15
|
+
* **SLA Performance Latency Assertions:** Enforces global and per-endpoint `max_response_time_ms` thresholds and logs response latency in HTML reports.
|
|
16
|
+
* **Response Header Contract & Rule Validation:** Validates OpenAPI `responses.<status>.headers` types/required rules plus custom `expected_headers` assertions (`not_empty`, `contains:`, `regex:`, `gte:`).
|
|
17
|
+
* **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.
|
|
18
|
+
* **Multi-Suite & Multi-Environment Execution:** Test multiple microservices simultaneously or isolate runs using `--suite` and `--env`.
|
|
19
|
+
* **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.
|
|
20
|
+
* **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.
|
|
21
|
+
* **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.
|
|
22
|
+
* **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.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Repository Structure
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
pytest-openapi-contract/
|
|
30
|
+
├── LICENSE # MIT License
|
|
31
|
+
├── pyproject.toml # Build config, dependencies, CLI script, and pytest11 hook
|
|
32
|
+
├── pytest.ini # Pytest configuration and unit/api markers
|
|
33
|
+
├── README.md # Project & package documentation
|
|
34
|
+
├── src/
|
|
35
|
+
│ └── pytest_openapi_contract/
|
|
36
|
+
│ ├── __init__.py
|
|
37
|
+
│ ├── cli.py # CLI commands ('init-project', 'validate')
|
|
38
|
+
│ ├── plugin.py # Pytest plugin hooks, CLI flags, spec loader, locked setup/teardown
|
|
39
|
+
│ ├── helpers.py # Schema, header, SLA & text validators, XML builders, cURL masker
|
|
40
|
+
│ └── runner.py # Dynamic API test execution runner (@pytest.mark.api)
|
|
41
|
+
└── tests/
|
|
42
|
+
└── test_framework_unit.py # Offline plugin unit test suite (@pytest.mark.unit)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Local Development & Contributing
|
|
48
|
+
|
|
49
|
+
### 1. Clone & Install in Editable Mode
|
|
50
|
+
```bash
|
|
51
|
+
git clone https://github.com
|
|
52
|
+
cd pytest-openapi-contract
|
|
53
|
+
python -m venv .venv
|
|
54
|
+
source .venv/bin/activate # macOS / Linux
|
|
55
|
+
# .venv\Scripts\activate # Windows
|
|
56
|
+
|
|
57
|
+
pip install -e .
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 2. Run Offline Unit Tests
|
|
61
|
+
Verify all internal plugin validators, CLI commands, and loaders without making external network calls:
|
|
62
|
+
```bash
|
|
63
|
+
pytest -m unit
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 3. Build & Publish to PyPI
|
|
67
|
+
```bash
|
|
68
|
+
pip install --upgrade build twine
|
|
69
|
+
rm -rf dist/ build/ *.egg-info
|
|
70
|
+
python -m build
|
|
71
|
+
twine check dist/*
|
|
72
|
+
twine upload dist/*
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Consumer Project Quick Start
|
|
78
|
+
|
|
79
|
+
### Step 1: Install the Package
|
|
80
|
+
Install from PyPI or directly from GitHub:
|
|
81
|
+
```bash
|
|
82
|
+
pip install pytest-openapi-contract
|
|
83
|
+
# Or directly from GitHub:
|
|
84
|
+
# pip install git+https://github.com
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Step 2: Scaffold Your Project via CLI
|
|
88
|
+
Navigate to your target API repository and run:
|
|
89
|
+
```bash
|
|
90
|
+
openapi-contract init-project --suite=petstore_service --with-ci
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
This creates the complete project layout:
|
|
94
|
+
```text
|
|
95
|
+
your-repository/
|
|
96
|
+
├── .github/
|
|
97
|
+
│ └── workflows/
|
|
98
|
+
│ └── api-contract-tests.yml # Generated when --with-ci is passed
|
|
99
|
+
├── pytest.ini # Pre-configured with -m api and HTML report output
|
|
100
|
+
├── requirements.txt # Project dependencies
|
|
101
|
+
├── reports/
|
|
102
|
+
│ └── .gitkeep # Output directory for report.html
|
|
103
|
+
├── specs/
|
|
104
|
+
│ └── petstore_service/
|
|
105
|
+
│ └── test_data.json # Starter environment, auth, SLA, and assertion config
|
|
106
|
+
└── tests/
|
|
107
|
+
└── conftest.py # Hook file for any custom project-level fixtures
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
#### CLI Scaffolding & Validation Options
|
|
111
|
+
|
|
112
|
+
| Command | Description |
|
|
113
|
+
| :--- | :--- |
|
|
114
|
+
| `openapi-contract init-project` | Scaffold folders and starter template files in the current directory. |
|
|
115
|
+
| `--path <dir>` | Target directory where files and folders will be created (default: `.`). |
|
|
116
|
+
| `--suite <name>` | Name of the initial starter service folder inside `specs/` (default: `sample_service`). |
|
|
117
|
+
| `--with-ci` | Also generate `.github/workflows/api-contract-tests.yml` for GitHub Actions. |
|
|
118
|
+
| `--force` | Overwrite existing template files if they already exist. |
|
|
119
|
+
| `openapi-contract validate` | Validate all `openapi.json` and `test_data.json` files offline (`--specs-dir` optional). |
|
|
120
|
+
|
|
121
|
+
### Step 3: Validate & Run Tests
|
|
122
|
+
Update `specs/petstore_service/test_data.json` with your API's `spec_url` and `server_url`, validate your config, and run `pytest`:
|
|
123
|
+
```bash
|
|
124
|
+
openapi-contract validate
|
|
125
|
+
pytest
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Pytest CLI Options
|
|
131
|
+
|
|
132
|
+
| Command | Description |
|
|
133
|
+
| :--- | :--- |
|
|
134
|
+
| `pytest` | Run all live API suites across all configured environments in `specs/`. |
|
|
135
|
+
| `pytest -n auto` | Run tests in parallel across CPU cores safely (`pytest-xdist` compatible). |
|
|
136
|
+
| `pytest --suite=petstore_service` | Run tests only for `specs/petstore_service/`. |
|
|
137
|
+
| `pytest --env=sandbox` | Run tests only against the `sandbox` environment. |
|
|
138
|
+
| `pytest --suite=petstore_service --env=local` | Run a specific service against a specific environment. |
|
|
139
|
+
| `pytest --update-spec` | Overwrite local baseline `openapi.json` files when live spec drift is detected (disabled by default). |
|
|
140
|
+
| `pytest --unmask` | Reveal masked tokens, API keys, and passwords in cURL logs and HTML reports for local debugging. |
|
|
141
|
+
| `pytest -k "GET_ and HAPPY"` | Filter tests by keyword (HTTP method, path, or test type). |
|
|
142
|
+
| `pytest -m unit` | Run internal plugin unit tests (inside this plugin repository). |
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## Service Configuration (`test_data.json`)
|
|
147
|
+
|
|
148
|
+
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 expected response assertions.
|
|
149
|
+
|
|
150
|
+
```json
|
|
151
|
+
{
|
|
152
|
+
"max_response_time_ms": 2000,
|
|
153
|
+
"environments": {
|
|
154
|
+
"sandbox": {
|
|
155
|
+
"spec_url": "https://swagger.io",
|
|
156
|
+
"server_url": "https://swagger.io",
|
|
157
|
+
"security": {
|
|
158
|
+
"headers": {
|
|
159
|
+
"api_key": "special-key"
|
|
160
|
+
},
|
|
161
|
+
"query_params": {}
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
"local": {
|
|
165
|
+
"spec_url": "http://localhost:8080/api/v3/openapi.json",
|
|
166
|
+
"server_url": "http://localhost:8080/api/v3",
|
|
167
|
+
"security": {
|
|
168
|
+
"headers": {
|
|
169
|
+
"Authorization": "Bearer local_dev_token"
|
|
170
|
+
},
|
|
171
|
+
"query_params": {}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
"setup_resources": [
|
|
176
|
+
{
|
|
177
|
+
"method": "POST",
|
|
178
|
+
"url": "https://swagger.io/pet",
|
|
179
|
+
"payload": {
|
|
180
|
+
"id": 998877,
|
|
181
|
+
"name": "Buddy",
|
|
182
|
+
"photoUrls": ["https://example.com"],
|
|
183
|
+
"status": "available"
|
|
184
|
+
},
|
|
185
|
+
"extract": {
|
|
186
|
+
"petId": "id"
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
],
|
|
190
|
+
"teardown_resources": [
|
|
191
|
+
{
|
|
192
|
+
"method": "DELETE",
|
|
193
|
+
"url": "https://swagger.io/pet/{{petId}}"
|
|
194
|
+
}
|
|
195
|
+
],
|
|
196
|
+
"global_params": {
|
|
197
|
+
"username": "user1",
|
|
198
|
+
"petId": "{{petId}}",
|
|
199
|
+
"status": "available"
|
|
200
|
+
},
|
|
201
|
+
"endpoints": {
|
|
202
|
+
"GET /pet/{petId}": {
|
|
203
|
+
"max_response_time_ms": 800,
|
|
204
|
+
"path_params": {
|
|
205
|
+
"petId": "{{petId}}"
|
|
206
|
+
},
|
|
207
|
+
"expected_headers": {
|
|
208
|
+
"Content-Type": "contains:application/json"
|
|
209
|
+
},
|
|
210
|
+
"expected_response": {
|
|
211
|
+
"200": {
|
|
212
|
+
"$body": [
|
|
213
|
+
"not_empty",
|
|
214
|
+
"contains:logged in user session"
|
|
215
|
+
]
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
## Response Body & Header Assertion Rules
|
|
226
|
+
|
|
227
|
+
Inside `endpoints -> <METHOD /path> -> expected_response -> <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:
|
|
228
|
+
|
|
229
|
+
| Rule Syntax | Example | Behavior |
|
|
230
|
+
| :--- | :--- | :--- |
|
|
231
|
+
| **Exact Match** | `"status": "available"` | Verifies exact value and data type (`int`, `str`, `bool`). |
|
|
232
|
+
| **Plain-Text Body** | `"$body": ["not_empty", "contains:session"]` | Validates `text/plain` response bodies directly. |
|
|
233
|
+
| **Dynamic Variable** | `"id": "{{petId}}"` | Injects captured setup variable while preserving its type. |
|
|
234
|
+
| **`not_empty`** | `"token": "not_empty"` | Fails if value is `null`, `""`, `[]`, or `{}`. |
|
|
235
|
+
| **`contains:<text>`** | `"message": "contains:Success"` | Fails if `<text>` is not found in the response value. |
|
|
236
|
+
| **`not_contains:<text>`** | `"error": "not_contains:Exception"` | Fails if unwanted text appears in the response value. |
|
|
237
|
+
| **`regex:<pattern>`** | `"date": "regex:^\\d{4}-\\d{2}-\\d{2}"` | Validates string against a regular expression. |
|
|
238
|
+
| **`gt:` / `gte:` / `lt:` / `lte:`** | `"id": ["not_empty", "gt:0"]` | Performs numeric comparisons on integers or floats. |
|
|
239
|
+
| **`exact:<json>`** | `"tags": "exact:[\"tag1\", \"tag2\"]"` | Forces an exact list/object match instead of treating a list as multiple rules. |
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
## Security & Sensitive Data Masking
|
|
244
|
+
|
|
245
|
+
* **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 HTML reports.
|
|
246
|
+
* **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.
|
|
247
|
+
|
|
248
|
+
---
|