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,875 @@
1
+ import logging
2
+ import csv
3
+ import io
4
+ import re
5
+ import json
6
+ import xml.etree.ElementTree as ET
7
+ from urllib.parse import urlparse, parse_qsl, urlencode, urlunparse
8
+
9
+ SENSITIVE_KEYS = {
10
+ "authorization",
11
+ "x-api-key",
12
+ "api_key",
13
+ "apikey",
14
+ "x-auth-token",
15
+ "token",
16
+ "access_token",
17
+ "refresh_token",
18
+ "secret",
19
+ "client_secret",
20
+ "password",
21
+ "passwd",
22
+ "cookie",
23
+ "set-cookie"
24
+ }
25
+
26
+ UNMASK_SENSITIVE_DATA = False
27
+
28
+ def generate_mock_data_from_schema(schema, full_spec):
29
+ if not schema:
30
+ return None
31
+
32
+ if "$ref" in schema:
33
+ ref_path = schema["$ref"].split("/")
34
+ schema_name = ref_path[-1]
35
+ referenced_schema = full_spec.get("components", {}).get("schemas", {}).get(schema_name, {})
36
+ return generate_mock_data_from_schema(referenced_schema, full_spec)
37
+
38
+ if "default" in schema and schema["default"] is not None:
39
+ return schema["default"]
40
+
41
+ if "example" in schema and schema["example"] is not None:
42
+ return schema["example"]
43
+
44
+ if "examples" in schema and isinstance(schema["examples"], list) and len(schema["examples"]) > 0:
45
+ return schema["examples"][0]
46
+
47
+ schema_type = schema.get("type")
48
+
49
+ if schema_type == "object":
50
+ payload = {}
51
+ properties = schema.get("properties", {})
52
+ for prop_name, prop_schema in properties.items():
53
+ payload[prop_name] = generate_mock_data_from_schema(prop_schema, full_spec)
54
+ return payload
55
+
56
+ elif schema_type == "array":
57
+ items_schema = schema.get("items", {})
58
+ return [generate_mock_data_from_schema(items_schema, full_spec)]
59
+
60
+ elif schema_type == "string":
61
+ if "enum" in schema:
62
+ return schema["enum"][0] if isinstance(schema["enum"], list) and len(schema["enum"]) > 0 else schema["enum"]
63
+ if "default" in schema:
64
+ return schema["default"]
65
+
66
+ string_format = schema.get("format")
67
+ if string_format == "uuid":
68
+ return "123e4567-e89b-12d3-a456-426614174000"
69
+ elif string_format == "email":
70
+ return "test.user@example.com"
71
+ elif string_format == "date":
72
+ return "2026-11-13"
73
+ elif string_format == "date-time":
74
+ return "2026-11-13T06:00:00Z"
75
+ elif string_format == "uri" or string_format == "url":
76
+ return "https://example.com"
77
+ return "mock_string_value"
78
+
79
+ elif schema_type == "integer":
80
+ if "enum" in schema:
81
+ return schema["enum"][0] if isinstance(schema["enum"], list) and len(schema["enum"]) > 0 else schema["enum"]
82
+ if "default" in schema:
83
+ return schema["default"]
84
+ return 123
85
+
86
+ elif schema_type == "number":
87
+ if "enum" in schema:
88
+ return schema["enum"][0] if isinstance(schema["enum"], list) and len(schema["enum"]) > 0 else schema["enum"]
89
+ if "default" in schema:
90
+ return schema["default"]
91
+ return 12.34
92
+
93
+ elif schema_type == "boolean":
94
+ if "enum" in schema:
95
+ return schema["enum"][0] if isinstance(schema["enum"], list) and len(schema["enum"]) > 0 else schema["enum"]
96
+ if "default" in schema:
97
+ return schema["default"]
98
+ return True
99
+
100
+ return None
101
+
102
+ def dict_to_xml_string(data, root_tag="root", schema=None, full_spec=None):
103
+ """
104
+ Converts a Python dictionary or list into an XML string, respecting OpenAPI
105
+ 'xml' metadata (custom tag names and wrapped arrays) when available.
106
+ """
107
+ if schema and "$ref" in schema and full_spec:
108
+ schema_name = schema["$ref"].split("/")[-1]
109
+ schema = full_spec.get("components", {}).get("schemas", {}).get(schema_name, {})
110
+ if root_tag == "root":
111
+ root_tag = schema.get("xml", {}).get("name") or schema_name
112
+
113
+ if schema and isinstance(schema, dict):
114
+ xml_meta = schema.get("xml", {})
115
+ if xml_meta.get("name"):
116
+ root_tag = xml_meta["name"]
117
+
118
+ root_elem = ET.Element(root_tag)
119
+ _build_xml_children(root_elem, data, schema, full_spec)
120
+ return ET.tostring(root_elem, encoding="unicode")
121
+
122
+ def _build_xml_children(parent_elem, data, schema=None, full_spec=None):
123
+ if schema and "$ref" in schema and full_spec:
124
+ schema_name = schema["$ref"].split("/")[-1]
125
+ schema = full_spec.get("components", {}).get("schemas", {}).get(schema_name, {})
126
+
127
+ properties = schema.get("properties", {}) if isinstance(schema, dict) else {}
128
+
129
+ if isinstance(data, dict):
130
+ for key, val in data.items():
131
+ prop_schema = properties.get(key, {})
132
+ if "$ref" in prop_schema and full_spec:
133
+ ref_name = prop_schema["$ref"].split("/")[-1]
134
+ prop_schema = full_spec.get("components", {}).get("schemas", {}).get(ref_name, {})
135
+
136
+ xml_meta = prop_schema.get("xml", {}) if isinstance(prop_schema, dict) else {}
137
+ tag_name = xml_meta.get("name") or key
138
+
139
+ if isinstance(val, list):
140
+ items_schema = prop_schema.get("items", {}) if isinstance(prop_schema, dict) else {}
141
+ item_xml_name = (
142
+ items_schema.get("xml", {}).get("name")
143
+ if isinstance(items_schema, dict) else None
144
+ ) or key.rstrip("s") or "item"
145
+
146
+ if xml_meta.get("wrapped", False):
147
+ wrapper_elem = ET.SubElement(parent_elem, tag_name)
148
+ for item in val:
149
+ item_elem = ET.SubElement(wrapper_elem, item_xml_name)
150
+ _build_xml_children(item_elem, item, items_schema, full_spec)
151
+ else:
152
+ for item in val:
153
+ item_elem = ET.SubElement(parent_elem, tag_name)
154
+ _build_xml_children(item_elem, item, items_schema, full_spec)
155
+
156
+ elif isinstance(val, dict):
157
+ child_elem = ET.SubElement(parent_elem, tag_name)
158
+ _build_xml_children(child_elem, val, prop_schema, full_spec)
159
+
160
+ elif val is not None:
161
+ child_elem = ET.SubElement(parent_elem, tag_name)
162
+ child_elem.text = str(val).lower() if isinstance(val, bool) else str(val)
163
+
164
+ elif isinstance(data, list):
165
+ items_schema = schema.get("items", {}) if isinstance(schema, dict) else {}
166
+ item_tag = items_schema.get("xml", {}).get("name") or "item"
167
+ for item in data:
168
+ item_elem = ET.SubElement(parent_elem, item_tag)
169
+ _build_xml_children(item_elem, item, items_schema, full_spec)
170
+
171
+ elif data is not None:
172
+ parent_elem.text = str(data).lower() if isinstance(data, bool) else str(data)
173
+
174
+ def inject_dynamic_variables(target, dynamic_vars):
175
+ """
176
+ Recursively replaces {{key}} placeholders in strings, dicts, and lists
177
+ with live values from the dynamic_vars dictionary.
178
+ """
179
+ if not dynamic_vars or target is None:
180
+ return target
181
+
182
+ if isinstance(target, str):
183
+ for key, val in dynamic_vars.items():
184
+ placeholder = f"{{{{{key}}}}}"
185
+ if placeholder in target:
186
+ # Preserve original type if the entire string is just the placeholder
187
+ if target == placeholder:
188
+ return val
189
+ target = target.replace(placeholder, str(val))
190
+ return target
191
+
192
+ elif isinstance(target, dict):
193
+ return {k: inject_dynamic_variables(v, dynamic_vars) for k, v in target.items()}
194
+
195
+ elif isinstance(target, list):
196
+ return [inject_dynamic_variables(item, dynamic_vars) for item in target]
197
+
198
+ return target
199
+
200
+ def generate_invalid_enum_payload(schema, full_spec, valid_payload):
201
+ if not schema or not isinstance(valid_payload, dict):
202
+ return None
203
+
204
+ if "$ref" in schema:
205
+ ref_path = schema["$ref"].split("/")
206
+ schema_name = ref_path[-1]
207
+ schema = full_spec.get("components", {}).get("schemas", {}).get(schema_name, {})
208
+
209
+ properties = schema.get("properties", {})
210
+ for prop_name, prop_schema in properties.items():
211
+ if "$ref" in prop_schema:
212
+ ref_path = prop_schema["$ref"].split("/")
213
+ prop_schema = full_spec.get("components", {}).get("schemas", {}).get(ref_path[-1], {})
214
+
215
+ if "enum" in prop_schema:
216
+ corrupted_payload = valid_payload.copy()
217
+ if prop_schema.get("type") in ["integer", "number"]:
218
+ corrupted_payload[prop_name] = -999999
219
+ else:
220
+ corrupted_payload[prop_name] = "INVALID_ENUM_OPTION_XYZ"
221
+ return corrupted_payload
222
+
223
+ return None
224
+
225
+ def validate_response_by_content_type(response, response_content_type, response_schema, full_spec):
226
+ if not response_schema:
227
+ return
228
+
229
+ actual_ct = (response.headers.get("Content-Type") or response_content_type or "").lower()
230
+
231
+ # 1. JSON (application/json, application/vnd.api+json, etc.)
232
+ if "json" in actual_ct:
233
+ try:
234
+ response_json = response.json()
235
+ except Exception as e:
236
+ raise ValueError(f"Expected valid JSON, but failed to parse response: {e}")
237
+ validate_json_response_schema(response_json, response_schema, full_spec)
238
+
239
+ # 2. XML (application/xml, text/xml)
240
+ elif "xml" in actual_ct:
241
+ validate_xml_response_schema(response.text, response_schema, full_spec)
242
+
243
+ # 3. CSV (text/csv)
244
+ elif "csv" in actual_ct:
245
+ if not response.text.strip():
246
+ raise ValueError("Expected non-empty CSV response, got empty body.")
247
+ try:
248
+ reader = list(csv.reader(io.StringIO(response.text)))
249
+ if len(reader) < 1:
250
+ raise ValueError("CSV response contains no rows.")
251
+ except csv.Error as e:
252
+ raise ValueError(f"Malformed CSV returned by server: {e}")
253
+
254
+ # 4. HTML (text/html)
255
+ elif "html" in actual_ct:
256
+ if "<html" not in response.text.lower() and "<!doctype html" not in response.text.lower():
257
+ raise ValueError("Expected HTML document, but missing <html> or <!DOCTYPE html> tags.")
258
+
259
+ # 5. Plain Text (text/plain)
260
+ elif "text/plain" in actual_ct or actual_ct.startswith("text/"):
261
+ if response_schema.get("minLength"):
262
+ min_len = response_schema["minLength"]
263
+ if len(response.text) < min_len:
264
+ raise ValueError(f"Plain text response shorter than minLength ({len(response.text)} < {min_len}).")
265
+ validate_text_response_schema(response.text, response_schema)
266
+
267
+ # 6. Binary / File Downloads (application/pdf, image/*, application/octet-stream, application/zip)
268
+ elif any(bin_type in actual_ct for bin_type in ["octet-stream", "pdf", "image/", "audio/", "video/", "zip"]):
269
+ if not response.content or len(response.content) == 0:
270
+ raise ValueError(f"Expected binary file content for '{actual_ct}', but received 0 bytes.")
271
+
272
+ def validate_text_response_schema(text_data, schema):
273
+ """
274
+ Validates a plain-text (text/plain) response against an OpenAPI primitive schema
275
+ (type, enum, pattern, minLength, maxLength).
276
+ """
277
+ if not schema:
278
+ return
279
+
280
+ schema_type = schema.get("type", "string")
281
+
282
+ if schema_type == "integer":
283
+ try:
284
+ int(text_data.strip())
285
+ except ValueError:
286
+ raise ValueError(f"Expected integer in text/plain response, got '{text_data}'")
287
+
288
+ elif schema_type == "number":
289
+ try:
290
+ float(text_data.strip())
291
+ except ValueError:
292
+ raise ValueError(f"Expected number in text/plain response, got '{text_data}'")
293
+
294
+ elif schema_type == "boolean":
295
+ if text_data.strip().lower() not in {"true", "false", "1", "0"}:
296
+ raise ValueError(f"Expected boolean in text/plain response, got '{text_data}'")
297
+
298
+ if "enum" in schema:
299
+ allowed_str = [str(v) for v in schema["enum"]]
300
+ if text_data.strip() not in allowed_str:
301
+ raise ValueError(f"text/plain enum mismatch. Received '{text_data}', expected one of {schema['enum']}")
302
+
303
+ if "pattern" in schema:
304
+ if not re.search(schema["pattern"], text_data):
305
+ raise ValueError(f"text/plain value '{text_data}' did not match pattern '{schema['pattern']}'")
306
+
307
+ if "minLength" in schema and len(text_data) < schema["minLength"]:
308
+ raise ValueError(f"text/plain length {len(text_data)} is less than minLength {schema['minLength']}")
309
+
310
+ if "maxLength" in schema and len(text_data) > schema["maxLength"]:
311
+ raise ValueError(f"text/plain length {len(text_data)} exceeds maxLength {schema['maxLength']}")
312
+
313
+ def validate_json_response_schema(data, schema, full_spec, path="root"):
314
+ """
315
+ Recursively validates that every field in the live JSON response strictly
316
+ matches its OpenAPI data type, required rules, enums, nullability, and
317
+ composition schemas (allOf, oneOf, anyOf).
318
+ """
319
+ if not schema:
320
+ return
321
+
322
+ # 1. Resolve $ref pointers
323
+ if "$ref" in schema:
324
+ ref_path = schema["$ref"].split("/")
325
+ schema_name = ref_path[-1]
326
+ referenced_schema = full_spec.get("components", {}).get("schemas", {}).get(schema_name, {})
327
+ validate_json_response_schema(data, referenced_schema, full_spec, path)
328
+ return
329
+
330
+ # 2. Handle Composition Schemas (allOf, oneOf, anyOf)
331
+ if "allOf" in schema:
332
+ for sub_schema in schema["allOf"]:
333
+ validate_json_response_schema(data, sub_schema, full_spec, path)
334
+ return
335
+
336
+ if "oneOf" in schema or "anyOf" in schema:
337
+ sub_schemas = schema.get("oneOf") or schema.get("anyOf")
338
+ errors = []
339
+ for sub_schema in sub_schemas:
340
+ try:
341
+ validate_json_response_schema(data, sub_schema, full_spec, path)
342
+ return # Passed at least one valid schema branch
343
+ except ValueError as e:
344
+ errors.append(str(e))
345
+ raise ValueError(f"At '{path}': Data did not match any allowed schema variant. Details: {errors}")
346
+
347
+ # 3. Handle Nullability (OpenAPI 3.0 'nullable: true' & OpenAPI 3.1 type arrays)
348
+ schema_type = schema.get("type")
349
+ is_nullable = schema.get("nullable", False)
350
+ if isinstance(schema_type, list) and "null" in schema_type:
351
+ is_nullable = True
352
+ non_null_types = [t for t in schema_type if t != "null"]
353
+ schema_type = non_null_types[0] if non_null_types else None
354
+
355
+ if data is None:
356
+ if is_nullable:
357
+ return
358
+ raise ValueError(f"At '{path}': Received null, but field is not nullable.")
359
+
360
+ # 4. Strict Enum Value Validation
361
+ if "enum" in schema:
362
+ allowed_values = schema["enum"]
363
+ if data not in allowed_values:
364
+ raise ValueError(f"At '{path}': Enum mismatch. Received '{data}', expected one of {allowed_values}")
365
+
366
+ # 5. Object Validation (Handles both explicit "type: object" and implicit "properties")
367
+ if schema_type == "object" or "properties" in schema:
368
+ if not isinstance(data, dict):
369
+ raise ValueError(f"At '{path}': Expected object/dict, got {type(data).__name__}")
370
+
371
+ required_fields = schema.get("required", [])
372
+ for field in required_fields:
373
+ if field not in data:
374
+ raise ValueError(f"At '{path}': Missing required field '{field}'")
375
+
376
+ properties = schema.get("properties", {})
377
+ for key, value in data.items():
378
+ if key in properties:
379
+ validate_json_response_schema(value, properties[key], full_spec, f"{path}.{key}")
380
+
381
+ # 6. Array Validation
382
+ elif schema_type == "array":
383
+ if not isinstance(data, list):
384
+ raise ValueError(f"At '{path}': Expected array/list, got {type(data).__name__}")
385
+ items_schema = schema.get("items", {})
386
+ for idx, item in enumerate(data):
387
+ validate_json_response_schema(item, items_schema, full_spec, f"{path}[{idx}]")
388
+
389
+ # 7. Primitive Type Validation
390
+ elif schema_type == "string" and not isinstance(data, str):
391
+ raise ValueError(f"At '{path}': Expected string, got '{data}' ({type(data).__name__})")
392
+ elif schema_type == "integer" and (not isinstance(data, int) or isinstance(data, bool)):
393
+ raise ValueError(f"At '{path}': Expected integer, got '{data}' ({type(data).__name__})")
394
+ elif schema_type == "number" and (not isinstance(data, (int, float)) or isinstance(data, bool)):
395
+ raise ValueError(f"At '{path}': Expected number, got '{data}' ({type(data).__name__})")
396
+ elif schema_type == "boolean" and not isinstance(data, bool):
397
+ raise ValueError(f"At '{path}': Expected boolean, got '{data}' ({type(data).__name__})")
398
+
399
+ def validate_xml_response_schema(xml_text, schema, full_spec):
400
+ """
401
+ Entry point: parses raw XML text and validates all elements, nested objects,
402
+ arrays, required fields, enums, and primitive types against the OpenAPI schema.
403
+ """
404
+ if not schema:
405
+ return
406
+
407
+ try:
408
+ root = ET.fromstring(xml_text)
409
+ except ET.ParseError as e:
410
+ raise ValueError(f"Invalid XML returned by server: {e}")
411
+
412
+ _validate_xml_element(root, schema, full_spec, path=root.tag)
413
+
414
+ def _validate_xml_element(element, schema, full_spec, path="root"):
415
+ if not schema:
416
+ return
417
+
418
+ # 1. Resolve $ref pointers
419
+ if "$ref" in schema:
420
+ ref_path = schema["$ref"].split("/")
421
+ schema_name = ref_path[-1]
422
+ referenced_schema = full_spec.get("components", {}).get("schemas", {}).get(schema_name, {})
423
+ _validate_xml_element(element, referenced_schema, full_spec, path)
424
+ return
425
+
426
+ # 2. Check expected root/element tag name if specified in OpenAPI 'xml' metadata
427
+ xml_meta = schema.get("xml", {})
428
+ expected_tag = xml_meta.get("name")
429
+ if expected_tag and element.tag != expected_tag:
430
+ raise ValueError(f"At '{path}': XML tag mismatch. Expected <{expected_tag}>, got <{element.tag}>")
431
+
432
+ schema_type = schema.get("type")
433
+ text_val = element.text.strip() if element.text else ""
434
+
435
+ # 3. Object Validation (Traverses child XML tags recursively)
436
+ if schema_type == "object" or "properties" in schema:
437
+ child_elements = list(element)
438
+ child_tags = {child.tag for child in child_elements}
439
+
440
+ required_fields = schema.get("required", [])
441
+ for field in required_fields:
442
+ if field not in child_tags:
443
+ raise ValueError(f"At '{path}': Missing required XML element <{field}>")
444
+
445
+ properties = schema.get("properties", {})
446
+ for child in child_elements:
447
+ if child.tag in properties:
448
+ _validate_xml_element(child, properties[child.tag], full_spec, f"{path}.{child.tag}")
449
+ return
450
+
451
+ # 4. Array Validation (Handles wrapped <items><item>...</item></items> or repeated tags)
452
+ if schema_type == "array":
453
+ items_schema = schema.get("items", {})
454
+ for idx, child in enumerate(list(element)):
455
+ _validate_xml_element(child, items_schema, full_spec, f"{path}[{idx}]")
456
+ return
457
+
458
+ # 5. Nullability Check (Empty tag like <age /> or <age></age>)
459
+ if text_val == "":
460
+ if schema.get("nullable", False):
461
+ return
462
+ if schema_type in ["integer", "number", "boolean"]:
463
+ raise ValueError(f"At '{path}': Expected {schema_type}, got empty XML tag")
464
+
465
+ # 6. Enum Validation
466
+ if "enum" in schema:
467
+ allowed_str_values = [str(v) for v in schema["enum"]]
468
+ if text_val not in allowed_str_values:
469
+ raise ValueError(f"At '{path}': XML enum mismatch. Received '{text_val}', expected one of {schema['enum']}")
470
+
471
+ # 7. Primitive Type Validation (Parses XML strings into target types)
472
+ if schema_type == "integer":
473
+ try:
474
+ int(text_val)
475
+ except ValueError:
476
+ raise ValueError(f"At '{path}': Expected integer in XML, got '{text_val}'")
477
+
478
+ elif schema_type == "number":
479
+ try:
480
+ float(text_val)
481
+ except ValueError:
482
+ raise ValueError(f"At '{path}': Expected number in XML, got '{text_val}'")
483
+
484
+ elif schema_type == "boolean":
485
+ if text_val.lower() not in ["true", "false", "1", "0"]:
486
+ raise ValueError(f"At '{path}': Expected boolean in XML, got '{text_val}'")
487
+
488
+ def _get_xml_value_by_path(xml_root, json_path):
489
+ """
490
+ Traverses an ElementTree using dot notation (e.g., 'Pet.category.name' or 'category.name').
491
+ Automatically skips the root tag name if the path starts with it.
492
+ """
493
+ parts = json_path.split(".")
494
+ if parts and parts[0] == xml_root.tag:
495
+ parts = parts[1:]
496
+
497
+ current = xml_root
498
+ for part in parts:
499
+ if part.isdigit():
500
+ children = list(current)
501
+ idx = int(part)
502
+ if idx < len(children):
503
+ current = children[idx]
504
+ else:
505
+ return None, False
506
+ else:
507
+ found = current.find(part)
508
+ if found is None:
509
+ return None, False
510
+ current = found
511
+
512
+ text_val = current.text.strip() if current.text else ""
513
+ return text_val, True
514
+
515
+ def validate_expected_response_values(response, expected_values, content_type=""):
516
+ """
517
+ Validates dot-notated fields in either a JSON or XML response against exact values
518
+ or dynamic rules ('not_empty', 'contains:', 'regex:', 'gt:', etc.).
519
+ """
520
+ if not expected_values:
521
+ return
522
+
523
+ ct_lower = content_type.lower()
524
+ if "text/plain" in ct_lower or ct_lower.startswith("text/"):
525
+ for key_path, expected_rule in expected_values.items():
526
+ rules = expected_rule if isinstance(expected_rule, list) else [expected_rule]
527
+ for single_rule in rules:
528
+ _check_single_rule(response.text, single_rule, key_path)
529
+ return
530
+
531
+ is_xml = "xml" in ct_lower or response.text.strip().startswith("<")
532
+
533
+ if is_xml:
534
+ try:
535
+ xml_root = ET.fromstring(response.text)
536
+ except ET.ParseError as e:
537
+ raise ValueError(f"Failed to parse XML response for value validation: {e}")
538
+
539
+ for xml_path, expected_rule in expected_values.items():
540
+ actual_val, found = _get_xml_value_by_path(xml_root, xml_path)
541
+ if not found:
542
+ raise ValueError(f"Expected XML tag '{xml_path}' was missing from response.")
543
+
544
+ # Convert string to float/int if numeric comparison rule is used
545
+ rules = expected_rule if isinstance(expected_rule, list) else [expected_rule]
546
+ for single_rule in rules:
547
+ eval_val = actual_val
548
+ if isinstance(single_rule, (int, float)) and not isinstance(single_rule, bool):
549
+ try:
550
+ eval_val = float(actual_val) if "." in actual_val else int(actual_val)
551
+ except ValueError:
552
+ pass
553
+ elif isinstance(single_rule, str) and single_rule.startswith(("gt:", "gte:", "lt:", "lte:")):
554
+ try:
555
+ eval_val = float(actual_val)
556
+ except ValueError:
557
+ pass
558
+
559
+ _check_single_rule(eval_val, single_rule, xml_path)
560
+ return
561
+
562
+ # Standard JSON validation
563
+ try:
564
+ response_json = response.json()
565
+ except Exception as e:
566
+ raise ValueError(f"Failed to parse JSON response for value validation: {e}")
567
+
568
+ for json_path, expected_rule in expected_values.items():
569
+ actual_val = response_json
570
+ for part in json_path.split("."):
571
+ if isinstance(actual_val, dict) and part in actual_val:
572
+ actual_val = actual_val[part]
573
+ elif isinstance(actual_val, list) and part.isdigit() and int(part) < len(actual_val):
574
+ actual_val = actual_val[int(part)]
575
+ else:
576
+ raise ValueError(f"Expected field '{json_path}' was missing from response.")
577
+
578
+ if isinstance(expected_rule, list):
579
+ for single_rule in expected_rule:
580
+ _check_single_rule(actual_val, single_rule, json_path)
581
+ else:
582
+ _check_single_rule(actual_val, expected_rule, json_path)
583
+
584
+ def validate_response_headers(response_headers, openapi_headers_spec=None, expected_headers=None, full_spec=None):
585
+ """
586
+ Validates live HTTP response headers (case-insensitively) against:
587
+ 1. OpenAPI 3.0/3.1 'responses.<status>.headers' schema & required rules
588
+ 2. Custom 'expected_headers' rules from test_data.json
589
+ """
590
+ # Normalize response header keys to lowercase for case-insensitive lookup
591
+ lower_headers = {k.lower(): v for k, v in response_headers.items()}
592
+
593
+ # 1. Validate against OpenAPI response headers specification
594
+ if isinstance(openapi_headers_spec, dict):
595
+ for header_name, header_obj in openapi_headers_spec.items():
596
+ if not isinstance(header_obj, dict):
597
+ continue
598
+
599
+ if "$ref" in header_obj and full_spec:
600
+ ref_name = header_obj["$ref"].split("/")[-1]
601
+ header_obj = full_spec.get("components", {}).get("headers", {}).get(ref_name, {})
602
+
603
+ h_lower = header_name.lower()
604
+ is_required = header_obj.get("required", False)
605
+
606
+ if is_required and h_lower not in lower_headers:
607
+ raise ValueError(f"Missing required OpenAPI response header: '{header_name}'")
608
+
609
+ if h_lower in lower_headers:
610
+ h_schema = header_obj.get("schema", {})
611
+ h_type = h_schema.get("type")
612
+ raw_val = lower_headers[h_lower]
613
+
614
+ if h_type == "integer":
615
+ try:
616
+ int(raw_val.strip())
617
+ except ValueError:
618
+ raise ValueError(f"Response header '{header_name}' expected integer, got '{raw_val}'")
619
+ elif h_type == "number":
620
+ try:
621
+ float(raw_val.strip())
622
+ except ValueError:
623
+ raise ValueError(f"Response header '{header_name}' expected number, got '{raw_val}'")
624
+ elif h_type == "boolean":
625
+ if raw_val.strip().lower() not in {"true", "false", "1", "0"}:
626
+ raise ValueError(f"Response header '{header_name}' expected boolean, got '{raw_val}'")
627
+
628
+ if "enum" in h_schema:
629
+ allowed = [str(v) for v in h_schema["enum"]]
630
+ if raw_val.strip() not in allowed:
631
+ raise ValueError(f"Response header '{header_name}' enum mismatch: '{raw_val}' not in {allowed}")
632
+
633
+ # 2. Validate against custom expected_headers rules from test_data.json
634
+ if isinstance(expected_headers, dict):
635
+ for header_name, expected_rule in expected_headers.items():
636
+ h_lower = header_name.lower()
637
+ if h_lower not in lower_headers:
638
+ raise ValueError(f"Expected response header '{header_name}' was missing.")
639
+
640
+ actual_val = lower_headers[h_lower]
641
+ rules = expected_rule if isinstance(expected_rule, list) else [expected_rule]
642
+ for single_rule in rules:
643
+ eval_val = actual_val
644
+ if isinstance(single_rule, (int, float)) and not isinstance(single_rule, bool):
645
+ try:
646
+ eval_val = float(actual_val) if "." in actual_val else int(actual_val)
647
+ except ValueError:
648
+ pass
649
+ elif isinstance(single_rule, str) and single_rule.startswith(("gt:", "gte:", "lt:", "lte:")):
650
+ try:
651
+ eval_val = float(actual_val)
652
+ except ValueError:
653
+ pass
654
+
655
+ _check_single_rule(eval_val, single_rule, f"header.{header_name}")
656
+
657
+ def validate_sla_latency(elapsed_ms, max_ms):
658
+ """
659
+ Validates that the endpoint response time (in milliseconds) does not exceed the SLA threshold.
660
+ """
661
+ if max_ms is None:
662
+ return
663
+ if elapsed_ms > float(max_ms):
664
+ raise ValueError(
665
+ f"SLA Latency Exceeded: Response took {elapsed_ms:.2f} ms, "
666
+ f"exceeding max threshold of {float(max_ms):.2f} ms."
667
+ )
668
+
669
+ def _check_single_rule(actual_val, rule, json_path):
670
+ """Evaluates a single expected rule (text, pattern, numeric, or exact) against actual_val."""
671
+ if isinstance(rule, str):
672
+ if rule == "not_empty":
673
+ if actual_val in (None, "", [], {}):
674
+ raise ValueError(f"At '{json_path}': Expected non-empty value, got '{actual_val}'.")
675
+ return
676
+
677
+ if rule.startswith("contains:"):
678
+ substring = rule.split("contains:", 1)
679
+ if substring[1] not in str(actual_val):
680
+ raise ValueError(f"At '{json_path}': Expected '{actual_val}' to contain '{substring[1]}'.")
681
+ return
682
+
683
+ if rule.startswith("not_contains:"):
684
+ substring = rule.split("not_contains:", 1)
685
+ if substring[1] in str(actual_val):
686
+ raise ValueError(f"At '{json_path}': Expected '{actual_val}' NOT to contain '{substring[1]}'.")
687
+ return
688
+
689
+ if rule.startswith("regex:"):
690
+ pattern = rule.split("regex:", 1)
691
+ if not re.search(pattern[1], str(actual_val)):
692
+ raise ValueError(f"At '{json_path}': Value '{actual_val}' did not match regex '{pattern[1]}'.")
693
+ return
694
+
695
+ if rule.startswith("exact:"):
696
+ raw_expected = json.loads(rule.split("exact:", 1)[1])
697
+ if actual_val != raw_expected:
698
+ raise ValueError(f"At '{json_path}': Expected exact value {raw_expected}, got {actual_val}.")
699
+ return
700
+
701
+ # Numeric comparison rules: gt:, gte:, lt:, lte:
702
+ for op_prefix, op_label in [("gte:", ">="), ("lte:", "<="), ("gt:", ">"), ("lt:", "<")]:
703
+ if rule.startswith(op_prefix):
704
+ threshold = float(rule.split(op_prefix, 1)[1])
705
+ if not isinstance(actual_val, (int, float)) or isinstance(actual_val, bool):
706
+ raise ValueError(
707
+ f"At '{json_path}': Expected numeric value for '{rule}', got '{actual_val}' ({type(actual_val).__name__})."
708
+ )
709
+ if op_prefix == "gt:" and not (actual_val > threshold):
710
+ raise ValueError(f"At '{json_path}': Expected {actual_val} > {threshold}.")
711
+ if op_prefix == "gte:" and not (actual_val >= threshold):
712
+ raise ValueError(f"At '{json_path}': Expected {actual_val} >= {threshold}.")
713
+ if op_prefix == "lt:" and not (actual_val < threshold):
714
+ raise ValueError(f"At '{json_path}': Expected {actual_val} < {threshold}.")
715
+ if op_prefix == "lte:" and not (actual_val <= threshold):
716
+ raise ValueError(f"At '{json_path}': Expected {actual_val} <= {threshold}.")
717
+ return
718
+
719
+ # Standard exact match check
720
+ if actual_val != rule:
721
+ raise ValueError(
722
+ f"At '{json_path}': Expected '{rule}' ({type(rule).__name__}), "
723
+ f"got '{actual_val}' ({type(actual_val).__name__})."
724
+ )
725
+
726
+ def format_as_curl(prepared_request, masked_values=None, unmask=None):
727
+ """
728
+ Formats a requests.PreparedRequest into a copy-pasteable cURL command.
729
+ Automatically checks helpers.UNMASK_SENSITIVE_DATA unless explicitly overridden.
730
+ """
731
+ should_unmask = UNMASK_SENSITIVE_DATA if unmask is None else unmask
732
+
733
+ method = prepared_request.method
734
+ safe_url = prepared_request.url if should_unmask else _mask_url(prepared_request.url, masked_values=masked_values)
735
+
736
+ headers_list = []
737
+ for k, v in prepared_request.headers.items():
738
+ display_val = v if should_unmask else _mask_secret_value(k, v)
739
+ headers_list.append(f"-H '{k}: {display_val}'")
740
+
741
+ headers_str = " \\\n ".join(headers_list)
742
+ curl_parts = [f"curl -X {method} '{safe_url}'"]
743
+
744
+ if headers_str:
745
+ curl_parts.append(f" {headers_str}")
746
+
747
+ if prepared_request.body:
748
+ content_type = prepared_request.headers.get("Content-Type", "")
749
+ if should_unmask:
750
+ if isinstance(prepared_request.body, bytes):
751
+ try:
752
+ display_body = prepared_request.body.decode("utf-8")
753
+ except UnicodeDecodeError:
754
+ display_body = "<BINARY_PAYLOAD>"
755
+ else:
756
+ display_body = str(prepared_request.body)
757
+ else:
758
+ display_body = _format_and_mask_body(prepared_request.body, content_type)
759
+
760
+ safe_body = display_body.replace("'", "'\"'\"'")
761
+ curl_parts.append(f" -d '{safe_body}'")
762
+
763
+ return " \\\n".join(curl_parts)
764
+
765
+ def _mask_secret_value(key, value):
766
+ """
767
+ Masks sensitive header or query values while keeping auth prefixes (e.g., 'Bearer') visible.
768
+ """
769
+ if key.lower() not in SENSITIVE_KEYS:
770
+ return value
771
+
772
+ val_str = str(value)
773
+ if " " in val_str:
774
+ prefix, secret = val_str.split(" ", 1)
775
+ if prefix.lower() in {"bearer", "basic", "token", "apikey"} and len(secret) > 0:
776
+ return f"{prefix} ***MASKED***"
777
+
778
+ return "***MASKED***"
779
+
780
+ def _mask_url(raw_url, masked_values=None):
781
+ """
782
+ Masks sensitive query parameter keys and replaces any explicit secret values
783
+ appearing in the URL path.
784
+ """
785
+ parsed = urlparse(raw_url)
786
+
787
+ # 1. Mask sensitive path segments matching explicit secret values
788
+ safe_path = parsed.path
789
+ if masked_values:
790
+ for secret in masked_values:
791
+ if secret and str(secret) in safe_path:
792
+ safe_path = safe_path.replace(str(secret), "***MASKED***")
793
+
794
+ # 2. Mask sensitive query parameter values by key name
795
+ if parsed.query:
796
+ query_pairs = parse_qsl(parsed.query, keep_blank_values=True)
797
+ masked_pairs = [(k, _mask_secret_value(k, v)) for k, v in query_pairs]
798
+ safe_query = urlencode(masked_pairs)
799
+ else:
800
+ safe_query = ""
801
+
802
+ return urlunparse((
803
+ parsed.scheme,
804
+ parsed.netloc,
805
+ safe_path,
806
+ parsed.params,
807
+ safe_query,
808
+ parsed.fragment
809
+ ))
810
+
811
+ def _mask_payload_data(data):
812
+ """
813
+ Recursively masks sensitive keys inside dictionaries and lists
814
+ for safe cURL logging.
815
+ """
816
+ if isinstance(data, dict):
817
+ masked_dict = {}
818
+ for k, v in data.items():
819
+ if str(k).lower() in SENSITIVE_KEYS:
820
+ masked_dict[k] = "***MASKED***"
821
+ else:
822
+ masked_dict[k] = _mask_payload_data(v)
823
+ return masked_dict
824
+
825
+ elif isinstance(data, list):
826
+ return [_mask_payload_data(item) for item in data]
827
+
828
+ return data
829
+
830
+ def _format_and_mask_body(raw_body, content_type=""):
831
+ """
832
+ Decodes the prepared request body and masks sensitive fields
833
+ in JSON or form-urlencoded payloads.
834
+ """
835
+ if isinstance(raw_body, bytes):
836
+ try:
837
+ body_str = raw_body.decode("utf-8")
838
+ except UnicodeDecodeError:
839
+ return "<BINARY_PAYLOAD>"
840
+ else:
841
+ body_str = str(raw_body)
842
+
843
+ ct_lower = content_type.lower()
844
+
845
+ # 1. JSON Payloads
846
+ if "json" in ct_lower or body_str.strip().startswith(("{", "[")):
847
+ try:
848
+ parsed_json = json.loads(body_str)
849
+ masked_json = _mask_payload_data(parsed_json)
850
+ return json.dumps(masked_json)
851
+ except Exception:
852
+ pass
853
+
854
+ # 2. Form-Urlencoded Payloads (e.g., username=user1&password=secret123)
855
+ if "x-www-form-urlencoded" in ct_lower:
856
+ try:
857
+ pairs = parse_qsl(body_str, keep_blank_values=True)
858
+ masked_pairs = [(k, _mask_secret_value(k, v)) for k, v in pairs]
859
+ return urlencode(masked_pairs)
860
+ except Exception:
861
+ pass
862
+
863
+ # 3. XML Payloads (e.g., <User><password>secret</password></User>)
864
+ if "xml" in ct_lower or body_str.strip().startswith("<"):
865
+ try:
866
+ xml_root = ET.fromstring(body_str)
867
+ for elem in xml_root.iter():
868
+ tag_clean = elem.tag.split("}")[-1].lower()
869
+ if tag_clean in SENSITIVE_KEYS and elem.text:
870
+ elem.text = "***MASKED***"
871
+ return ET.tostring(xml_root, encoding="unicode")
872
+ except Exception:
873
+ pass
874
+
875
+ return body_str