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
|
File without changes
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import glob
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
GITHUB_WORKFLOW_YAML = """name: OpenAPI Contract & Functional Tests
|
|
9
|
+
|
|
10
|
+
on:
|
|
11
|
+
push:
|
|
12
|
+
branches: [ main ]
|
|
13
|
+
pull_request:
|
|
14
|
+
branches: [ main ]
|
|
15
|
+
workflow_dispatch:
|
|
16
|
+
inputs:
|
|
17
|
+
env:
|
|
18
|
+
description: 'Target environment (e.g., sandbox, staging)'
|
|
19
|
+
required: false
|
|
20
|
+
default: 'sandbox'
|
|
21
|
+
|
|
22
|
+
jobs:
|
|
23
|
+
api-contract-tests:
|
|
24
|
+
runs-on: ubuntu-latest
|
|
25
|
+
steps:
|
|
26
|
+
- name: Checkout repository
|
|
27
|
+
uses: actions/checkout@v4
|
|
28
|
+
|
|
29
|
+
- name: Set up Python
|
|
30
|
+
uses: actions/setup-python@v5
|
|
31
|
+
with:
|
|
32
|
+
python-version: '3.12'
|
|
33
|
+
|
|
34
|
+
- name: Install dependencies
|
|
35
|
+
run: |
|
|
36
|
+
python -m pip install --upgrade pip
|
|
37
|
+
pip install -r requirements.txt
|
|
38
|
+
|
|
39
|
+
- name: Validate OpenAPI & test_data configurations
|
|
40
|
+
run: openapi-contract validate
|
|
41
|
+
|
|
42
|
+
- name: Run OpenAPI Contract Tests
|
|
43
|
+
env:
|
|
44
|
+
API_TOKEN: ${{ secrets.API_TOKEN }}
|
|
45
|
+
run: |
|
|
46
|
+
TARGET_ENV="${{ github.event.inputs.env || 'sandbox' }}"
|
|
47
|
+
pytest --env="$TARGET_ENV" --html=reports/report.html --self-contained-html
|
|
48
|
+
|
|
49
|
+
- name: Upload HTML Test Report
|
|
50
|
+
if: always()
|
|
51
|
+
uses: actions/upload-artifact@v4
|
|
52
|
+
with:
|
|
53
|
+
name: api-contract-report
|
|
54
|
+
path: reports/report.html
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
DEFAULT_PYTEST_INI = """[pytest]
|
|
58
|
+
testpaths = tests
|
|
59
|
+
python_files = test_*.py
|
|
60
|
+
python_functions = test_*
|
|
61
|
+
addopts = -v -s -m api --html=reports/report.html --self-contained-html
|
|
62
|
+
markers =
|
|
63
|
+
unit: Offline unit tests validating internal framework helpers and loaders
|
|
64
|
+
api: Live API contract tests generated dynamically from OpenAPI specs
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
DEFAULT_REQUIREMENTS = """pytest>=7.0.0
|
|
68
|
+
requests>=2.31.0
|
|
69
|
+
pytest-html>=4.1.0
|
|
70
|
+
pytest-openapi-contract>=0.1.0
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
DEFAULT_CONFTEST = '''"""
|
|
74
|
+
Project-level conftest.py for custom hooks or project-specific fixtures.
|
|
75
|
+
Core OpenAPI contract fixtures and CLI flags (--suite, --env, --unmask)
|
|
76
|
+
are automatically provided by the installed 'pytest-openapi-contract' plugin.
|
|
77
|
+
"""
|
|
78
|
+
import pytest
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@pytest.fixture(scope="session")
|
|
82
|
+
def custom_project_headers():
|
|
83
|
+
"""Add any project-wide custom headers here if needed."""
|
|
84
|
+
return {}
|
|
85
|
+
'''
|
|
86
|
+
|
|
87
|
+
SAMPLE_TEST_DATA = {
|
|
88
|
+
"environments": {
|
|
89
|
+
"sandbox": {
|
|
90
|
+
"spec_url": "https://swagger.io",
|
|
91
|
+
"server_url": "https://swagger.io",
|
|
92
|
+
"security": {
|
|
93
|
+
"headers": {
|
|
94
|
+
"api_key": "special-key"
|
|
95
|
+
},
|
|
96
|
+
"query_params": {}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
"setup_resources": [],
|
|
101
|
+
"teardown_resources": [],
|
|
102
|
+
"global_params": {
|
|
103
|
+
"username": "user1",
|
|
104
|
+
"petId": 10,
|
|
105
|
+
"status": "available"
|
|
106
|
+
},
|
|
107
|
+
"endpoints": {
|
|
108
|
+
"GET /pet/{petId}": {
|
|
109
|
+
"path_params": {
|
|
110
|
+
"petId": "{{petId}}"
|
|
111
|
+
},
|
|
112
|
+
"expected_response": {
|
|
113
|
+
"200": {
|
|
114
|
+
"id": 10,
|
|
115
|
+
"status": "available"
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
def _collect_placeholders(obj):
|
|
123
|
+
"""Recursively finds all {{var_name}} placeholders inside a nested dict/list/str."""
|
|
124
|
+
found = set()
|
|
125
|
+
if isinstance(obj, str):
|
|
126
|
+
found.update(re.findall(r"\{\{([^{}]+)\}\}", obj))
|
|
127
|
+
elif isinstance(obj, dict):
|
|
128
|
+
for v in obj.values():
|
|
129
|
+
found.update(_collect_placeholders(v))
|
|
130
|
+
elif isinstance(obj, list):
|
|
131
|
+
for item in obj:
|
|
132
|
+
found.update(_collect_placeholders(item))
|
|
133
|
+
return found
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _check_refs_and_regex(obj, full_spec, errors, path="root"):
|
|
137
|
+
"""Recursively checks for broken $ref pointers and invalid regex: rules."""
|
|
138
|
+
if isinstance(obj, dict):
|
|
139
|
+
if "$ref" in obj and isinstance(obj["$ref"], str):
|
|
140
|
+
ref_str = obj["$ref"]
|
|
141
|
+
if ref_str.startswith("#/"):
|
|
142
|
+
parts = ref_str[2:].split("/")
|
|
143
|
+
cursor = full_spec
|
|
144
|
+
for p in parts:
|
|
145
|
+
if isinstance(cursor, dict) and p in cursor:
|
|
146
|
+
cursor = cursor[p]
|
|
147
|
+
else:
|
|
148
|
+
errors.append(f"Broken $ref pointer '{ref_str}' at {path}")
|
|
149
|
+
break
|
|
150
|
+
for k, v in obj.items():
|
|
151
|
+
_check_refs_and_regex(v, full_spec, errors, f"{path}.{k}")
|
|
152
|
+
elif isinstance(obj, list):
|
|
153
|
+
for idx, item in enumerate(obj):
|
|
154
|
+
_check_refs_and_regex(item, full_spec, errors, f"{path}[{idx}]")
|
|
155
|
+
elif isinstance(obj, str) and obj.startswith("regex:"):
|
|
156
|
+
pattern = obj.split("regex:", 1)[1]
|
|
157
|
+
try:
|
|
158
|
+
re.compile(pattern)
|
|
159
|
+
except re.error as e:
|
|
160
|
+
errors.append(f"Invalid regex pattern '{pattern}' at {path}: {e}")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def validate_specs_directory(specs_dir: str) -> int:
|
|
164
|
+
"""Validates all suite folders in specs/ offline. Returns 0 if valid, 1 on errors."""
|
|
165
|
+
root = Path(specs_dir).resolve()
|
|
166
|
+
if not root.is_dir():
|
|
167
|
+
print(f"[ERROR] Specs directory not found: {root}")
|
|
168
|
+
return 1
|
|
169
|
+
|
|
170
|
+
suite_dirs = sorted({Path(p).parent for p in glob.glob(str(root / "*" / "*.json"))})
|
|
171
|
+
if not suite_dirs:
|
|
172
|
+
print(f"[WARNING] No service suites found in {root}")
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
total_errors = 0
|
|
176
|
+
for suite_dir in suite_dirs:
|
|
177
|
+
suite_name = suite_dir.name
|
|
178
|
+
errors = []
|
|
179
|
+
spec_file = suite_dir / "openapi.json"
|
|
180
|
+
data_file = suite_dir / "test_data.json"
|
|
181
|
+
|
|
182
|
+
openapi_doc = {}
|
|
183
|
+
test_data_doc = {}
|
|
184
|
+
|
|
185
|
+
if spec_file.exists():
|
|
186
|
+
try:
|
|
187
|
+
openapi_doc = json.loads(spec_file.read_text(encoding="utf-8"))
|
|
188
|
+
_check_refs_and_regex(openapi_doc, openapi_doc, errors, "openapi.json")
|
|
189
|
+
except json.JSONDecodeError as e:
|
|
190
|
+
errors.append(f"Malformed JSON in openapi.json: {e}")
|
|
191
|
+
|
|
192
|
+
if data_file.exists():
|
|
193
|
+
try:
|
|
194
|
+
test_data_doc = json.loads(data_file.read_text(encoding="utf-8"))
|
|
195
|
+
_check_refs_and_regex(test_data_doc, openapi_doc, errors, "test_data.json")
|
|
196
|
+
|
|
197
|
+
# Verify all {{variables}} are defined in setup_resources.extract or global_params
|
|
198
|
+
defined_vars = set(test_data_doc.get("global_params", {}).keys())
|
|
199
|
+
for step in test_data_doc.get("setup_resources", []):
|
|
200
|
+
if isinstance(step, dict) and isinstance(step.get("extract"), dict):
|
|
201
|
+
defined_vars.update(step["extract"].keys())
|
|
202
|
+
|
|
203
|
+
used_vars = _collect_placeholders(test_data_doc.get("endpoints", {}))
|
|
204
|
+
used_vars.update(_collect_placeholders(test_data_doc.get("teardown_resources", [])))
|
|
205
|
+
used_vars.update(_collect_placeholders(test_data_doc.get("environments", {})))
|
|
206
|
+
|
|
207
|
+
for var in sorted(used_vars - defined_vars):
|
|
208
|
+
errors.append(
|
|
209
|
+
f"Undefined variable '{{{{{var}}}}}' in test_data.json "
|
|
210
|
+
f"(not found in setup_resources.extract or global_params)"
|
|
211
|
+
)
|
|
212
|
+
except json.JSONDecodeError as e:
|
|
213
|
+
errors.append(f"Malformed JSON in test_data.json: {e}")
|
|
214
|
+
|
|
215
|
+
if errors:
|
|
216
|
+
print(f"\n[FAIL] Suite '{suite_name}' has {len(errors)} configuration error(s):")
|
|
217
|
+
for err in errors:
|
|
218
|
+
print(f" - {err}")
|
|
219
|
+
total_errors += len(errors)
|
|
220
|
+
else:
|
|
221
|
+
print(f"[PASS] Suite '{suite_name}' validated cleanly.")
|
|
222
|
+
|
|
223
|
+
return 1 if total_errors > 0 else 0
|
|
224
|
+
|
|
225
|
+
def write_file_safely(file_path: Path, content: str, force: bool = False):
|
|
226
|
+
"""Writes a template file unless it already exists (overwrites if --force is used)."""
|
|
227
|
+
if file_path.exists() and not force:
|
|
228
|
+
print(f" [SKIP] {file_path} (already exists)")
|
|
229
|
+
return
|
|
230
|
+
file_path.write_text(content, encoding="utf-8")
|
|
231
|
+
print(f" [CREATE] {file_path}")
|
|
232
|
+
|
|
233
|
+
def scaffold_project(target_dir: str, suite_name: str, force: bool = False, with_ci: bool = False):
|
|
234
|
+
"""Creates the complete directory structure and starter files for an API test project."""
|
|
235
|
+
root = Path(target_dir).resolve()
|
|
236
|
+
print(f"\nInitializing OpenAPI Contract Test Project in: {root}\n")
|
|
237
|
+
|
|
238
|
+
# 1. Create required directories
|
|
239
|
+
dirs_to_create = [
|
|
240
|
+
root / "reports",
|
|
241
|
+
root / "specs" / suite_name,
|
|
242
|
+
root / "tests",
|
|
243
|
+
]
|
|
244
|
+
|
|
245
|
+
if with_ci:
|
|
246
|
+
dirs_to_create.append(root / ".github" / "workflows")
|
|
247
|
+
|
|
248
|
+
for d in dirs_to_create:
|
|
249
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
250
|
+
print(f" [DIR] {d.relative_to(root)}/")
|
|
251
|
+
|
|
252
|
+
# 2. Create starter configuration & test files
|
|
253
|
+
write_file_safely(root / "pytest.ini", DEFAULT_PYTEST_INI, force)
|
|
254
|
+
write_file_safely(root / "requirements.txt", DEFAULT_REQUIREMENTS, force)
|
|
255
|
+
write_file_safely(root / "tests" / "conftest.py", DEFAULT_CONFTEST, force)
|
|
256
|
+
write_file_safely(root / "reports" / ".gitkeep", "", force)
|
|
257
|
+
|
|
258
|
+
if with_ci:
|
|
259
|
+
workflow_path = root / ".github" / "workflows" / "api-contract-tests.yml"
|
|
260
|
+
write_file_safely(workflow_path, GITHUB_WORKFLOW_YAML, force)
|
|
261
|
+
|
|
262
|
+
# 3. Create sample service test_data.json
|
|
263
|
+
sample_data_path = root / "specs" / suite_name / "test_data.json"
|
|
264
|
+
write_file_safely(sample_data_path, json.dumps(SAMPLE_TEST_DATA, indent=2) + "\n", force)
|
|
265
|
+
|
|
266
|
+
print("\nProject initialized successfully!")
|
|
267
|
+
print("Next steps:")
|
|
268
|
+
print(f" 1. Review/edit specs/{suite_name}/test_data.json with your API's spec_url and server_url")
|
|
269
|
+
print(" 2. Run 'pytest' to download the live spec, run contract tests, and generate reports/report.html\n")
|
|
270
|
+
|
|
271
|
+
def main():
|
|
272
|
+
parser = argparse.ArgumentParser(
|
|
273
|
+
prog="openapi-contract",
|
|
274
|
+
description="CLI utilities for pytest-openapi-contract"
|
|
275
|
+
)
|
|
276
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
277
|
+
|
|
278
|
+
# Subcommand: init-project
|
|
279
|
+
init_parser = subparsers.add_parser(
|
|
280
|
+
"init-project",
|
|
281
|
+
help="Scaffold folders (specs/, tests/, reports/) and starter template files"
|
|
282
|
+
)
|
|
283
|
+
init_parser.add_argument(
|
|
284
|
+
"--path",
|
|
285
|
+
default=".",
|
|
286
|
+
help="Target directory to initialize (defaults to current folder)"
|
|
287
|
+
)
|
|
288
|
+
init_parser.add_argument(
|
|
289
|
+
"--suite",
|
|
290
|
+
default="sample_service",
|
|
291
|
+
help="Name of the initial starter service folder inside specs/ (default: sample_service)"
|
|
292
|
+
)
|
|
293
|
+
init_parser.add_argument(
|
|
294
|
+
"--force",
|
|
295
|
+
action="store_true",
|
|
296
|
+
help="Overwrite existing template files if they already exist"
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
init_parser.add_argument(
|
|
300
|
+
"--with-ci",
|
|
301
|
+
action="store_true",
|
|
302
|
+
help="Also generate a starter GitHub Actions workflow (.github/workflows/api-contract-tests.yml)"
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
val_parser = subparsers.add_parser(
|
|
306
|
+
"validate",
|
|
307
|
+
help="Validate openapi.json and test_data.json syntax, $ref pointers, regexes, and variables offline"
|
|
308
|
+
)
|
|
309
|
+
val_parser.add_argument(
|
|
310
|
+
"--specs-dir",
|
|
311
|
+
default="specs",
|
|
312
|
+
help="Path to the specs directory (default: specs)"
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
args = parser.parse_args()
|
|
316
|
+
|
|
317
|
+
if args.command == "init-project":
|
|
318
|
+
scaffold_project(target_dir=args.path, suite_name=args.suite, force=args.force, with_ci=args.with_ci)
|
|
319
|
+
elif args.command == "validate":
|
|
320
|
+
raise SystemExit(validate_specs_directory(args.specs_dir))
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
if __name__ == "__main__":
|
|
324
|
+
main()
|