robotframework-openapitools 0.1.2__py3-none-any.whl → 0.2.0__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.
@@ -1,744 +1,764 @@
1
- """Module containing the classes to perform automatic OpenAPI contract validation."""
2
-
3
- import json as _json
4
- from enum import Enum
5
- from logging import getLogger
6
- from pathlib import Path
7
- from random import choice
8
- from typing import Any, Dict, List, Optional, Tuple, Union
9
-
10
- from openapi_core.contrib.requests import (
11
- RequestsOpenAPIRequest,
12
- RequestsOpenAPIResponse,
13
- )
14
- from openapi_core.exceptions import OpenAPIError
15
- from openapi_core.validation.exceptions import ValidationError
16
- from openapi_core.validation.response.exceptions import InvalidData
17
- from openapi_core.validation.schemas.exceptions import InvalidSchemaValue
18
- from requests import Response
19
- from requests.auth import AuthBase
20
- from requests.cookies import RequestsCookieJar as CookieJar
21
- from robot.api import Failure, SkipExecution
22
- from robot.api.deco import keyword, library
23
- from robot.libraries.BuiltIn import BuiltIn
24
-
25
- from OpenApiLibCore import OpenApiLibCore, RequestData, RequestValues, resolve_schema
26
-
27
- run_keyword = BuiltIn().run_keyword
28
-
29
-
30
- logger = getLogger(__name__)
31
-
32
-
33
- class ValidationLevel(str, Enum):
34
- """The available levels for the response_validation parameter."""
35
-
36
- DISABLED = "DISABLED"
37
- INFO = "INFO"
38
- WARN = "WARN"
39
- STRICT = "STRICT"
40
-
41
-
42
- @library(scope="TEST SUITE", doc_format="ROBOT")
43
- class OpenApiExecutors(OpenApiLibCore): # pylint: disable=too-many-instance-attributes
44
- """Main class providing the keywords and core logic to perform endpoint validations."""
45
-
46
- def __init__( # pylint: disable=too-many-arguments
47
- self,
48
- source: str,
49
- origin: str = "",
50
- base_path: str = "",
51
- response_validation: ValidationLevel = ValidationLevel.WARN,
52
- disable_server_validation: bool = True,
53
- mappings_path: Union[str, Path] = "",
54
- invalid_property_default_response: int = 422,
55
- default_id_property_name: str = "id",
56
- faker_locale: Optional[Union[str, List[str]]] = None,
57
- require_body_for_invalid_url: bool = False,
58
- recursion_limit: int = 1,
59
- recursion_default: Any = {},
60
- username: str = "",
61
- password: str = "",
62
- security_token: str = "",
63
- auth: Optional[AuthBase] = None,
64
- cert: Optional[Union[str, Tuple[str, str]]] = None,
65
- verify_tls: Optional[Union[bool, str]] = True,
66
- extra_headers: Optional[Dict[str, str]] = None,
67
- cookies: Optional[Union[Dict[str, str], CookieJar]] = None,
68
- proxies: Optional[Dict[str, str]] = None,
69
- ) -> None:
70
- super().__init__(
71
- source=source,
72
- origin=origin,
73
- base_path=base_path,
74
- mappings_path=mappings_path,
75
- default_id_property_name=default_id_property_name,
76
- faker_locale=faker_locale,
77
- recursion_limit=recursion_limit,
78
- recursion_default=recursion_default,
79
- username=username,
80
- password=password,
81
- security_token=security_token,
82
- auth=auth,
83
- cert=cert,
84
- verify_tls=verify_tls,
85
- extra_headers=extra_headers,
86
- cookies=cookies,
87
- proxies=proxies,
88
- )
89
- self.response_validation = response_validation
90
- self.disable_server_validation = disable_server_validation
91
- self.require_body_for_invalid_url = require_body_for_invalid_url
92
- self.invalid_property_default_response = invalid_property_default_response
93
-
94
- @keyword
95
- def test_unauthorized(self, path: str, method: str) -> None:
96
- """
97
- Perform a request for `method` on the `path`, with no authorization.
98
-
99
- This keyword only passes if the response code is 401: Unauthorized.
100
-
101
- Any authorization parameters used to initialize the library are
102
- ignored for this request.
103
- > Note: No headers or (json) body are send with the request. For security
104
- reasons, the authorization validation should be checked first.
105
- """
106
- url: str = run_keyword("get_valid_url", path, method)
107
- response = self.session.request(
108
- method=method,
109
- url=url,
110
- verify=False,
111
- )
112
- assert response.status_code == 401
113
-
114
- @keyword
115
- def test_invalid_url(
116
- self, path: str, method: str, expected_status_code: int = 404
117
- ) -> None:
118
- """
119
- Perform a request for the provided 'path' and 'method' where the url for
120
- the `path` is invalidated.
121
-
122
- This keyword will be `SKIPPED` if the path contains no parts that
123
- can be invalidated.
124
-
125
- The optional `expected_status_code` parameter (default: 404) can be set to the
126
- expected status code for APIs that do not return a 404 on invalid urls.
127
-
128
- > Note: Depending on API design, the url may be validated before or after
129
- validation of headers, query parameters and / or (json) body. By default, no
130
- parameters are send with the request. The `require_body_for_invalid_url`
131
- parameter can be set to `True` if needed.
132
- """
133
- valid_url: str = run_keyword("get_valid_url", path, method)
134
-
135
- if not (url := run_keyword("get_invalidated_url", valid_url)):
136
- raise SkipExecution(
137
- f"Path {path} does not contain resource references that "
138
- f"can be invalidated."
139
- )
140
-
141
- params, headers, json_data = None, None, None
142
- if self.require_body_for_invalid_url:
143
- request_data = self.get_request_data(method=method, endpoint=path)
144
- params = request_data.params
145
- headers = request_data.headers
146
- dto = request_data.dto
147
- json_data = dto.as_dict()
148
- response: Response = run_keyword(
149
- "authorized_request", url, method, params, headers, json_data
150
- )
151
- if response.status_code != expected_status_code:
152
- raise AssertionError(
153
- f"Response {response.status_code} was not {expected_status_code}"
154
- )
155
-
156
- @keyword
157
- def test_endpoint(self, path: str, method: str, status_code: int) -> None:
158
- """
159
- Validate that performing the `method` operation on `path` results in a
160
- `status_code` response.
161
-
162
- This is the main keyword to be used in the `Test Template` keyword when using
163
- the OpenApiDriver.
164
-
165
- The keyword calls other keywords to generate the neccesary data to perform
166
- the desired operation and validate the response against the openapi document.
167
- """
168
- json_data: Optional[Dict[str, Any]] = None
169
- original_data = None
170
-
171
- url: str = run_keyword("get_valid_url", path, method)
172
- request_data: RequestData = self.get_request_data(method=method, endpoint=path)
173
- params = request_data.params
174
- headers = request_data.headers
175
- if request_data.has_body:
176
- json_data = request_data.dto.as_dict()
177
- # when patching, get the original data to check only patched data has changed
178
- if method == "PATCH":
179
- original_data = self.get_original_data(url=url)
180
- # in case of a status code indicating an error, ensure the error occurs
181
- if status_code >= 400:
182
- invalidation_keyword_data = {
183
- "get_invalid_json_data": [
184
- "get_invalid_json_data",
185
- url,
186
- method,
187
- status_code,
188
- request_data,
189
- ],
190
- "get_invalidated_parameters": [
191
- "get_invalidated_parameters",
192
- status_code,
193
- request_data,
194
- ],
195
- }
196
- invalidation_keywords = []
197
-
198
- if request_data.dto.get_relations_for_error_code(status_code):
199
- invalidation_keywords.append("get_invalid_json_data")
200
- if request_data.dto.get_parameter_relations_for_error_code(status_code):
201
- invalidation_keywords.append("get_invalidated_parameters")
202
- if invalidation_keywords:
203
- if (
204
- invalidation_keyword := choice(invalidation_keywords)
205
- ) == "get_invalid_json_data":
206
- json_data = run_keyword(
207
- *invalidation_keyword_data[invalidation_keyword]
208
- )
209
- else:
210
- params, headers = run_keyword(
211
- *invalidation_keyword_data[invalidation_keyword]
212
- )
213
- # if there are no relations to invalide and the status_code is the default
214
- # response_code for invalid properties, invalidate properties instead
215
- elif status_code == self.invalid_property_default_response:
216
- if (
217
- request_data.params_that_can_be_invalidated
218
- or request_data.headers_that_can_be_invalidated
219
- ):
220
- params, headers = run_keyword(
221
- *invalidation_keyword_data["get_invalidated_parameters"]
222
- )
223
- if request_data.dto_schema:
224
- json_data = run_keyword(
225
- *invalidation_keyword_data["get_invalid_json_data"]
226
- )
227
- elif request_data.dto_schema:
228
- json_data = run_keyword(
229
- *invalidation_keyword_data["get_invalid_json_data"]
230
- )
231
- else:
232
- raise SkipExecution(
233
- "No properties or parameters can be invalidated."
234
- )
235
- else:
236
- raise AssertionError(
237
- f"No Dto mapping found to cause status_code {status_code}."
238
- )
239
- run_keyword(
240
- "perform_validated_request",
241
- path,
242
- status_code,
243
- RequestValues(
244
- url=url,
245
- method=method,
246
- params=params,
247
- headers=headers,
248
- json_data=json_data,
249
- ),
250
- original_data,
251
- )
252
- if status_code < 300 and (
253
- request_data.has_optional_properties
254
- or request_data.has_optional_params
255
- or request_data.has_optional_headers
256
- ):
257
- logger.info("Performing request without optional properties and parameters")
258
- url = run_keyword("get_valid_url", path, method)
259
- request_data = self.get_request_data(method=method, endpoint=path)
260
- params = request_data.get_required_params()
261
- headers = request_data.get_required_headers()
262
- json_data = request_data.get_required_properties_dict()
263
- original_data = None
264
- if method == "PATCH":
265
- original_data = self.get_original_data(url=url)
266
- run_keyword(
267
- "perform_validated_request",
268
- path,
269
- status_code,
270
- RequestValues(
271
- url=url,
272
- method=method,
273
- params=params,
274
- headers=headers,
275
- json_data=json_data,
276
- ),
277
- original_data,
278
- )
279
-
280
- def get_original_data(self, url: str) -> Optional[Dict[str, Any]]:
281
- """
282
- Attempt to GET the current data for the given url and return it.
283
-
284
- If the GET request fails, None is returned.
285
- """
286
- original_data = None
287
- path = self.get_parameterized_endpoint_from_url(url)
288
- get_request_data = self.get_request_data(endpoint=path, method="GET")
289
- get_params = get_request_data.params
290
- get_headers = get_request_data.headers
291
- response: Response = run_keyword(
292
- "authorized_request", url, "GET", get_params, get_headers
293
- )
294
- if response.ok:
295
- original_data = response.json()
296
- return original_data
297
-
298
- @keyword
299
- def perform_validated_request(
300
- self,
301
- path: str,
302
- status_code: int,
303
- request_values: RequestValues,
304
- original_data: Optional[Dict[str, Any]] = None,
305
- ) -> None:
306
- """
307
- This keyword first calls the Authorized Request keyword, then the Validate
308
- Response keyword and finally validates, for `DELETE` operations, whether
309
- the target resource was indeed deleted (OK response) or not (error responses).
310
- """
311
- response = run_keyword(
312
- "authorized_request",
313
- request_values.url,
314
- request_values.method,
315
- request_values.params,
316
- request_values.headers,
317
- request_values.json_data,
318
- )
319
- if response.status_code != status_code:
320
- try:
321
- response_json = response.json()
322
- except Exception as _: # pylint: disable=broad-except
323
- logger.info(
324
- f"Failed to get json content from response. "
325
- f"Response text was: {response.text}"
326
- )
327
- response_json = {}
328
- if not response.ok:
329
- if description := response_json.get("detail"):
330
- pass
331
- else:
332
- description = response_json.get(
333
- "message", "response contains no message or detail."
334
- )
335
- logger.error(f"{response.reason}: {description}")
336
-
337
- logger.debug(
338
- f"\nSend: {_json.dumps(request_values.json_data, indent=4, sort_keys=True)}"
339
- f"\nGot: {_json.dumps(response_json, indent=4, sort_keys=True)}"
340
- )
341
- raise AssertionError(
342
- f"Response status_code {response.status_code} was not {status_code}"
343
- )
344
-
345
- run_keyword("validate_response", path, response, original_data)
346
-
347
- if request_values.method == "DELETE":
348
- get_request_data = self.get_request_data(endpoint=path, method="GET")
349
- get_params = get_request_data.params
350
- get_headers = get_request_data.headers
351
- get_response = run_keyword(
352
- "authorized_request", request_values.url, "GET", get_params, get_headers
353
- )
354
- if response.ok:
355
- if get_response.ok:
356
- raise AssertionError(
357
- f"Resource still exists after deletion. Url was {request_values.url}"
358
- )
359
- # if the path supports GET, 404 is expected, if not 405 is expected
360
- if get_response.status_code not in [404, 405]:
361
- logger.warning(
362
- f"Unexpected response after deleting resource: Status_code "
363
- f"{get_response.status_code} was received after trying to get {request_values.url} "
364
- f"after sucessfully deleting it."
365
- )
366
- elif not get_response.ok:
367
- raise AssertionError(
368
- f"Resource could not be retrieved after failed deletion. "
369
- f"Url was {request_values.url}, status_code was {get_response.status_code}"
370
- )
371
-
372
- @keyword
373
- def validate_response(
374
- self,
375
- path: str,
376
- response: Response,
377
- original_data: Optional[Dict[str, Any]] = None,
378
- ) -> None:
379
- """
380
- Validate the `response` by performing the following validations:
381
- - validate the `response` against the openapi schema for the `endpoint`
382
- - validate that the response does not contain extra properties
383
- - validate that a href, if present, refers to the correct resource
384
- - validate that the value for a property that is in the response is equal to
385
- the property value that was send
386
- - validate that no `original_data` is preserved when performing a PUT operation
387
- - validate that a PATCH operation only updates the provided properties
388
- """
389
- if response.status_code == 204:
390
- assert not response.content
391
- return None
392
-
393
- try:
394
- self._validate_response_against_spec(response)
395
- except OpenAPIError:
396
- raise Failure("Response did not pass schema validation.")
397
-
398
- request_method = response.request.method
399
- if request_method is None:
400
- logger.warning(
401
- f"Could not validate response for path {path}; no method found "
402
- f"on the request property of the provided response."
403
- )
404
- return None
405
-
406
- response_spec = self._get_response_spec(
407
- path=path,
408
- method=request_method,
409
- status_code=response.status_code,
410
- )
411
-
412
- content_type_from_response = response.headers.get("Content-Type", "unknown")
413
- mime_type_from_response, _, _ = content_type_from_response.partition(";")
414
-
415
- if not response_spec.get("content"):
416
- logger.warning(
417
- "The response cannot be validated: 'content' not specified in the OAS."
418
- )
419
- return None
420
-
421
- # multiple content types can be specified in the OAS
422
- content_types = list(response_spec["content"].keys())
423
- supported_types = [
424
- ct for ct in content_types if ct.partition(";")[0].endswith("json")
425
- ]
426
- if not supported_types:
427
- raise NotImplementedError(
428
- f"The content_types '{content_types}' are not supported. "
429
- f"Only json types are currently supported."
430
- )
431
- content_type = supported_types[0]
432
- mime_type = content_type.partition(";")[0]
433
-
434
- if mime_type != mime_type_from_response:
435
- raise ValueError(
436
- f"Content-Type '{content_type_from_response}' of the response "
437
- f"does not match '{mime_type}' as specified in the OpenAPI document."
438
- )
439
-
440
- json_response = response.json()
441
- response_schema = resolve_schema(
442
- response_spec["content"][content_type]["schema"]
443
- )
444
- if list_item_schema := response_schema.get("items"):
445
- if not isinstance(json_response, list):
446
- raise AssertionError(
447
- f"Response schema violation: the schema specifies an array as "
448
- f"response type but the response was of type {type(json_response)}."
449
- )
450
- type_of_list_items = list_item_schema.get("type")
451
- if type_of_list_items == "object":
452
- for resource in json_response:
453
- run_keyword(
454
- "validate_resource_properties", resource, list_item_schema
455
- )
456
- else:
457
- for item in json_response:
458
- self._validate_value_type(
459
- value=item, expected_type=type_of_list_items
460
- )
461
- # no further validation; value validation of individual resources should
462
- # be performed on the endpoints for the specific resource
463
- return None
464
-
465
- run_keyword("validate_resource_properties", json_response, response_schema)
466
- # ensure the href is valid if present in the response
467
- if href := json_response.get("href"):
468
- self._assert_href_is_valid(href, json_response)
469
- # every property that was sucessfully send and that is in the response
470
- # schema must have the value that was send
471
- if response.ok and response.request.method in ["POST", "PUT", "PATCH"]:
472
- run_keyword("validate_send_response", response, original_data)
473
- return None
474
-
475
- def _assert_href_is_valid(self, href: str, json_response: Dict[str, Any]) -> None:
476
- url = f"{self.origin}{href}"
477
- path = url.replace(self.base_url, "")
478
- request_data = self.get_request_data(endpoint=path, method="GET")
479
- params = request_data.params
480
- headers = request_data.headers
481
- get_response = run_keyword("authorized_request", url, "GET", params, headers)
482
- assert (
483
- get_response.json() == json_response
484
- ), f"{get_response.json()} not equal to original {json_response}"
485
-
486
- def _validate_response_against_spec(self, response: Response) -> None:
487
- try:
488
- self.validate_response_vs_spec(
489
- request=RequestsOpenAPIRequest(response.request),
490
- response=RequestsOpenAPIResponse(response),
491
- )
492
- except InvalidData as exception:
493
- errors: List[InvalidSchemaValue] = exception.__cause__
494
- validation_errors: Optional[List[ValidationError]] = getattr(
495
- errors, "schema_errors", None
496
- )
497
- if validation_errors:
498
- error_message = "\n".join(
499
- [
500
- f"{list(error.schema_path)}: {error.message}"
501
- for error in validation_errors
502
- ]
503
- )
504
- else:
505
- error_message = str(exception)
506
-
507
- if response.status_code == self.invalid_property_default_response:
508
- logger.debug(error_message)
509
- return
510
- if self.response_validation == ValidationLevel.STRICT:
511
- logger.error(error_message)
512
- raise exception
513
- if self.response_validation == ValidationLevel.WARN:
514
- logger.warning(error_message)
515
- elif self.response_validation == ValidationLevel.INFO:
516
- logger.info(error_message)
517
-
518
- @keyword
519
- def validate_resource_properties(
520
- self, resource: Dict[str, Any], schema: Dict[str, Any]
521
- ) -> None:
522
- """
523
- Validate that the `resource` does not contain any properties that are not
524
- defined in the `schema_properties`.
525
- """
526
- schema_properties = schema.get("properties", {})
527
- property_names_from_schema = set(schema_properties.keys())
528
- property_names_in_resource = set(resource.keys())
529
-
530
- if property_names_from_schema != property_names_in_resource:
531
- # The additionalProperties property determines whether properties with
532
- # unspecified names are allowed. This property can be boolean or an object
533
- # (dict) that specifies the type of any additional properties.
534
- additional_properties = schema.get("additionalProperties", True)
535
- if isinstance(additional_properties, bool):
536
- allow_additional_properties = additional_properties
537
- allowed_additional_properties_type = None
538
- else:
539
- allow_additional_properties = True
540
- allowed_additional_properties_type = additional_properties["type"]
541
-
542
- extra_property_names = property_names_in_resource.difference(
543
- property_names_from_schema
544
- )
545
- if allow_additional_properties:
546
- # If a type is defined for extra properties, validate them
547
- if allowed_additional_properties_type:
548
- extra_properties = {
549
- key: value
550
- for key, value in resource.items()
551
- if key in extra_property_names
552
- }
553
- self._validate_type_of_extra_properties(
554
- extra_properties=extra_properties,
555
- expected_type=allowed_additional_properties_type,
556
- )
557
- # If allowed, validation should not fail on extra properties
558
- extra_property_names = set()
559
-
560
- required_properties = set(schema.get("required", []))
561
- missing_properties = required_properties.difference(
562
- property_names_in_resource
563
- )
564
-
565
- if extra_property_names or missing_properties:
566
- extra = (
567
- f"\n\tExtra properties in response: {extra_property_names}"
568
- if extra_property_names
569
- else ""
570
- )
571
- missing = (
572
- f"\n\tRequired properties missing in response: {missing_properties}"
573
- if missing_properties
574
- else ""
575
- )
576
- raise AssertionError(
577
- f"Response schema violation: the response contains properties that are "
578
- f"not specified in the schema or does not contain properties that are "
579
- f"required according to the schema."
580
- f"\n\tReceived in the response: {property_names_in_resource}"
581
- f"\n\tDefined in the schema: {property_names_from_schema}"
582
- f"{extra}{missing}"
583
- )
584
-
585
- @staticmethod
586
- def _validate_value_type(value: Any, expected_type: str) -> None:
587
- type_mapping = {
588
- "string": str,
589
- "number": float,
590
- "integer": int,
591
- "boolean": bool,
592
- "array": list,
593
- "object": dict,
594
- }
595
- python_type = type_mapping.get(expected_type, None)
596
- if python_type is None:
597
- raise AssertionError(
598
- f"Validation of type '{expected_type}' is not supported."
599
- )
600
- if not isinstance(value, python_type):
601
- raise AssertionError(f"{value} is not of type {expected_type}")
602
-
603
- @staticmethod
604
- def _validate_type_of_extra_properties(
605
- extra_properties: Dict[str, Any], expected_type: str
606
- ) -> None:
607
- type_mapping = {
608
- "string": str,
609
- "number": float,
610
- "integer": int,
611
- "boolean": bool,
612
- "array": list,
613
- "object": dict,
614
- }
615
-
616
- python_type = type_mapping.get(expected_type, None)
617
- if python_type is None:
618
- logger.warning(
619
- f"Additonal properties were not validated: "
620
- f"type '{expected_type}' is not supported."
621
- )
622
- return
623
-
624
- invalid_extra_properties = {
625
- key: value
626
- for key, value in extra_properties.items()
627
- if not isinstance(value, python_type)
628
- }
629
- if invalid_extra_properties:
630
- raise AssertionError(
631
- f"Response contains invalid additionalProperties: "
632
- f"{invalid_extra_properties} are not of type {expected_type}."
633
- )
634
-
635
- @staticmethod
636
- @keyword
637
- def validate_send_response(
638
- response: Response, original_data: Optional[Dict[str, Any]] = None
639
- ) -> None:
640
- """
641
- Validate that each property that was send that is in the response has the value
642
- that was send.
643
- In case a PATCH request, validate that only the properties that were patched
644
- have changed and that other properties are still at their pre-patch values.
645
- """
646
-
647
- def validate_list_response(
648
- send_list: List[Any], received_list: List[Any]
649
- ) -> None:
650
- for item in send_list:
651
- if item not in received_list:
652
- raise AssertionError(
653
- f"Received value '{received_list}' does "
654
- f"not contain '{item}' in the {response.request.method} request."
655
- f"\nSend: {_json.dumps(send_json, indent=4, sort_keys=True)}"
656
- f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
657
- )
658
-
659
- def validate_dict_response(
660
- send_dict: Dict[str, Any], received_dict: Dict[str, Any]
661
- ) -> None:
662
- for send_property_name, send_property_value in send_dict.items():
663
- # sometimes, a property in the request is not in the response, e.g. a password
664
- if send_property_name not in received_dict.keys():
665
- continue
666
- if send_property_value is not None:
667
- # if a None value is send, the target property should be cleared or
668
- # reverted to the default value (which cannot be specified in the
669
- # openapi document)
670
- received_value = received_dict[send_property_name]
671
- # In case of lists / arrays, the send values are often appended to
672
- # existing data
673
- if isinstance(received_value, list):
674
- validate_list_response(
675
- send_list=send_property_value, received_list=received_value
676
- )
677
- continue
678
-
679
- # when dealing with objects, we'll need to iterate the properties
680
- if isinstance(received_value, dict):
681
- validate_dict_response(
682
- send_dict=send_property_value, received_dict=received_value
683
- )
684
- continue
685
-
686
- assert received_value == send_property_value, (
687
- f"Received value for {send_property_name} '{received_value}' does not "
688
- f"match '{send_property_value}' in the {response.request.method} request."
689
- f"\nSend: {_json.dumps(send_json, indent=4, sort_keys=True)}"
690
- f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
691
- )
692
-
693
- if response.request.body is None:
694
- logger.warning(
695
- "Could not validate send response; the body of the request property "
696
- "on the provided response was None."
697
- )
698
- return None
699
- if isinstance(response.request.body, bytes):
700
- send_json = _json.loads(response.request.body.decode("UTF-8"))
701
- else:
702
- send_json = _json.loads(response.request.body)
703
-
704
- response_data = response.json()
705
- # POST on /resource_type/{id}/array_item/ will return the updated {id} resource
706
- # instead of a newly created resource. In this case, the send_json must be
707
- # in the array of the 'array_item' property on {id}
708
- send_path: str = response.request.path_url
709
- response_path = response_data.get("href", None)
710
- if response_path and send_path not in response_path:
711
- property_to_check = send_path.replace(response_path, "")[1:]
712
- if response_data.get(property_to_check) and isinstance(
713
- response_data[property_to_check], list
714
- ):
715
- item_list: List[Dict[str, Any]] = response_data[property_to_check]
716
- # Use the (mandatory) id to get the POSTed resource from the list
717
- [response_data] = [
718
- item for item in item_list if item["id"] == send_json["id"]
719
- ]
720
-
721
- # incoming arguments are dictionaries, so they can be validated as such
722
- validate_dict_response(send_dict=send_json, received_dict=response_data)
723
-
724
- # In case of PATCH requests, ensure that only send properties have changed
725
- if original_data:
726
- for send_property_name, send_value in original_data.items():
727
- if send_property_name not in send_json.keys():
728
- assert send_value == response_data[send_property_name], (
729
- f"Received value for {send_property_name} '{response_data[send_property_name]}' does not "
730
- f"match '{send_value}' in the pre-patch data"
731
- f"\nPre-patch: {_json.dumps(original_data, indent=4, sort_keys=True)}"
732
- f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
733
- )
734
- return None
735
-
736
- def _get_response_spec(
737
- self, path: str, method: str, status_code: int
738
- ) -> Dict[str, Any]:
739
- method = method.lower()
740
- status = str(status_code)
741
- spec: Dict[str, Any] = {**self.openapi_spec}["paths"][path][method][
742
- "responses"
743
- ][status]
744
- return spec
1
+ """Module containing the classes to perform automatic OpenAPI contract validation."""
2
+
3
+ import json as _json
4
+ from enum import Enum
5
+ from logging import getLogger
6
+ from pathlib import Path
7
+ from random import choice
8
+ from typing import Any, Dict, List, Optional, Tuple, Union
9
+
10
+ from openapi_core.contrib.requests import (
11
+ RequestsOpenAPIRequest,
12
+ RequestsOpenAPIResponse,
13
+ )
14
+ from openapi_core.exceptions import OpenAPIError
15
+ from openapi_core.validation.exceptions import ValidationError
16
+ from openapi_core.validation.response.exceptions import InvalidData
17
+ from openapi_core.validation.schemas.exceptions import InvalidSchemaValue
18
+ from requests import Response
19
+ from requests.auth import AuthBase
20
+ from requests.cookies import RequestsCookieJar as CookieJar
21
+ from robot.api import Failure, SkipExecution
22
+ from robot.api.deco import keyword, library
23
+ from robot.libraries.BuiltIn import BuiltIn
24
+
25
+ from OpenApiLibCore import OpenApiLibCore, RequestData, RequestValues, resolve_schema
26
+
27
+ run_keyword = BuiltIn().run_keyword
28
+
29
+
30
+ logger = getLogger(__name__)
31
+
32
+
33
+ class ValidationLevel(str, Enum):
34
+ """The available levels for the response_validation parameter."""
35
+
36
+ DISABLED = "DISABLED"
37
+ INFO = "INFO"
38
+ WARN = "WARN"
39
+ STRICT = "STRICT"
40
+
41
+
42
+ @library(scope="TEST SUITE", doc_format="ROBOT")
43
+ class OpenApiExecutors(OpenApiLibCore): # pylint: disable=too-many-instance-attributes
44
+ """Main class providing the keywords and core logic to perform endpoint validations."""
45
+
46
+ def __init__( # pylint: disable=too-many-arguments
47
+ self,
48
+ source: str,
49
+ origin: str = "",
50
+ base_path: str = "",
51
+ response_validation: ValidationLevel = ValidationLevel.WARN,
52
+ disable_server_validation: bool = True,
53
+ mappings_path: Union[str, Path] = "",
54
+ invalid_property_default_response: int = 422,
55
+ default_id_property_name: str = "id",
56
+ faker_locale: Optional[Union[str, List[str]]] = None,
57
+ require_body_for_invalid_url: bool = False,
58
+ recursion_limit: int = 1,
59
+ recursion_default: Any = {},
60
+ username: str = "",
61
+ password: str = "",
62
+ security_token: str = "",
63
+ auth: Optional[AuthBase] = None,
64
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
65
+ verify_tls: Optional[Union[bool, str]] = True,
66
+ extra_headers: Optional[Dict[str, str]] = None,
67
+ cookies: Optional[Union[Dict[str, str], CookieJar]] = None,
68
+ proxies: Optional[Dict[str, str]] = None,
69
+ ) -> None:
70
+ super().__init__(
71
+ source=source,
72
+ origin=origin,
73
+ base_path=base_path,
74
+ mappings_path=mappings_path,
75
+ default_id_property_name=default_id_property_name,
76
+ faker_locale=faker_locale,
77
+ recursion_limit=recursion_limit,
78
+ recursion_default=recursion_default,
79
+ username=username,
80
+ password=password,
81
+ security_token=security_token,
82
+ auth=auth,
83
+ cert=cert,
84
+ verify_tls=verify_tls,
85
+ extra_headers=extra_headers,
86
+ cookies=cookies,
87
+ proxies=proxies,
88
+ )
89
+ self.response_validation = response_validation
90
+ self.disable_server_validation = disable_server_validation
91
+ self.require_body_for_invalid_url = require_body_for_invalid_url
92
+ self.invalid_property_default_response = invalid_property_default_response
93
+
94
+ @keyword
95
+ def test_unauthorized(self, path: str, method: str) -> None:
96
+ """
97
+ Perform a request for `method` on the `path`, with no authorization.
98
+
99
+ This keyword only passes if the response code is 401: Unauthorized.
100
+
101
+ Any authorization parameters used to initialize the library are
102
+ ignored for this request.
103
+ > Note: No headers or (json) body are send with the request. For security
104
+ reasons, the authorization validation should be checked first.
105
+ """
106
+ url: str = run_keyword("get_valid_url", path, method)
107
+ response = self.session.request(
108
+ method=method,
109
+ url=url,
110
+ verify=False,
111
+ )
112
+ if response.status_code != 401:
113
+ raise AssertionError(f"Response {response.status_code} was not 401.")
114
+
115
+ @keyword
116
+ def test_forbidden(self, path: str, method: str) -> None:
117
+ """
118
+ Perform a request for `method` on the `path`, with the provided authorization.
119
+
120
+ This keyword only passes if the response code is 403: Forbidden.
121
+
122
+ For this keyword to pass, the authorization parameters used to initialize the
123
+ library should grant insufficient access rights to the target endpoint.
124
+ > Note: No headers or (json) body are send with the request. For security
125
+ reasons, the access rights validation should be checked first.
126
+ """
127
+ url: str = run_keyword("get_valid_url", path, method)
128
+ response: Response = run_keyword("authorized_request", url, method)
129
+ if response.status_code != 403:
130
+ raise AssertionError(f"Response {response.status_code} was not 403.")
131
+
132
+ @keyword
133
+ def test_invalid_url(
134
+ self, path: str, method: str, expected_status_code: int = 404
135
+ ) -> None:
136
+ """
137
+ Perform a request for the provided 'path' and 'method' where the url for
138
+ the `path` is invalidated.
139
+
140
+ This keyword will be `SKIPPED` if the path contains no parts that
141
+ can be invalidated.
142
+
143
+ The optional `expected_status_code` parameter (default: 404) can be set to the
144
+ expected status code for APIs that do not return a 404 on invalid urls.
145
+
146
+ > Note: Depending on API design, the url may be validated before or after
147
+ validation of headers, query parameters and / or (json) body. By default, no
148
+ parameters are send with the request. The `require_body_for_invalid_url`
149
+ parameter can be set to `True` if needed.
150
+ """
151
+ valid_url: str = run_keyword("get_valid_url", path, method)
152
+
153
+ if not (url := run_keyword("get_invalidated_url", valid_url)):
154
+ raise SkipExecution(
155
+ f"Path {path} does not contain resource references that "
156
+ f"can be invalidated."
157
+ )
158
+
159
+ params, headers, json_data = None, None, None
160
+ if self.require_body_for_invalid_url:
161
+ request_data = self.get_request_data(method=method, endpoint=path)
162
+ params = request_data.params
163
+ headers = request_data.headers
164
+ dto = request_data.dto
165
+ json_data = dto.as_dict()
166
+ response: Response = run_keyword(
167
+ "authorized_request", url, method, params, headers, json_data
168
+ )
169
+ if response.status_code != expected_status_code:
170
+ raise AssertionError(
171
+ f"Response {response.status_code} was not {expected_status_code}"
172
+ )
173
+
174
+ @keyword
175
+ def test_endpoint(self, path: str, method: str, status_code: int) -> None:
176
+ """
177
+ Validate that performing the `method` operation on `path` results in a
178
+ `status_code` response.
179
+
180
+ This is the main keyword to be used in the `Test Template` keyword when using
181
+ the OpenApiDriver.
182
+
183
+ The keyword calls other keywords to generate the neccesary data to perform
184
+ the desired operation and validate the response against the openapi document.
185
+ """
186
+ json_data: Optional[Dict[str, Any]] = None
187
+ original_data = None
188
+
189
+ url: str = run_keyword("get_valid_url", path, method)
190
+ request_data: RequestData = self.get_request_data(method=method, endpoint=path)
191
+ params = request_data.params
192
+ headers = request_data.headers
193
+ if request_data.has_body:
194
+ json_data = request_data.dto.as_dict()
195
+ # when patching, get the original data to check only patched data has changed
196
+ if method == "PATCH":
197
+ original_data = self.get_original_data(url=url)
198
+ # in case of a status code indicating an error, ensure the error occurs
199
+ if status_code >= 400:
200
+ invalidation_keyword_data = {
201
+ "get_invalid_json_data": [
202
+ "get_invalid_json_data",
203
+ url,
204
+ method,
205
+ status_code,
206
+ request_data,
207
+ ],
208
+ "get_invalidated_parameters": [
209
+ "get_invalidated_parameters",
210
+ status_code,
211
+ request_data,
212
+ ],
213
+ }
214
+ invalidation_keywords = []
215
+
216
+ if request_data.dto.get_relations_for_error_code(status_code):
217
+ invalidation_keywords.append("get_invalid_json_data")
218
+ if request_data.dto.get_parameter_relations_for_error_code(status_code):
219
+ invalidation_keywords.append("get_invalidated_parameters")
220
+ if invalidation_keywords:
221
+ if (
222
+ invalidation_keyword := choice(invalidation_keywords)
223
+ ) == "get_invalid_json_data":
224
+ json_data = run_keyword(
225
+ *invalidation_keyword_data[invalidation_keyword]
226
+ )
227
+ else:
228
+ params, headers = run_keyword(
229
+ *invalidation_keyword_data[invalidation_keyword]
230
+ )
231
+ # if there are no relations to invalide and the status_code is the default
232
+ # response_code for invalid properties, invalidate properties instead
233
+ elif status_code == self.invalid_property_default_response:
234
+ if (
235
+ request_data.params_that_can_be_invalidated
236
+ or request_data.headers_that_can_be_invalidated
237
+ ):
238
+ params, headers = run_keyword(
239
+ *invalidation_keyword_data["get_invalidated_parameters"]
240
+ )
241
+ if request_data.dto_schema:
242
+ json_data = run_keyword(
243
+ *invalidation_keyword_data["get_invalid_json_data"]
244
+ )
245
+ elif request_data.dto_schema:
246
+ json_data = run_keyword(
247
+ *invalidation_keyword_data["get_invalid_json_data"]
248
+ )
249
+ else:
250
+ raise SkipExecution(
251
+ "No properties or parameters can be invalidated."
252
+ )
253
+ else:
254
+ raise AssertionError(
255
+ f"No Dto mapping found to cause status_code {status_code}."
256
+ )
257
+ run_keyword(
258
+ "perform_validated_request",
259
+ path,
260
+ status_code,
261
+ RequestValues(
262
+ url=url,
263
+ method=method,
264
+ params=params,
265
+ headers=headers,
266
+ json_data=json_data,
267
+ ),
268
+ original_data,
269
+ )
270
+ if status_code < 300 and (
271
+ request_data.has_optional_properties
272
+ or request_data.has_optional_params
273
+ or request_data.has_optional_headers
274
+ ):
275
+ logger.info("Performing request without optional properties and parameters")
276
+ url = run_keyword("get_valid_url", path, method)
277
+ request_data = self.get_request_data(method=method, endpoint=path)
278
+ params = request_data.get_required_params()
279
+ headers = request_data.get_required_headers()
280
+ json_data = (
281
+ request_data.get_minimal_body_dict() if request_data.has_body else None
282
+ )
283
+ original_data = None
284
+ if method == "PATCH":
285
+ original_data = self.get_original_data(url=url)
286
+ run_keyword(
287
+ "perform_validated_request",
288
+ path,
289
+ status_code,
290
+ RequestValues(
291
+ url=url,
292
+ method=method,
293
+ params=params,
294
+ headers=headers,
295
+ json_data=json_data,
296
+ ),
297
+ original_data,
298
+ )
299
+
300
+ def get_original_data(self, url: str) -> Optional[Dict[str, Any]]:
301
+ """
302
+ Attempt to GET the current data for the given url and return it.
303
+
304
+ If the GET request fails, None is returned.
305
+ """
306
+ original_data = None
307
+ path = self.get_parameterized_endpoint_from_url(url)
308
+ get_request_data = self.get_request_data(endpoint=path, method="GET")
309
+ get_params = get_request_data.params
310
+ get_headers = get_request_data.headers
311
+ response: Response = run_keyword(
312
+ "authorized_request", url, "GET", get_params, get_headers
313
+ )
314
+ if response.ok:
315
+ original_data = response.json()
316
+ return original_data
317
+
318
+ @keyword
319
+ def perform_validated_request(
320
+ self,
321
+ path: str,
322
+ status_code: int,
323
+ request_values: RequestValues,
324
+ original_data: Optional[Dict[str, Any]] = None,
325
+ ) -> None:
326
+ """
327
+ This keyword first calls the Authorized Request keyword, then the Validate
328
+ Response keyword and finally validates, for `DELETE` operations, whether
329
+ the target resource was indeed deleted (OK response) or not (error responses).
330
+ """
331
+ response = run_keyword(
332
+ "authorized_request",
333
+ request_values.url,
334
+ request_values.method,
335
+ request_values.params,
336
+ request_values.headers,
337
+ request_values.json_data,
338
+ )
339
+ if response.status_code != status_code:
340
+ try:
341
+ response_json = response.json()
342
+ except Exception as _: # pylint: disable=broad-except
343
+ logger.info(
344
+ f"Failed to get json content from response. "
345
+ f"Response text was: {response.text}"
346
+ )
347
+ response_json = {}
348
+ if not response.ok:
349
+ if description := response_json.get("detail"):
350
+ pass
351
+ else:
352
+ description = response_json.get(
353
+ "message", "response contains no message or detail."
354
+ )
355
+ logger.error(f"{response.reason}: {description}")
356
+
357
+ logger.debug(
358
+ f"\nSend: {_json.dumps(request_values.json_data, indent=4, sort_keys=True)}"
359
+ f"\nGot: {_json.dumps(response_json, indent=4, sort_keys=True)}"
360
+ )
361
+ raise AssertionError(
362
+ f"Response status_code {response.status_code} was not {status_code}"
363
+ )
364
+
365
+ run_keyword("validate_response", path, response, original_data)
366
+
367
+ if request_values.method == "DELETE":
368
+ get_request_data = self.get_request_data(endpoint=path, method="GET")
369
+ get_params = get_request_data.params
370
+ get_headers = get_request_data.headers
371
+ get_response = run_keyword(
372
+ "authorized_request", request_values.url, "GET", get_params, get_headers
373
+ )
374
+ if response.ok:
375
+ if get_response.ok:
376
+ raise AssertionError(
377
+ f"Resource still exists after deletion. Url was {request_values.url}"
378
+ )
379
+ # if the path supports GET, 404 is expected, if not 405 is expected
380
+ if get_response.status_code not in [404, 405]:
381
+ logger.warning(
382
+ f"Unexpected response after deleting resource: Status_code "
383
+ f"{get_response.status_code} was received after trying to get {request_values.url} "
384
+ f"after sucessfully deleting it."
385
+ )
386
+ elif not get_response.ok:
387
+ raise AssertionError(
388
+ f"Resource could not be retrieved after failed deletion. "
389
+ f"Url was {request_values.url}, status_code was {get_response.status_code}"
390
+ )
391
+
392
+ @keyword
393
+ def validate_response(
394
+ self,
395
+ path: str,
396
+ response: Response,
397
+ original_data: Optional[Dict[str, Any]] = None,
398
+ ) -> None:
399
+ """
400
+ Validate the `response` by performing the following validations:
401
+ - validate the `response` against the openapi schema for the `endpoint`
402
+ - validate that the response does not contain extra properties
403
+ - validate that a href, if present, refers to the correct resource
404
+ - validate that the value for a property that is in the response is equal to
405
+ the property value that was send
406
+ - validate that no `original_data` is preserved when performing a PUT operation
407
+ - validate that a PATCH operation only updates the provided properties
408
+ """
409
+ if response.status_code == 204:
410
+ assert not response.content
411
+ return None
412
+
413
+ try:
414
+ self._validate_response_against_spec(response)
415
+ except OpenAPIError:
416
+ raise Failure("Response did not pass schema validation.")
417
+
418
+ request_method = response.request.method
419
+ if request_method is None:
420
+ logger.warning(
421
+ f"Could not validate response for path {path}; no method found "
422
+ f"on the request property of the provided response."
423
+ )
424
+ return None
425
+
426
+ response_spec = self._get_response_spec(
427
+ path=path,
428
+ method=request_method,
429
+ status_code=response.status_code,
430
+ )
431
+
432
+ content_type_from_response = response.headers.get("Content-Type", "unknown")
433
+ mime_type_from_response, _, _ = content_type_from_response.partition(";")
434
+
435
+ if not response_spec.get("content"):
436
+ logger.warning(
437
+ "The response cannot be validated: 'content' not specified in the OAS."
438
+ )
439
+ return None
440
+
441
+ # multiple content types can be specified in the OAS
442
+ content_types = list(response_spec["content"].keys())
443
+ supported_types = [
444
+ ct for ct in content_types if ct.partition(";")[0].endswith("json")
445
+ ]
446
+ if not supported_types:
447
+ raise NotImplementedError(
448
+ f"The content_types '{content_types}' are not supported. "
449
+ f"Only json types are currently supported."
450
+ )
451
+ content_type = supported_types[0]
452
+ mime_type = content_type.partition(";")[0]
453
+
454
+ if mime_type != mime_type_from_response:
455
+ raise ValueError(
456
+ f"Content-Type '{content_type_from_response}' of the response "
457
+ f"does not match '{mime_type}' as specified in the OpenAPI document."
458
+ )
459
+
460
+ json_response = response.json()
461
+ response_schema = resolve_schema(
462
+ response_spec["content"][content_type]["schema"]
463
+ )
464
+ if list_item_schema := response_schema.get("items"):
465
+ if not isinstance(json_response, list):
466
+ raise AssertionError(
467
+ f"Response schema violation: the schema specifies an array as "
468
+ f"response type but the response was of type {type(json_response)}."
469
+ )
470
+ type_of_list_items = list_item_schema.get("type")
471
+ if type_of_list_items == "object":
472
+ for resource in json_response:
473
+ run_keyword(
474
+ "validate_resource_properties", resource, list_item_schema
475
+ )
476
+ else:
477
+ for item in json_response:
478
+ self._validate_value_type(
479
+ value=item, expected_type=type_of_list_items
480
+ )
481
+ # no further validation; value validation of individual resources should
482
+ # be performed on the endpoints for the specific resource
483
+ return None
484
+
485
+ run_keyword("validate_resource_properties", json_response, response_schema)
486
+ # ensure the href is valid if present in the response
487
+ if href := json_response.get("href"):
488
+ self._assert_href_is_valid(href, json_response)
489
+ # every property that was sucessfully send and that is in the response
490
+ # schema must have the value that was send
491
+ if response.ok and response.request.method in ["POST", "PUT", "PATCH"]:
492
+ run_keyword("validate_send_response", response, original_data)
493
+ return None
494
+
495
+ def _assert_href_is_valid(self, href: str, json_response: Dict[str, Any]) -> None:
496
+ url = f"{self.origin}{href}"
497
+ path = url.replace(self.base_url, "")
498
+ request_data = self.get_request_data(endpoint=path, method="GET")
499
+ params = request_data.params
500
+ headers = request_data.headers
501
+ get_response = run_keyword("authorized_request", url, "GET", params, headers)
502
+ assert (
503
+ get_response.json() == json_response
504
+ ), f"{get_response.json()} not equal to original {json_response}"
505
+
506
+ def _validate_response_against_spec(self, response: Response) -> None:
507
+ try:
508
+ self.validate_response_vs_spec(
509
+ request=RequestsOpenAPIRequest(response.request),
510
+ response=RequestsOpenAPIResponse(response),
511
+ )
512
+ except InvalidData as exception:
513
+ errors: List[InvalidSchemaValue] = exception.__cause__
514
+ validation_errors: Optional[List[ValidationError]] = getattr(
515
+ errors, "schema_errors", None
516
+ )
517
+ if validation_errors:
518
+ error_message = "\n".join(
519
+ [
520
+ f"{list(error.schema_path)}: {error.message}"
521
+ for error in validation_errors
522
+ ]
523
+ )
524
+ else:
525
+ error_message = str(exception)
526
+
527
+ if response.status_code == self.invalid_property_default_response:
528
+ logger.debug(error_message)
529
+ return
530
+ if self.response_validation == ValidationLevel.STRICT:
531
+ logger.error(error_message)
532
+ raise exception
533
+ if self.response_validation == ValidationLevel.WARN:
534
+ logger.warning(error_message)
535
+ elif self.response_validation == ValidationLevel.INFO:
536
+ logger.info(error_message)
537
+
538
+ @keyword
539
+ def validate_resource_properties(
540
+ self, resource: Dict[str, Any], schema: Dict[str, Any]
541
+ ) -> None:
542
+ """
543
+ Validate that the `resource` does not contain any properties that are not
544
+ defined in the `schema_properties`.
545
+ """
546
+ schema_properties = schema.get("properties", {})
547
+ property_names_from_schema = set(schema_properties.keys())
548
+ property_names_in_resource = set(resource.keys())
549
+
550
+ if property_names_from_schema != property_names_in_resource:
551
+ # The additionalProperties property determines whether properties with
552
+ # unspecified names are allowed. This property can be boolean or an object
553
+ # (dict) that specifies the type of any additional properties.
554
+ additional_properties = schema.get("additionalProperties", True)
555
+ if isinstance(additional_properties, bool):
556
+ allow_additional_properties = additional_properties
557
+ allowed_additional_properties_type = None
558
+ else:
559
+ allow_additional_properties = True
560
+ allowed_additional_properties_type = additional_properties["type"]
561
+
562
+ extra_property_names = property_names_in_resource.difference(
563
+ property_names_from_schema
564
+ )
565
+ if allow_additional_properties:
566
+ # If a type is defined for extra properties, validate them
567
+ if allowed_additional_properties_type:
568
+ extra_properties = {
569
+ key: value
570
+ for key, value in resource.items()
571
+ if key in extra_property_names
572
+ }
573
+ self._validate_type_of_extra_properties(
574
+ extra_properties=extra_properties,
575
+ expected_type=allowed_additional_properties_type,
576
+ )
577
+ # If allowed, validation should not fail on extra properties
578
+ extra_property_names = set()
579
+
580
+ required_properties = set(schema.get("required", []))
581
+ missing_properties = required_properties.difference(
582
+ property_names_in_resource
583
+ )
584
+
585
+ if extra_property_names or missing_properties:
586
+ extra = (
587
+ f"\n\tExtra properties in response: {extra_property_names}"
588
+ if extra_property_names
589
+ else ""
590
+ )
591
+ missing = (
592
+ f"\n\tRequired properties missing in response: {missing_properties}"
593
+ if missing_properties
594
+ else ""
595
+ )
596
+ raise AssertionError(
597
+ f"Response schema violation: the response contains properties that are "
598
+ f"not specified in the schema or does not contain properties that are "
599
+ f"required according to the schema."
600
+ f"\n\tReceived in the response: {property_names_in_resource}"
601
+ f"\n\tDefined in the schema: {property_names_from_schema}"
602
+ f"{extra}{missing}"
603
+ )
604
+
605
+ @staticmethod
606
+ def _validate_value_type(value: Any, expected_type: str) -> None:
607
+ type_mapping = {
608
+ "string": str,
609
+ "number": float,
610
+ "integer": int,
611
+ "boolean": bool,
612
+ "array": list,
613
+ "object": dict,
614
+ }
615
+ python_type = type_mapping.get(expected_type, None)
616
+ if python_type is None:
617
+ raise AssertionError(
618
+ f"Validation of type '{expected_type}' is not supported."
619
+ )
620
+ if not isinstance(value, python_type):
621
+ raise AssertionError(f"{value} is not of type {expected_type}")
622
+
623
+ @staticmethod
624
+ def _validate_type_of_extra_properties(
625
+ extra_properties: Dict[str, Any], expected_type: str
626
+ ) -> None:
627
+ type_mapping = {
628
+ "string": str,
629
+ "number": float,
630
+ "integer": int,
631
+ "boolean": bool,
632
+ "array": list,
633
+ "object": dict,
634
+ }
635
+
636
+ python_type = type_mapping.get(expected_type, None)
637
+ if python_type is None:
638
+ logger.warning(
639
+ f"Additonal properties were not validated: "
640
+ f"type '{expected_type}' is not supported."
641
+ )
642
+ return
643
+
644
+ invalid_extra_properties = {
645
+ key: value
646
+ for key, value in extra_properties.items()
647
+ if not isinstance(value, python_type)
648
+ }
649
+ if invalid_extra_properties:
650
+ raise AssertionError(
651
+ f"Response contains invalid additionalProperties: "
652
+ f"{invalid_extra_properties} are not of type {expected_type}."
653
+ )
654
+
655
+ @staticmethod
656
+ @keyword
657
+ def validate_send_response(
658
+ response: Response, original_data: Optional[Dict[str, Any]] = None
659
+ ) -> None:
660
+ """
661
+ Validate that each property that was send that is in the response has the value
662
+ that was send.
663
+ In case a PATCH request, validate that only the properties that were patched
664
+ have changed and that other properties are still at their pre-patch values.
665
+ """
666
+
667
+ def validate_list_response(
668
+ send_list: List[Any], received_list: List[Any]
669
+ ) -> None:
670
+ for item in send_list:
671
+ if item not in received_list:
672
+ raise AssertionError(
673
+ f"Received value '{received_list}' does "
674
+ f"not contain '{item}' in the {response.request.method} request."
675
+ f"\nSend: {_json.dumps(send_json, indent=4, sort_keys=True)}"
676
+ f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
677
+ )
678
+
679
+ def validate_dict_response(
680
+ send_dict: Dict[str, Any], received_dict: Dict[str, Any]
681
+ ) -> None:
682
+ for send_property_name, send_property_value in send_dict.items():
683
+ # sometimes, a property in the request is not in the response, e.g. a password
684
+ if send_property_name not in received_dict.keys():
685
+ continue
686
+ if send_property_value is not None:
687
+ # if a None value is send, the target property should be cleared or
688
+ # reverted to the default value (which cannot be specified in the
689
+ # openapi document)
690
+ received_value = received_dict[send_property_name]
691
+ # In case of lists / arrays, the send values are often appended to
692
+ # existing data
693
+ if isinstance(received_value, list):
694
+ validate_list_response(
695
+ send_list=send_property_value, received_list=received_value
696
+ )
697
+ continue
698
+
699
+ # when dealing with objects, we'll need to iterate the properties
700
+ if isinstance(received_value, dict):
701
+ validate_dict_response(
702
+ send_dict=send_property_value, received_dict=received_value
703
+ )
704
+ continue
705
+
706
+ assert received_value == send_property_value, (
707
+ f"Received value for {send_property_name} '{received_value}' does not "
708
+ f"match '{send_property_value}' in the {response.request.method} request."
709
+ f"\nSend: {_json.dumps(send_json, indent=4, sort_keys=True)}"
710
+ f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
711
+ )
712
+
713
+ if response.request.body is None:
714
+ logger.warning(
715
+ "Could not validate send response; the body of the request property "
716
+ "on the provided response was None."
717
+ )
718
+ return None
719
+ if isinstance(response.request.body, bytes):
720
+ send_json = _json.loads(response.request.body.decode("UTF-8"))
721
+ else:
722
+ send_json = _json.loads(response.request.body)
723
+
724
+ response_data = response.json()
725
+ # POST on /resource_type/{id}/array_item/ will return the updated {id} resource
726
+ # instead of a newly created resource. In this case, the send_json must be
727
+ # in the array of the 'array_item' property on {id}
728
+ send_path: str = response.request.path_url
729
+ response_path = response_data.get("href", None)
730
+ if response_path and send_path not in response_path:
731
+ property_to_check = send_path.replace(response_path, "")[1:]
732
+ if response_data.get(property_to_check) and isinstance(
733
+ response_data[property_to_check], list
734
+ ):
735
+ item_list: List[Dict[str, Any]] = response_data[property_to_check]
736
+ # Use the (mandatory) id to get the POSTed resource from the list
737
+ [response_data] = [
738
+ item for item in item_list if item["id"] == send_json["id"]
739
+ ]
740
+
741
+ # incoming arguments are dictionaries, so they can be validated as such
742
+ validate_dict_response(send_dict=send_json, received_dict=response_data)
743
+
744
+ # In case of PATCH requests, ensure that only send properties have changed
745
+ if original_data:
746
+ for send_property_name, send_value in original_data.items():
747
+ if send_property_name not in send_json.keys():
748
+ assert send_value == response_data[send_property_name], (
749
+ f"Received value for {send_property_name} '{response_data[send_property_name]}' does not "
750
+ f"match '{send_value}' in the pre-patch data"
751
+ f"\nPre-patch: {_json.dumps(original_data, indent=4, sort_keys=True)}"
752
+ f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
753
+ )
754
+ return None
755
+
756
+ def _get_response_spec(
757
+ self, path: str, method: str, status_code: int
758
+ ) -> Dict[str, Any]:
759
+ method = method.lower()
760
+ status = str(status_code)
761
+ spec: Dict[str, Any] = {**self.openapi_spec}["paths"][path][method][
762
+ "responses"
763
+ ][status]
764
+ return spec