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.
@@ -0,0 +1,985 @@
1
+ import json
2
+ import os
3
+ import pytest
4
+ import requests
5
+ import glob
6
+ import html
7
+ import tempfile
8
+ from filelock import FileLock
9
+ from . import helpers
10
+ from requests.adapters import HTTPAdapter
11
+ from urllib3.util.retry import Retry
12
+ from urllib.parse import urlparse
13
+ from .helpers import (
14
+ generate_mock_data_from_schema,
15
+ generate_invalid_enum_payload,
16
+ inject_dynamic_variables
17
+ )
18
+
19
+ ALL_LOADED_SPECS = {}
20
+
21
+ @pytest.fixture(scope="session")
22
+ def auth_headers():
23
+ return {
24
+ "Content-Type": "application/json"
25
+ }
26
+
27
+ @pytest.fixture(scope="session")
28
+ def http_session():
29
+ """
30
+ Provides a persistent requests.Session with automatic exponential backoff
31
+ retries for rate limits (429) and transient gateway errors (502, 503, 504).
32
+ """
33
+ session = requests.Session()
34
+
35
+ retry_strategy = Retry(
36
+ total=3, # Maximum 3 retry attempts
37
+ backoff_factor=1, # Wait 1s, then 2s, then 4s between retries
38
+ status_forcelist=[429, 502, 503, 504], # Retry on rate limits & gateway timeouts
39
+ allowed_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
40
+ respect_retry_after_header=True # Honor 'Retry-After' headers on 429 limits
41
+ )
42
+
43
+ adapter = HTTPAdapter(max_retries=retry_strategy)
44
+ session.mount("http://", adapter)
45
+ session.mount("https://", adapter)
46
+
47
+ yield session
48
+ session.close()
49
+
50
+ def _extract_nested_value(data, dot_path):
51
+ """Extracts a value from a nested dictionary or list using dot notation (e.g., 'data.id')."""
52
+ current = data
53
+ for part in str(dot_path).split("."):
54
+ if isinstance(current, dict) and part in current:
55
+ current = current[part]
56
+ elif isinstance(current, list) and part.isdigit() and int(part) < len(current):
57
+ current = current[int(part)]
58
+ else:
59
+ return None
60
+ return current
61
+
62
+
63
+ def _resolve_suite_security(seed_data, target_env):
64
+ """Finds the security dictionary matching target_env from test_data.json."""
65
+ envs_block = seed_data.get("environments", {})
66
+ if isinstance(envs_block, dict) and envs_block:
67
+ target_lower = target_env.strip().lower()
68
+ if target_lower != "all":
69
+ for env_name, cfg in envs_block.items():
70
+ if env_name.strip().lower() == target_lower:
71
+ return cfg.get("security", {"headers": {}, "query_params": {}})
72
+ first_cfg = next(iter(envs_block.values()))
73
+ return first_cfg.get("security", {"headers": {}, "query_params": {}})
74
+
75
+ raw_sec = seed_data.get("security", {})
76
+ if isinstance(raw_sec, dict):
77
+ return raw_sec
78
+ return {"headers": {}, "query_params": {}}
79
+
80
+
81
+ def _run_all_suite_setups(specs_root, target_suite, target_env, http_session, auth_headers):
82
+ """Executes setup_resources for all matching suites and returns extracted variables per suite."""
83
+ suite_vars_map = {}
84
+
85
+ if target_suite == "all":
86
+ suite_dirs = sorted({os.path.dirname(p) for p in glob.glob(os.path.join(specs_root, "*/*.json"))})
87
+ else:
88
+ suite_dirs = [os.path.join(specs_root, target_suite)]
89
+
90
+ for suite_dir in suite_dirs:
91
+ if not os.path.isdir(suite_dir):
92
+ continue
93
+
94
+ suite_name = os.path.basename(suite_dir)
95
+ test_data_path = os.path.join(suite_dir, "test_data.json")
96
+ if not os.path.exists(test_data_path):
97
+ suite_vars_map[suite_name] = {}
98
+ continue
99
+
100
+ with open(test_data_path, "r", encoding="utf-8") as f:
101
+ seed_data = json.load(f)
102
+
103
+ extracted_vars = {}
104
+ sec_block = _resolve_suite_security(seed_data, target_env)
105
+ base_headers = {**auth_headers, **sec_block.get("headers", {})}
106
+ base_query = dict(sec_block.get("query_params", {}))
107
+
108
+ for step in seed_data.get("setup_resources", []):
109
+ method = step.get("method", "POST").upper()
110
+ url = inject_dynamic_variables(step.get("url", ""), extracted_vars)
111
+ payload = inject_dynamic_variables(step.get("payload"), extracted_vars)
112
+ step_headers = {**base_headers, **inject_dynamic_variables(step.get("headers", {}), extracted_vars)}
113
+ step_query = {**base_query, **inject_dynamic_variables(step.get("query_params", {}), extracted_vars)}
114
+
115
+ resp = http_session.request(
116
+ method=method,
117
+ url=url,
118
+ headers=step_headers,
119
+ params=step_query if step_query else None,
120
+ json=payload,
121
+ timeout=15
122
+ )
123
+ resp.raise_for_status()
124
+
125
+ extract_rules = step.get("extract", {})
126
+ if extract_rules:
127
+ resp_json = resp.json()
128
+ for var_name, json_path in extract_rules.items():
129
+ val = _extract_nested_value(resp_json, json_path)
130
+ if val is not None:
131
+ extracted_vars[var_name] = val
132
+
133
+ suite_vars_map[suite_name] = extracted_vars
134
+
135
+ return suite_vars_map
136
+
137
+ def _run_all_suite_teardowns(specs_root, target_suite, target_env, suite_vars_map, http_session, auth_headers):
138
+ """Executes teardown_resources for all matching suites using the extracted session variables."""
139
+ if target_suite == "all":
140
+ suite_dirs = sorted({os.path.dirname(p) for p in glob.glob(os.path.join(specs_root, "*/*.json"))})
141
+ else:
142
+ suite_dirs = [os.path.join(specs_root, target_suite)]
143
+
144
+ for suite_dir in suite_dirs:
145
+ if not os.path.isdir(suite_dir):
146
+ continue
147
+
148
+ suite_name = os.path.basename(suite_dir)
149
+ test_data_path = os.path.join(suite_dir, "test_data.json")
150
+ if not os.path.exists(test_data_path):
151
+ continue
152
+
153
+ with open(test_data_path, "r", encoding="utf-8") as f:
154
+ seed_data = json.load(f)
155
+
156
+ extracted_vars = suite_vars_map.get(suite_name, {})
157
+ sec_block = _resolve_suite_security(seed_data, target_env)
158
+ base_headers = {**auth_headers, **sec_block.get("headers", {})}
159
+ base_query = dict(sec_block.get("query_params", {}))
160
+
161
+ for step in seed_data.get("teardown_resources", []):
162
+ method = step.get("method", "DELETE").upper()
163
+ url = inject_dynamic_variables(step.get("url", ""), extracted_vars)
164
+ payload = inject_dynamic_variables(step.get("payload"), extracted_vars)
165
+ step_headers = {**base_headers, **inject_dynamic_variables(step.get("headers", {}), extracted_vars)}
166
+ step_query = {**base_query, **inject_dynamic_variables(step.get("query_params", {}), extracted_vars)}
167
+
168
+ try:
169
+ http_session.request(
170
+ method=method,
171
+ url=url,
172
+ headers=step_headers,
173
+ params=step_query if step_query else None,
174
+ json=payload,
175
+ timeout=15
176
+ )
177
+ except Exception as e:
178
+ print(f"\n[{suite_name} Teardown Warning] Failed to run {method} {url}: {e}")
179
+
180
+ @pytest.fixture(scope="session")
181
+ def created_resource_ids(request, http_session, auth_headers):
182
+ """
183
+ Executes setup_resources once per test session (even when running in parallel
184
+ with pytest-xdist '-n auto') using a session-scoped file lock, shares extracted
185
+ IDs across all workers, and runs teardown_resources once after all workers finish.
186
+ """
187
+ target_suite = request.config.getoption("--suite")
188
+ target_env = request.config.getoption("--env")
189
+ specs_root = os.path.join(os.getcwd(), "specs")
190
+
191
+ # Scope state files to the current test run UID (or current PID if not using xdist)
192
+ run_uid = os.environ.get("PYTEST_XDIST_TESTRUNUID") or f"pid_{os.getppid()}"
193
+ lock_dir = os.path.join(tempfile.gettempdir(), "pytest_openapi_contract_state", run_uid)
194
+ os.makedirs(lock_dir, exist_ok=True)
195
+
196
+ state_file = os.path.join(lock_dir, f"state_{target_suite}_{target_env}.json")
197
+ lock_file = f"{state_file}.lock"
198
+ refcount_file = f"{state_file}.workers"
199
+
200
+ with FileLock(lock_file):
201
+ active_workers = 0
202
+ if os.path.exists(refcount_file):
203
+ with open(refcount_file, "r", encoding="utf-8") as rf:
204
+ active_workers = int(rf.read().strip() or "0")
205
+ active_workers += 1
206
+ with open(refcount_file, "w", encoding="utf-8") as rf:
207
+ rf.write(str(active_workers))
208
+
209
+ # Run setup if first worker OR if state_file is missing (self-healing)
210
+ if active_workers == 1 or not os.path.exists(state_file):
211
+ suite_vars_map = _run_all_suite_setups(specs_root, target_suite, target_env, http_session, auth_headers)
212
+ with open(state_file, "w", encoding="utf-8") as sf:
213
+ json.dump(suite_vars_map, sf)
214
+ else:
215
+ with open(state_file, "r", encoding="utf-8") as sf:
216
+ suite_vars_map = json.load(sf)
217
+
218
+ yield suite_vars_map
219
+
220
+ with FileLock(lock_file):
221
+ remaining = 0
222
+ if os.path.exists(refcount_file):
223
+ with open(refcount_file, "r", encoding="utf-8") as rf:
224
+ remaining = max(0, int(rf.read().strip() or "1") - 1)
225
+
226
+ if remaining == 0:
227
+ _run_all_suite_teardowns(specs_root, target_suite, target_env, suite_vars_map, http_session, auth_headers)
228
+ for f_path in (state_file, refcount_file):
229
+ if os.path.exists(f_path):
230
+ os.remove(f_path)
231
+ else:
232
+ with open(refcount_file, "w", encoding="utf-8") as rf:
233
+ rf.write(str(remaining))
234
+
235
+ def get_response_spec_for_status(details, status_code):
236
+ """
237
+ Extracts (content_type, schema) for a given HTTP status code (e.g., 400 or 401).
238
+ Falls back to the OpenAPI 'default' error response if the exact code is omitted.
239
+ """
240
+ responses = details.get("responses", {})
241
+ status_obj = responses.get(str(status_code)) or responses.get("default", {})
242
+ content = status_obj.get("content", {})
243
+
244
+ if not content:
245
+ return None, None
246
+
247
+ # Prioritize application/json if multiple error formats exist, otherwise take the first
248
+ resp_ct = "application/json" if "application/json" in content else next(iter(content))
249
+ resp_schema = content[resp_ct].get("schema")
250
+ return resp_ct, resp_schema
251
+
252
+ def compare_openapi_specs(suite_name, local_spec, live_spec):
253
+ """
254
+ Compares the local baseline OpenAPI spec against the live downloaded spec
255
+ and prints a summary of any discrepancies (added, removed, or modified routes/schemas).
256
+ """
257
+ if local_spec == live_spec:
258
+ print(f"\n[{suite_name} Spec Check] Live spec matches local baseline cleanly.")
259
+ return
260
+
261
+ print(f"\n==================== [{suite_name} SPEC DRIFT DETECTED] ====================")
262
+
263
+ local_paths = set(local_spec.get("paths", {}).keys())
264
+ live_paths = set(live_spec.get("paths", {}).keys())
265
+
266
+ # 1. Check for added or removed routes
267
+ added_paths = live_paths - local_paths
268
+ removed_paths = local_paths - live_paths
269
+
270
+ for p in sorted(added_paths):
271
+ print(f" [+ ADDED ROUTE] {p} (Present in live API, missing in local spec)")
272
+ for p in sorted(removed_paths):
273
+ print(f" [- REMOVED ROUTE] {p} (Present in local spec, missing in live API)")
274
+
275
+ # 2. Check for method or parameter/schema changes on shared routes
276
+ for p in sorted(local_paths & live_paths):
277
+ if local_spec["paths"][p] != live_spec["paths"][p]:
278
+ print(f" [~ MODIFIED ROUTE] {p} (Method, parameters, or response schema changed)")
279
+
280
+ # 3. Check for schema changes under components/schemas
281
+ local_schemas = set(local_spec.get("components", {}).get("schemas", {}).keys())
282
+ live_schemas = set(live_spec.get("components", {}).get("schemas", {}).keys())
283
+
284
+ for s in sorted(live_schemas - local_schemas):
285
+ print(f" [+ ADDED SCHEMA] {s}")
286
+ for s in sorted(local_schemas - live_schemas):
287
+ print(f" [- REMOVED SCHEMA] {s}")
288
+ for s in sorted(local_schemas & live_schemas):
289
+ if local_spec["components"]["schemas"][s] != live_spec["components"]["schemas"][s]:
290
+ print(f" [~ MODIFIED SCHEMA] {s}")
291
+
292
+ print("=========================================================================\n")
293
+
294
+ def extract_openapi_example(obj):
295
+ """
296
+ Extracts an example value from a Parameter or MediaType object if present.
297
+ Supports both singular 'example' and OpenAPI 3.0 named 'examples' maps.
298
+ """
299
+ if not isinstance(obj, dict):
300
+ return None
301
+
302
+ if "example" in obj and obj["example"] is not None:
303
+ return obj["example"]
304
+
305
+ examples_map = obj.get("examples")
306
+ if isinstance(examples_map, dict) and examples_map:
307
+ first_example = next(iter(examples_map.values()))
308
+ if isinstance(first_example, dict) and "value" in first_example:
309
+ return first_example["value"]
310
+
311
+ return None
312
+
313
+ def resolve_target_environments(spec_data, seed_data, target_env="all"):
314
+ """
315
+ Resolves active (env_name, base_url, spec_url, security_dict) tuples
316
+ from the 'environments' block in test_data.json, filtered by --env.
317
+ Falls back to openapi.json 'servers' if 'environments' is omitted.
318
+ """
319
+ envs_block = seed_data.get("environments", {})
320
+ env_override_spec = os.getenv("OPENAPI_SPEC_URL")
321
+ target_lower = target_env.strip().lower()
322
+ active_envs = []
323
+
324
+ if isinstance(envs_block, dict) and envs_block:
325
+ for env_name, cfg in envs_block.items():
326
+ clean_label = env_name.strip().replace(" ", "_")
327
+ if target_lower != "all" and clean_label.lower() != target_lower:
328
+ continue
329
+
330
+ matched_spec_url = env_override_spec or cfg.get("spec_url")
331
+ base_url = cfg.get("server_url", "").rstrip("/")
332
+
333
+ # Prepend spec_url domain if server_url is relative (e.g., "/api/v3")
334
+ if base_url.startswith("/") and matched_spec_url:
335
+ parsed = urlparse(matched_spec_url)
336
+ base_url = f"{parsed.scheme}://{parsed.netloc}{base_url}"
337
+
338
+ matched_security = cfg.get("security", {"headers": {}, "query_params": {}})
339
+ active_envs.append((clean_label, base_url, matched_spec_url, matched_security))
340
+
341
+ return active_envs
342
+
343
+ # Fallback if test_data.json does not define 'environments'
344
+ raw_servers = spec_data.get("servers") or [{"name": "default", "url": "https://httpbin.org"}]
345
+ for idx, srv in enumerate(raw_servers):
346
+ env_label = (srv.get("name") or srv.get("description") or f"env_{idx}").strip().replace(" ", "_")
347
+ if target_lower != "all" and env_label.lower() != target_lower:
348
+ continue
349
+
350
+ base_url = srv.get("url", "").rstrip("/")
351
+ if base_url.startswith("/") and env_override_spec:
352
+ parsed = urlparse(env_override_spec)
353
+ base_url = f"{parsed.scheme}://{parsed.netloc}{base_url}"
354
+
355
+ active_envs.append((env_label, base_url, env_override_spec, {"headers": {}, "query_params": {}}))
356
+
357
+ return active_envs
358
+
359
+ def load_openapi_specs(target_suite="all", target_env="all", specs_root=None, update_spec=False):
360
+ global ALL_LOADED_SPECS
361
+ ALL_LOADED_SPECS = {}
362
+ all_test_cases = []
363
+
364
+ if specs_root is None:
365
+ specs_root = os.path.join(os.getcwd(), "specs")
366
+
367
+ VALID_HTTP_METHODS = {"get", "post", "put", "patch", "delete", "head", "options"}
368
+
369
+ # Find all specs/<suite_name>/openapi.json files
370
+ suite_dirs = set()
371
+ if target_suite == "all":
372
+ for f_path in glob.glob(os.path.join(specs_root, "*/*.json")):
373
+ suite_dirs.add(os.path.dirname(f_path))
374
+ else:
375
+ suite_dirs.add(os.path.join(specs_root, target_suite))
376
+
377
+ for suite_dir in sorted(suite_dirs):
378
+ if not os.path.isdir(suite_dir):
379
+ continue
380
+
381
+ suite_name = os.path.basename(suite_dir)
382
+ spec_path = os.path.join(suite_dir, "openapi.json")
383
+ test_data_path = os.path.join(suite_dir, "test_data.json")
384
+
385
+ # Load suite-specific test_data.json first to check for a live 'spec_url'
386
+ seed_data = {"global_params": {}, "endpoints": {}}
387
+ if os.path.exists(test_data_path):
388
+ with open(test_data_path, "r") as f:
389
+ seed_data = json.load(f)
390
+
391
+ # Load local baseline copy first if it exists
392
+ local_spec = {}
393
+ if os.path.exists(spec_path):
394
+ with open(spec_path, "r") as f:
395
+ local_spec = json.load(f)
396
+
397
+ # Determine which spec_url to download based on --env
398
+ env_override_spec = os.getenv("OPENAPI_SPEC_URL")
399
+ envs_block = seed_data.get("environments", {})
400
+ spec_url = env_override_spec
401
+
402
+ if not spec_url and isinstance(envs_block, dict) and envs_block:
403
+ if target_env.lower() != "all" and target_env in envs_block:
404
+ spec_url = envs_block[target_env].get("spec_url")
405
+ else:
406
+ first_env_cfg = next(iter(envs_block.values()))
407
+ spec_url = first_env_cfg.get("spec_url")
408
+
409
+ live_spec = {}
410
+ # 3. Download live OpenAPI JSON if spec_url is configured
411
+ if spec_url:
412
+ try:
413
+ spec_headers = seed_data.get("spec_headers", {})
414
+ spec_params = seed_data.get("spec_params", {})
415
+ resp = requests.get(spec_url, headers=spec_headers, params=spec_params, timeout=10)
416
+ resp.raise_for_status()
417
+ live_spec = resp.json()
418
+ print(f"\n[{suite_name}] Downloaded live OpenAPI spec from {spec_url}")
419
+ except Exception as e:
420
+ print(f"\n[{suite_name} Warning] Live spec download failed ({e}). Falling back to local file...")
421
+
422
+ # 4. Decide which spec to use and log discrepancies
423
+ if local_spec and live_spec:
424
+ compare_openapi_specs(suite_name, local_spec, live_spec)
425
+ if local_spec != live_spec:
426
+ if update_spec:
427
+ with open(spec_path, "w", encoding="utf-8") as f:
428
+ json.dump(live_spec, f, indent=2)
429
+ print(f"[{suite_name}] Updated local baseline spec at {spec_path} (--update-spec enabled).")
430
+ else:
431
+ print(
432
+ f"[{suite_name}] Local baseline spec was NOT overwritten. Run with --update-spec to save changes.")
433
+ spec_data = live_spec
434
+
435
+ elif not local_spec and live_spec:
436
+ # No local copy existed yet: always save the initial baseline
437
+ with open(spec_path, "w", encoding="utf-8") as f:
438
+ json.dump(live_spec, f, indent=2)
439
+ print(f"[{suite_name}] Saved initial local baseline to {spec_path}")
440
+ spec_data = live_spec
441
+
442
+ elif local_spec:
443
+ spec_data = local_spec
444
+ else:
445
+ continue
446
+
447
+ ALL_LOADED_SPECS[suite_name] = spec_data
448
+
449
+ global_params = seed_data.get("global_params", {})
450
+ endpoint_overrides = seed_data.get("endpoints", {})
451
+ suite_max_ms = seed_data.get("max_response_time_ms")
452
+
453
+ active_envs = resolve_target_environments(spec_data, seed_data, target_env)
454
+
455
+ for env_label, base_url, env_spec_url, env_security in active_envs:
456
+ for path, methods in spec_data.get("paths", {}).items():
457
+ if not isinstance(methods, dict):
458
+ continue
459
+ path_level_params = methods.get("parameters", [])
460
+
461
+ for method, details in methods.items():
462
+ if method.lower() not in VALID_HTTP_METHODS or not isinstance(details, dict):
463
+ continue
464
+
465
+ method_upper = method.upper()
466
+ clean_path_id = path.replace("{", "").replace("}", "")
467
+ route_key = f"{method_upper} {path}".strip()
468
+
469
+ route_seed = endpoint_overrides.get(route_key, {})
470
+ seed_expected_response = route_seed.get("expected_response", {})
471
+
472
+ seed_expected_headers = route_seed.get("expected_headers", {})
473
+ endpoint_max_ms = route_seed.get("max_response_time_ms", suite_max_ms)
474
+
475
+ responses = details.get("responses", {})
476
+ openapi_resp_headers = {}
477
+ for code_str, resp_obj in responses.items():
478
+ if isinstance(resp_obj, dict) and "headers" in resp_obj:
479
+ openapi_resp_headers[str(code_str)] = resp_obj["headers"]
480
+
481
+ seed_path_params = route_seed.get("path_params", {})
482
+ seed_query_params = route_seed.get("query_params", {})
483
+
484
+ # 1. Determine Security Requirements
485
+ has_security = "security" in details or "security" in spec_data
486
+
487
+ # 2. Determine Primary Success Status Code (200, 201, etc.)
488
+ success_status = 200
489
+ for code in responses.keys():
490
+ if str(code).startswith("2"):
491
+ success_status = int(code)
492
+ break
493
+
494
+ # 3. Extract All Success & Error Response Schemas
495
+ success_response_content = responses.get(str(success_status), {}).get("content", {})
496
+ response_variants = []
497
+ if success_response_content:
498
+ for resp_ct, media_obj in success_response_content.items():
499
+ response_variants.append((resp_ct, media_obj.get("schema")))
500
+ else:
501
+ response_variants.append((None, None))
502
+
503
+ err_400_ct, err_400_schema = get_response_spec_for_status(details, 400)
504
+ err_401_ct, err_401_schema = get_response_spec_for_status(details, 401)
505
+ err_500_ct, err_500_schema = get_response_spec_for_status(details, 500)
506
+
507
+ # 4. Parse Path & Query Parameters (Applying Seed Overrides First)
508
+ all_params = path_level_params + details.get("parameters", [])
509
+ resolved_path = path
510
+ query_params = {}
511
+ required_query_params = []
512
+ enum_query_params = []
513
+ enum_path_params = []
514
+
515
+ for param in all_params:
516
+ param_name = param.get("name")
517
+ param_in = param.get("in")
518
+ param_schema = param.get("schema", {"type": "string"})
519
+ param_example = extract_openapi_example(param)
520
+
521
+ if "$ref" in param_schema:
522
+ ref_path = param_schema["$ref"].split("/")
523
+ param_schema = spec_data.get("components", {}).get("schemas", {}).get(ref_path[-1], {})
524
+
525
+ if param_in == "path":
526
+ # 1. Check endpoint-specific path_params first
527
+ if param_name in seed_path_params:
528
+ final_val = seed_path_params[param_name]
529
+ # 2. Check global_params second
530
+ elif param_name in global_params:
531
+ final_val = global_params[param_name]
532
+ elif param_example is not None:
533
+ final_val = param_example
534
+ # 3. Only generate dummy '123' if neither override exists
535
+ else:
536
+ final_val = generate_mock_data_from_schema(param_schema, spec_data)
537
+
538
+ resolved_path = resolved_path.replace(f"{{{param_name}}}", str(final_val))
539
+
540
+ if "enum" in param_schema:
541
+ enum_path_params.append((param_name, param_schema, final_val))
542
+
543
+ elif param_in == "query":
544
+ if param_name in seed_query_params:
545
+ query_params[param_name] = seed_query_params[param_name]
546
+ elif param_name in global_params:
547
+ query_params[param_name] = global_params[param_name]
548
+ elif param.get("required", False):
549
+ query_params[param_name] = (
550
+ param_example if param_example is not None
551
+ else generate_mock_data_from_schema(param_schema, spec_data)
552
+ )
553
+
554
+ if param.get("required", False):
555
+ required_query_params.append(param_name)
556
+ if "enum" in param_schema:
557
+ enum_query_params.append((param_name, param_schema))
558
+
559
+ if isinstance(seed_query_params, dict):
560
+ query_params.update(seed_query_params)
561
+
562
+ # 5. Build Request Body Variants (Per Content-Type)
563
+ request_body_content = details.get("requestBody", {}).get("content", {})
564
+ request_variants = []
565
+
566
+ if request_body_content:
567
+ for content_type, media_obj in request_body_content.items():
568
+ req_schema = media_obj.get("schema")
569
+ media_example = extract_openapi_example(media_obj)
570
+ if media_example is not None:
571
+ payload_data = media_example
572
+ else:
573
+ payload_data = generate_mock_data_from_schema(req_schema,
574
+ spec_data) if req_schema else None
575
+
576
+ seed_payload = route_seed.get("payload")
577
+ if isinstance(payload_data, dict):
578
+ # 1. Apply global_params to any matching keys in the JSON payload
579
+ for g_key, g_val in global_params.items():
580
+ if g_key in payload_data:
581
+ payload_data[g_key] = g_val
582
+
583
+ # 2. Apply endpoint-specific payload overrides on top
584
+ if isinstance(seed_payload, dict):
585
+ payload_data.update(seed_payload)
586
+ elif seed_payload is not None:
587
+ payload_data = seed_payload
588
+ request_variants.append((content_type, payload_data, req_schema))
589
+ else:
590
+ request_variants.append(("application/json", None, None))
591
+
592
+ for content_type, valid_payload, request_schema in request_variants:
593
+ # Clean label for pytest ID (e.g., "application/json" -> "json")
594
+ ct_label = content_type.split("/")[-1]
595
+
596
+ for resp_ct, response_schema in response_variants:
597
+ resp_ct_label = resp_ct.split("/")[-1] if resp_ct else "no-content"
598
+
599
+ # HAPPY PATH
600
+ all_test_cases.append({
601
+ "suite_name": suite_name,
602
+ "env_name": env_label,
603
+ "env_security": env_security,
604
+ "url": f"{base_url}{resolved_path}",
605
+ "method": method_upper,
606
+ "content_type": content_type,
607
+ "query_params": query_params,
608
+ "request_schema": request_schema,
609
+ "expected_status": success_status,
610
+ "requires_auth": has_security,
611
+ "payload": valid_payload,
612
+ "response_content_type": resp_ct,
613
+ "response_schema": response_schema,
614
+ "err_500_ct": err_500_ct,
615
+ "err_500_schema": err_500_schema,
616
+ "expected_response": seed_expected_response,
617
+ "max_response_time_ms": endpoint_max_ms,
618
+ "expected_headers": seed_expected_headers,
619
+ "openapi_resp_headers": openapi_resp_headers,
620
+ "test_type": "HAPPY_PATH",
621
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_req-{ct_label}_res-{resp_ct_label}_HAPPY"
622
+ })
623
+
624
+ # INVALID DATA PAYLOAD
625
+ if isinstance(valid_payload, dict) and method_upper in ["POST", "PUT", "PATCH"]:
626
+ corrupted_payload = {
627
+ k: ({"invalid_nested_object": True} if isinstance(v, str) else "CORRUPTED_STRING_FORCE_ERROR")
628
+ for k, v in valid_payload.items()
629
+ }
630
+ all_test_cases.append({
631
+ "suite_name": suite_name,
632
+ "env_name": env_label,
633
+ "env_security": env_security,
634
+ "url": f"{base_url}{resolved_path}",
635
+ "method": method_upper,
636
+ "content_type": content_type,
637
+ "query_params": query_params,
638
+ "request_schema": request_schema,
639
+ "expected_status": 400,
640
+ "requires_auth": has_security,
641
+ "payload": corrupted_payload,
642
+ "response_content_type": err_400_ct,
643
+ "response_schema": err_400_schema,
644
+ "err_500_ct": err_500_ct,
645
+ "err_500_schema": err_500_schema,
646
+ "expected_response": seed_expected_response,
647
+ "max_response_time_ms": endpoint_max_ms,
648
+ "expected_headers": seed_expected_headers,
649
+ "openapi_resp_headers": openapi_resp_headers,
650
+ "test_type": "INVALID_DATA",
651
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_req-{ct_label}_400_BAD_DATA"
652
+ })
653
+
654
+ # INVALID PAYLOAD ENUM VALUE
655
+ if valid_payload and request_schema and method_upper in ["POST", "PUT", "PATCH"]:
656
+ invalid_enum_payload = generate_invalid_enum_payload(request_schema, spec_data, valid_payload)
657
+ if invalid_enum_payload:
658
+ all_test_cases.append({
659
+ "suite_name": suite_name,
660
+ "env_name": env_label,
661
+ "env_security": env_security,
662
+ "url": f"{base_url}{resolved_path}",
663
+ "method": method_upper,
664
+ "content_type": content_type,
665
+ "query_params": query_params,
666
+ "request_schema": request_schema,
667
+ "expected_status": 400,
668
+ "requires_auth": has_security,
669
+ "payload": invalid_enum_payload,
670
+ "response_content_type": err_400_ct,
671
+ "response_schema": err_400_schema,
672
+ "err_500_ct": err_500_ct,
673
+ "err_500_schema": err_500_schema,
674
+ "expected_response": seed_expected_response,
675
+ "max_response_time_ms": endpoint_max_ms,
676
+ "expected_headers": seed_expected_headers,
677
+ "openapi_resp_headers": openapi_resp_headers,
678
+ "test_type": "INVALID_ENUM",
679
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_req-{ct_label}_400_INVALID_ENUM"
680
+ })
681
+
682
+ default_ct, default_payload, _ = request_variants[0]
683
+ # MISSING AUTH
684
+ if has_security:
685
+ all_test_cases.append({
686
+ "suite_name": suite_name,
687
+ "env_name": env_label,
688
+ "env_security": env_security,
689
+ "url": f"{base_url}{resolved_path}",
690
+ "method": method_upper,
691
+ "content_type": default_ct,
692
+ "query_params": query_params,
693
+ "request_schema": request_schema,
694
+ "expected_status": 401, # httpbin doesn't enforce auth natively without auth endpoints, adjust to 401 for real specs
695
+ "requires_auth": False,
696
+ "payload": default_payload,
697
+ "response_content_type": err_401_ct,
698
+ "response_schema": err_401_schema,
699
+ "err_500_ct": err_500_ct,
700
+ "err_500_schema": err_500_schema,
701
+ "expected_response": seed_expected_response,
702
+ "max_response_time_ms": endpoint_max_ms,
703
+ "expected_headers": seed_expected_headers,
704
+ "openapi_resp_headers": openapi_resp_headers,
705
+ "test_type": "MISSING_AUTH",
706
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_UNAUTHORIZED"
707
+ })
708
+
709
+ # INVALID QUERY ENUM VALUE
710
+ for target_param, target_schema in enum_query_params:
711
+ bad_query_params = query_params.copy()
712
+
713
+ if target_schema.get("type") in ["integer", "number"]:
714
+ bad_query_params[target_param] = -999999
715
+ else:
716
+ bad_query_params[target_param] = "INVALID_ENUM_OPTION_XYZ"
717
+
718
+ all_test_cases.append({
719
+ "suite_name": suite_name,
720
+ "env_name": env_label,
721
+ "env_security": env_security,
722
+ "url": f"{base_url}{resolved_path}",
723
+ "method": method_upper,
724
+ "content_type": default_ct,
725
+ "query_params": bad_query_params,
726
+ "request_schema": request_schema,
727
+ "expected_status": 400,
728
+ "requires_auth": has_security,
729
+ "payload": default_payload,
730
+ "response_content_type": err_400_ct,
731
+ "response_schema": err_400_schema,
732
+ "err_500_ct": err_500_ct,
733
+ "err_500_schema": err_500_schema,
734
+ "expected_response": seed_expected_response,
735
+ "max_response_time_ms": endpoint_max_ms,
736
+ "expected_headers": seed_expected_headers,
737
+ "openapi_resp_headers": openapi_resp_headers,
738
+ "test_type": "INVALID_QUERY_ENUM",
739
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_400_INVALID_QUERY_{target_param}"
740
+ })
741
+
742
+ # INVALID PATH ENUM VALUE
743
+ for target_param, target_schema, _ in enum_path_params:
744
+ bad_path = path
745
+
746
+ for p in all_params:
747
+ if p.get("in") == "path":
748
+ p_name = p.get("name")
749
+ if p_name == target_param:
750
+ bad_val = -999999 if target_schema.get("type") in ["integer",
751
+ "number"] else "INVALID_ENUM_OPTION_XYZ"
752
+ bad_path = bad_path.replace(f"{{{p_name}}}", str(bad_val))
753
+ else:
754
+ p_schema = p.get("schema", {"type": "string"})
755
+ valid_val = generate_mock_data_from_schema(p_schema, spec_data)
756
+ bad_path = bad_path.replace(f"{{{p_name}}}", str(valid_val))
757
+
758
+ all_test_cases.append({
759
+ "suite_name": suite_name,
760
+ "env_name": env_label,
761
+ "env_security": env_security,
762
+ "url": f"{base_url}{bad_path}",
763
+ "method": method_upper,
764
+ "content_type": default_ct,
765
+ "query_params": query_params,
766
+ "request_schema": request_schema,
767
+ "expected_status": 400,
768
+ "requires_auth": has_security,
769
+ "payload": default_payload,
770
+ "response_content_type": err_400_ct,
771
+ "response_schema": err_400_schema,
772
+ "err_500_ct": err_500_ct,
773
+ "err_500_schema": err_500_schema,
774
+ "expected_response": seed_expected_response,
775
+ "max_response_time_ms": endpoint_max_ms,
776
+ "expected_headers": seed_expected_headers,
777
+ "openapi_resp_headers": openapi_resp_headers,
778
+ "test_type": "INVALID_PATH_ENUM",
779
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_400_INVALID_PATH_{target_param}"
780
+ })
781
+
782
+ # MISSING REQUIRED QUERY PARAMETERS
783
+ for req_param in required_query_params:
784
+ incomplete_query_params = query_params.copy()
785
+ incomplete_query_params.pop(req_param, None)
786
+
787
+ all_test_cases.append({
788
+ "suite_name": suite_name,
789
+ "env_name": env_label,
790
+ "env_security": env_security,
791
+ "url": f"{base_url}{resolved_path}",
792
+ "method": method_upper,
793
+ "content_type": default_ct,
794
+ "query_params": incomplete_query_params,
795
+ "request_schema": request_schema,
796
+ "expected_status": 400,
797
+ "requires_auth": has_security,
798
+ "payload": default_payload,
799
+ "response_content_type": err_400_ct,
800
+ "response_schema": err_400_schema,
801
+ "err_500_ct": err_500_ct,
802
+ "err_500_schema": err_500_schema,
803
+ "expected_response": seed_expected_response,
804
+ "max_response_time_ms": endpoint_max_ms,
805
+ "expected_headers": seed_expected_headers,
806
+ "openapi_resp_headers": openapi_resp_headers,
807
+ "test_type": "MISSING_REQUIRED_QUERY",
808
+ "id": f"[{suite_name}]-[{env_label}]_{method_upper}_{clean_path_id}_400_MISSING_QUERY_{req_param}"
809
+ })
810
+
811
+ return all_test_cases
812
+
813
+ def pytest_addoption(parser):
814
+ parser.addoption(
815
+ "--suite",
816
+ action="store",
817
+ default="all",
818
+ help="Name of the spec folder in specs/ to run (e.g., 'petstore_service'), or 'all'"
819
+ )
820
+ parser.addoption(
821
+ "--env",
822
+ action="store",
823
+ default="all",
824
+ help="Target environment name matching 'name' in spec_url, servers, and security (e.g., 'sandbox', 'local'), or 'all'"
825
+ )
826
+ parser.addoption(
827
+ "--unmask",
828
+ action="store_true",
829
+ default=False,
830
+ help="Disable masking of sensitive headers, URLs, and payloads in cURL logs for debugging"
831
+ )
832
+ parser.addoption(
833
+ "--update-spec",
834
+ action="store_true",
835
+ default=False,
836
+ help="Overwrite the local baseline openapi.json if discrepancies are detected with the live spec"
837
+ )
838
+
839
+ def pytest_configure(config):
840
+ """Syncs CLI flags like --unmask with helper modules at test session startup."""
841
+ helpers.UNMASK_SENSITIVE_DATA = config.getoption("--unmask", default=False)
842
+
843
+ # Do not collect the API runner if the user is strictly running unit tests
844
+ markexpr = config.getoption("-m", default="")
845
+ if markexpr == "unit":
846
+ return
847
+
848
+ # Automatically include the packaged runner module if specs/ exists in the project
849
+ specs_dir = os.path.join(os.getcwd(), "specs")
850
+ runner_path = os.path.join(os.path.dirname(__file__), "runner.py")
851
+ if os.path.isdir(specs_dir) and runner_path not in config.args:
852
+ # Only auto-inject if the user didn't explicitly target a specific file like test_framework_unit.py
853
+ if not any(arg.endswith(".py") for arg in config.args):
854
+ config.args.append(runner_path)
855
+
856
+ def pytest_ignore_collect(collection_path, config):
857
+ """Prevents unit test files from being collected (and listed as deselected) during -m api runs."""
858
+ markexpr = config.getoption("-m", default="")
859
+ if markexpr == "api" and collection_path.name == "test_framework_unit.py":
860
+ return True
861
+ return False
862
+
863
+ def pytest_collection_modifyitems(session, config, items):
864
+ """
865
+ Reorders collected test cases:
866
+ 1. By HTTP method: GET -> POST -> PUT -> PATCH -> DELETE
867
+ 2. Within DELETE: Negative cases run first so the Happy Path does not
868
+ delete seeded resources before negative checks complete.
869
+ """
870
+ method_priority = {
871
+ "GET": 1,
872
+ "POST": 2,
873
+ "PUT": 3,
874
+ "PATCH": 4,
875
+ "DELETE": 5
876
+ }
877
+
878
+ def get_test_priority(item):
879
+ callspec = getattr(item, "callspec", None)
880
+ if callspec and "api_endpoint_meta" in callspec.params:
881
+ meta = callspec.params["api_endpoint_meta"]
882
+
883
+ # Guard against non-dict values (e.g. empty parametrization during -m unit)
884
+ if not isinstance(meta, dict):
885
+ return (99, 99)
886
+
887
+ method = meta.get("method", "GET").upper()
888
+ test_type = meta.get("test_type", "HAPPY_PATH")
889
+
890
+ m_rank = method_priority.get(method, 99)
891
+
892
+ # For DELETE requests, run negative tests (0) before HAPPY_PATH (1)
893
+ if method == "DELETE":
894
+ c_rank = 1 if test_type == "HAPPY_PATH" else 0
895
+ else:
896
+ c_rank = 0 if test_type == "HAPPY_PATH" else 1
897
+
898
+ return (m_rank, c_rank)
899
+
900
+ return (99, 99)
901
+
902
+ items.sort(key=get_test_priority)
903
+
904
+ @pytest.hookimpl(hookwrapper=True)
905
+ def pytest_runtest_makereport(item, call):
906
+ """
907
+ Attaches masked cURL commands and live server responses into expandable
908
+ HTML blocks inside pytest-html reports.
909
+ """
910
+ outcome = yield
911
+ report = outcome.get_result()
912
+ extras = getattr(report, "extras", [])
913
+
914
+ if report.when == "call":
915
+ curl_text = getattr(item, "api_curl", None)
916
+ resp_text = getattr(item, "api_response_info", None)
917
+
918
+ if curl_text or resp_text:
919
+ pytest_html = item.config.pluginmanager.getplugin("html")
920
+ if pytest_html is not None:
921
+ safe_curl = html.escape(curl_text or "")
922
+ safe_resp = html.escape(resp_text or "")
923
+
924
+ is_unmasked = getattr(helpers, "UNMASK_SENSITIVE_DATA", False)
925
+ curl_label = "UNMASKED cURL Command (Debug Mode)" if is_unmasked else "Masked cURL Command"
926
+ curl_color = "#cf222e" if is_unmasked else "#0969da"
927
+
928
+ html_block = f"""
929
+ <div style="margin-top: 8px; font-family: monospace; font-size: 12px;">
930
+ <details open style="margin-bottom: 6px; border: 1px solid #d0d7de; border-radius: 4px; padding: 6px; background: #f6f8fa;">
931
+ <summary style="cursor: pointer; font-weight: bold; color: {curl_color};">{curl_label}</summary>
932
+ <pre style="white-space: pre-wrap; word-break: break-all; margin: 6px 0 0 0;">{safe_curl}</pre>
933
+ </details>
934
+ <details style="border: 1px solid #d0d7de; border-radius: 4px; padding: 6px; background: #f6f8fa;">
935
+ <summary style="cursor: pointer; font-weight: bold; color: #1a7f37;">Server Response</summary>
936
+ <pre style="white-space: pre-wrap; word-break: break-all; margin: 6px 0 0 0;">{safe_resp}</pre>
937
+ </details>
938
+ </div>
939
+ """
940
+ extras.append(pytest_html.extras.html(html_block))
941
+
942
+ report.extras = extras
943
+
944
+ @pytest.hookimpl(optionalhook=True)
945
+ def pytest_html_results_summary(prefix, summary, postfix):
946
+ """
947
+ Injects a high-visibility security warning banner at the top of reports/report.html
948
+ whenever the --unmask debugging flag is enabled.
949
+ """
950
+ if getattr(helpers, "UNMASK_SENSITIVE_DATA", False):
951
+ warning_banner = """
952
+ <div style="
953
+ background-color: #ffebe9;
954
+ border: 2px solid #cf222e;
955
+ border-radius: 6px;
956
+ color: #82071e;
957
+ padding: 12px 16px;
958
+ margin: 12px 0;
959
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
960
+ font-size: 14px;
961
+ ">
962
+ <strong>SECURITY WARNING (--unmask ACTIVE):</strong>
963
+ Sensitive headers, tokens, query parameters, and payloads are visible in plain text inside this report.
964
+ <strong>Do not commit or share this file publicly.</strong>
965
+ </div>
966
+ """
967
+ prefix.append(warning_banner)
968
+
969
+ def pytest_generate_tests(metafunc):
970
+ if "api_endpoint_meta" in metafunc.fixturenames:
971
+ markexpr = metafunc.config.getoption("-m", default="")
972
+ if markexpr == "unit":
973
+ metafunc.parametrize("api_endpoint_meta", [])
974
+ return
975
+
976
+ target_suite = metafunc.config.getoption("--suite")
977
+ target_env = metafunc.config.getoption("--env")
978
+ update_spec = metafunc.config.getoption("--update-spec", default=False)
979
+
980
+ test_cases = load_openapi_specs(
981
+ target_suite=target_suite,
982
+ target_env=target_env,
983
+ update_spec=update_spec
984
+ )
985
+ metafunc.parametrize("api_endpoint_meta", test_cases, ids=[tc["id"] for tc in test_cases])