robotframework-openapitools 0.3.0__py3-none-any.whl → 1.0.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.
- OpenApiDriver/__init__.py +45 -41
- OpenApiDriver/openapi_executors.py +83 -49
- OpenApiDriver/openapi_reader.py +114 -116
- OpenApiDriver/openapidriver.libspec +209 -133
- OpenApiDriver/openapidriver.py +31 -296
- OpenApiLibCore/__init__.py +39 -13
- OpenApiLibCore/annotations.py +10 -0
- OpenApiLibCore/data_generation/__init__.py +10 -0
- OpenApiLibCore/data_generation/body_data_generation.py +250 -0
- OpenApiLibCore/data_generation/data_generation_core.py +233 -0
- OpenApiLibCore/data_invalidation.py +294 -0
- OpenApiLibCore/dto_base.py +75 -129
- OpenApiLibCore/dto_utils.py +125 -85
- OpenApiLibCore/localized_faker.py +88 -0
- OpenApiLibCore/models.py +723 -0
- OpenApiLibCore/oas_cache.py +14 -13
- OpenApiLibCore/openapi_libcore.libspec +363 -322
- OpenApiLibCore/openapi_libcore.py +388 -1903
- OpenApiLibCore/parameter_utils.py +97 -0
- OpenApiLibCore/path_functions.py +215 -0
- OpenApiLibCore/path_invalidation.py +42 -0
- OpenApiLibCore/protocols.py +38 -0
- OpenApiLibCore/request_data.py +246 -0
- OpenApiLibCore/resource_relations.py +55 -0
- OpenApiLibCore/validation.py +380 -0
- OpenApiLibCore/value_utils.py +216 -481
- openapi_libgen/__init__.py +3 -0
- openapi_libgen/command_line.py +75 -0
- openapi_libgen/generator.py +82 -0
- openapi_libgen/parsing_utils.py +30 -0
- openapi_libgen/spec_parser.py +154 -0
- openapi_libgen/templates/__init__.jinja +3 -0
- openapi_libgen/templates/library.jinja +30 -0
- robotframework_openapitools-1.0.0.dist-info/METADATA +249 -0
- robotframework_openapitools-1.0.0.dist-info/RECORD +40 -0
- {robotframework_openapitools-0.3.0.dist-info → robotframework_openapitools-1.0.0.dist-info}/WHEEL +1 -1
- robotframework_openapitools-1.0.0.dist-info/entry_points.txt +3 -0
- roboswag/__init__.py +0 -9
- roboswag/__main__.py +0 -3
- roboswag/auth.py +0 -44
- roboswag/cli.py +0 -80
- roboswag/core.py +0 -85
- roboswag/generate/__init__.py +0 -1
- roboswag/generate/generate.py +0 -121
- roboswag/generate/models/__init__.py +0 -0
- roboswag/generate/models/api.py +0 -219
- roboswag/generate/models/definition.py +0 -28
- roboswag/generate/models/endpoint.py +0 -68
- roboswag/generate/models/parameter.py +0 -25
- roboswag/generate/models/response.py +0 -8
- roboswag/generate/models/tag.py +0 -16
- roboswag/generate/models/utils.py +0 -60
- roboswag/generate/templates/api_init.jinja +0 -15
- roboswag/generate/templates/models.jinja +0 -7
- roboswag/generate/templates/paths.jinja +0 -68
- roboswag/logger.py +0 -33
- roboswag/validate/__init__.py +0 -6
- roboswag/validate/core.py +0 -3
- roboswag/validate/schema.py +0 -21
- roboswag/validate/text_response.py +0 -14
- robotframework_openapitools-0.3.0.dist-info/METADATA +0 -41
- robotframework_openapitools-0.3.0.dist-info/RECORD +0 -41
- {robotframework_openapitools-0.3.0.dist-info → robotframework_openapitools-1.0.0.dist-info}/LICENSE +0 -0
@@ -1,603 +1,104 @@
|
|
1
|
-
"""
|
2
|
-
# OpenApiLibCore for Robot Framework
|
3
|
-
|
4
|
-
The OpenApiLibCore library is a utility library that is meant to simplify creation
|
5
|
-
of other Robot Framework libraries for API testing based on the information in
|
6
|
-
an OpenAPI document (also known as Swagger document).
|
7
|
-
This document explains how to use the OpenApiLibCore library.
|
8
|
-
|
9
|
-
My RoboCon 2022 talk about OpenApiDriver and OpenApiLibCore can be found
|
10
|
-
[here](https://www.youtube.com/watch?v=7YWZEHxk9Ps)
|
11
|
-
|
12
|
-
For more information about Robot Framework, see http://robotframework.org.
|
13
|
-
|
14
|
-
---
|
15
|
-
|
16
|
-
> Note: OpenApiLibCore is still being developed so there are currently
|
17
|
-
restrictions / limitations that you may encounter when using this library to run
|
18
|
-
tests against an API. See [Limitations](#limitations) for details.
|
19
|
-
|
20
|
-
---
|
21
|
-
|
22
|
-
## Installation
|
23
|
-
|
24
|
-
If you already have Python >= 3.8 with pip installed, you can simply run:
|
25
|
-
|
26
|
-
`pip install --upgrade robotframework-openapi-libcore`
|
27
|
-
|
28
|
-
---
|
29
|
-
|
30
|
-
## OpenAPI (aka Swagger)
|
31
|
-
|
32
|
-
The OpenAPI Specification (OAS) defines a standard, language-agnostic interface
|
33
|
-
to RESTful APIs, see https://swagger.io/specification/
|
34
|
-
|
35
|
-
The OpenApiLibCore implements a number of Robot Framework keywords that make it
|
36
|
-
easy to interact with an OpenAPI implementation by using the information in the
|
37
|
-
openapi document (Swagger file), for examply by automatic generation of valid values
|
38
|
-
for requests based on the schema information in the document.
|
39
|
-
|
40
|
-
> Note: OpenApiLibCore is designed for APIs based on the OAS v3
|
41
|
-
The library has not been tested for APIs based on the OAS v2.
|
42
|
-
|
43
|
-
---
|
44
|
-
|
45
|
-
## Getting started
|
46
|
-
|
47
|
-
Before trying to use the keywords exposed by OpenApiLibCore on the target API
|
48
|
-
it's recommended to first ensure that the openapi document for the API is valid
|
49
|
-
under the OpenAPI Specification.
|
50
|
-
|
51
|
-
This can be done using the command line interface of a package that is installed as
|
52
|
-
a prerequisite for OpenApiLibCore.
|
53
|
-
Both a local openapi.json or openapi.yaml file or one hosted by the API server
|
54
|
-
can be checked using the `prance validate <reference_to_file>` shell command:
|
55
|
-
|
56
|
-
```shell
|
57
|
-
prance validate --backend=openapi-spec-validator http://localhost:8000/openapi.json
|
58
|
-
Processing "http://localhost:8000/openapi.json"...
|
59
|
-
-> Resolving external references.
|
60
|
-
Validates OK as OpenAPI 3.0.2!
|
61
|
-
|
62
|
-
prance validate --backend=openapi-spec-validator /tests/files/petstore_openapi.yaml
|
63
|
-
Processing "/tests/files/petstore_openapi.yaml"...
|
64
|
-
-> Resolving external references.
|
65
|
-
Validates OK as OpenAPI 3.0.2!
|
66
|
-
```
|
67
|
-
|
68
|
-
You'll have to change the url or file reference to the location of the openapi
|
69
|
-
document for your API.
|
70
|
-
|
71
|
-
> Note: Although recursion is technically allowed under the OAS, tool support is limited
|
72
|
-
and changing the OAS to not use recursion is recommended.
|
73
|
-
OpenApiLibCore has limited support for parsing OpenAPI documents with
|
74
|
-
recursion in them. See the `recursion_limit` and `recursion_default` parameters.
|
75
|
-
|
76
|
-
If the openapi document passes this validation, the next step is trying to do a test
|
77
|
-
run with a minimal test suite.
|
78
|
-
The example below can be used, with `source`, `origin` and 'endpoint' altered to
|
79
|
-
fit your situation.
|
80
|
-
|
81
|
-
``` robotframework
|
82
|
-
*** Settings ***
|
83
|
-
Library OpenApiLibCore
|
84
|
-
... source=http://localhost:8000/openapi.json
|
85
|
-
... origin=http://localhost:8000
|
86
|
-
|
87
|
-
*** Test Cases ***
|
88
|
-
Getting Started
|
89
|
-
${url}= Get Valid Url endpoint=/employees/{employee_id} method=get
|
90
|
-
|
91
|
-
```
|
92
|
-
|
93
|
-
Running the above suite for the first time may result in an error / failed test.
|
94
|
-
You should look at the Robot Framework `log.html` to determine the reasons
|
95
|
-
for the failing tests.
|
96
|
-
Depending on the reasons for the failures, different solutions are possible.
|
97
|
-
|
98
|
-
Details about the OpenApiLibCore library parameters and keywords that you may need can be found
|
99
|
-
[here](https://marketsquare.github.io/robotframework-openapi-libcore/openapi_libcore.html).
|
100
|
-
|
101
|
-
The OpenApiLibCore also support handling of relations between resources within the scope
|
102
|
-
of the API being validated as well as handling dependencies on resources outside the
|
103
|
-
scope of the API. In addition there is support for handling restrictions on the values
|
104
|
-
of parameters and properties.
|
105
|
-
|
106
|
-
Details about the `mappings_path` variable usage can be found
|
107
|
-
[here](https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html).
|
108
|
-
|
109
|
-
---
|
110
|
-
|
111
|
-
## Limitations
|
112
|
-
|
113
|
-
There are currently a number of limitations to supported API structures, supported
|
114
|
-
data types and properties. The following list details the most important ones:
|
115
|
-
- Only JSON request and response bodies are supported.
|
116
|
-
- No support for per-endpoint authorization levels.
|
117
|
-
- Parsing of OAS 3.1 documents is supported by the parsing tools, but runtime behavior is untested.
|
118
|
-
|
119
|
-
"""
|
120
|
-
|
121
1
|
import json as _json
|
122
|
-
import re
|
123
2
|
import sys
|
3
|
+
from collections.abc import Mapping, MutableMapping
|
124
4
|
from copy import deepcopy
|
125
|
-
from dataclasses import Field, dataclass, field, make_dataclass
|
126
|
-
from enum import Enum
|
127
5
|
from functools import cached_property
|
128
|
-
from itertools import zip_longest
|
129
|
-
from logging import getLogger
|
130
6
|
from pathlib import Path
|
131
|
-
from
|
132
|
-
from typing import
|
133
|
-
Any,
|
134
|
-
Callable,
|
135
|
-
Dict,
|
136
|
-
Generator,
|
137
|
-
List,
|
138
|
-
Optional,
|
139
|
-
Set,
|
140
|
-
Tuple,
|
141
|
-
Type,
|
142
|
-
Union,
|
143
|
-
)
|
144
|
-
from uuid import uuid4
|
7
|
+
from types import MappingProxyType
|
8
|
+
from typing import Any, Generator
|
145
9
|
|
146
10
|
from openapi_core import Config, OpenAPI, Spec
|
147
|
-
from openapi_core.contrib.requests import (
|
148
|
-
RequestsOpenAPIRequest,
|
149
|
-
RequestsOpenAPIResponse,
|
150
|
-
)
|
151
|
-
from openapi_core.exceptions import OpenAPIError
|
152
|
-
from openapi_core.templating.paths.exceptions import ServerNotFound
|
153
11
|
from openapi_core.validation.exceptions import ValidationError
|
154
|
-
from openapi_core.validation.response.exceptions import ResponseValidationError
|
155
|
-
from openapi_core.validation.schemas.exceptions import InvalidSchemaValue
|
156
12
|
from prance import ResolvingParser
|
157
13
|
from prance.util.url import ResolutionError
|
158
14
|
from requests import Response, Session
|
159
15
|
from requests.auth import AuthBase, HTTPBasicAuth
|
160
16
|
from requests.cookies import RequestsCookieJar as CookieJar
|
17
|
+
from robot.api import logger
|
161
18
|
from robot.api.deco import keyword, library
|
162
|
-
from robot.api.exceptions import
|
19
|
+
from robot.api.exceptions import FatalError
|
163
20
|
from robot.libraries.BuiltIn import BuiltIn
|
164
21
|
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
Relation,
|
174
|
-
UniquePropertyValueConstraint,
|
175
|
-
resolve_schema,
|
176
|
-
)
|
22
|
+
import OpenApiLibCore.data_generation as _data_generation
|
23
|
+
import OpenApiLibCore.data_invalidation as _data_invalidation
|
24
|
+
import OpenApiLibCore.path_functions as _path_functions
|
25
|
+
import OpenApiLibCore.path_invalidation as _path_invalidation
|
26
|
+
import OpenApiLibCore.resource_relations as _resource_relations
|
27
|
+
import OpenApiLibCore.validation as _validation
|
28
|
+
from OpenApiLibCore.annotations import JSON
|
29
|
+
from OpenApiLibCore.dto_base import Dto, IdReference
|
177
30
|
from OpenApiLibCore.dto_utils import (
|
178
31
|
DEFAULT_ID_PROPERTY_NAME,
|
179
|
-
DefaultDto,
|
180
32
|
get_dto_class,
|
181
33
|
get_id_property_name,
|
34
|
+
get_path_dto_class,
|
35
|
+
)
|
36
|
+
from OpenApiLibCore.localized_faker import FAKE
|
37
|
+
from OpenApiLibCore.models import (
|
38
|
+
OpenApiObject,
|
39
|
+
PathItemObject,
|
40
|
+
)
|
41
|
+
from OpenApiLibCore.oas_cache import PARSER_CACHE, CachedParser
|
42
|
+
from OpenApiLibCore.parameter_utils import (
|
43
|
+
get_oas_name_from_safe_name,
|
44
|
+
register_path_parameters,
|
45
|
+
)
|
46
|
+
from OpenApiLibCore.protocols import ResponseValidatorType
|
47
|
+
from OpenApiLibCore.request_data import RequestData, RequestValues
|
48
|
+
from openapitools_docs.docstrings import (
|
49
|
+
OPENAPILIBCORE_INIT_DOCSTRING,
|
50
|
+
OPENAPILIBCORE_LIBRARY_DOCSTRING,
|
182
51
|
)
|
183
|
-
from OpenApiLibCore.oas_cache import PARSER_CACHE
|
184
|
-
from OpenApiLibCore.value_utils import FAKE, IGNORE, JSON
|
185
52
|
|
186
53
|
run_keyword = BuiltIn().run_keyword
|
54
|
+
default_str_mapping: Mapping[str, str] = MappingProxyType({})
|
55
|
+
default_json_mapping: Mapping[str, JSON] = MappingProxyType({})
|
187
56
|
|
188
|
-
logger = getLogger(__name__)
|
189
|
-
|
190
|
-
|
191
|
-
class ValidationLevel(str, Enum):
|
192
|
-
"""The available levels for the response_validation parameter."""
|
193
|
-
|
194
|
-
DISABLED = "DISABLED"
|
195
|
-
INFO = "INFO"
|
196
|
-
WARN = "WARN"
|
197
|
-
STRICT = "STRICT"
|
198
|
-
|
199
|
-
|
200
|
-
def get_safe_key(key: str) -> str:
|
201
|
-
"""
|
202
|
-
Helper function to convert a valid JSON property name to a string that can be used
|
203
|
-
as a Python variable or function / method name.
|
204
|
-
"""
|
205
|
-
key = key.replace("-", "_")
|
206
|
-
key = key.replace("@", "_")
|
207
|
-
if key[0].isdigit():
|
208
|
-
key = f"_{key}"
|
209
|
-
return key
|
210
|
-
|
211
|
-
|
212
|
-
@dataclass
|
213
|
-
class RequestValues:
|
214
|
-
"""Helper class to hold parameter values needed to make a request."""
|
215
|
-
|
216
|
-
url: str
|
217
|
-
method: str
|
218
|
-
params: Optional[Dict[str, Any]]
|
219
|
-
headers: Optional[Dict[str, str]]
|
220
|
-
json_data: Optional[Dict[str, Any]]
|
221
|
-
|
222
|
-
|
223
|
-
@dataclass
|
224
|
-
class RequestData:
|
225
|
-
"""Helper class to manage parameters used when making requests."""
|
226
|
-
|
227
|
-
dto: Union[Dto, DefaultDto] = field(default_factory=DefaultDto)
|
228
|
-
dto_schema: Dict[str, Any] = field(default_factory=dict)
|
229
|
-
parameters: List[Dict[str, Any]] = field(default_factory=list)
|
230
|
-
params: Dict[str, Any] = field(default_factory=dict)
|
231
|
-
headers: Dict[str, Any] = field(default_factory=dict)
|
232
|
-
has_body: bool = True
|
233
|
-
|
234
|
-
def __post_init__(self) -> None:
|
235
|
-
# prevent modification by reference
|
236
|
-
self.dto_schema = deepcopy(self.dto_schema)
|
237
|
-
self.parameters = deepcopy(self.parameters)
|
238
|
-
self.params = deepcopy(self.params)
|
239
|
-
self.headers = deepcopy(self.headers)
|
240
|
-
|
241
|
-
@property
|
242
|
-
def has_optional_properties(self) -> bool:
|
243
|
-
"""Whether or not the dto data (json data) contains optional properties."""
|
244
|
-
|
245
|
-
def is_required_property(property_name: str) -> bool:
|
246
|
-
return property_name in self.dto_schema.get("required", [])
|
247
|
-
|
248
|
-
properties = (self.dto.as_dict()).keys()
|
249
|
-
return not all(map(is_required_property, properties))
|
250
|
-
|
251
|
-
@property
|
252
|
-
def has_optional_params(self) -> bool:
|
253
|
-
"""Whether or not any of the query parameters are optional."""
|
254
|
-
|
255
|
-
def is_optional_param(query_param: str) -> bool:
|
256
|
-
optional_params = [
|
257
|
-
p.get("name")
|
258
|
-
for p in self.parameters
|
259
|
-
if p.get("in") == "query" and not p.get("required")
|
260
|
-
]
|
261
|
-
return query_param in optional_params
|
262
|
-
|
263
|
-
return any(map(is_optional_param, self.params))
|
264
|
-
|
265
|
-
@cached_property
|
266
|
-
def params_that_can_be_invalidated(self) -> Set[str]:
|
267
|
-
"""
|
268
|
-
The query parameters that can be invalidated by violating data
|
269
|
-
restrictions, data type or by not providing them in a request.
|
270
|
-
"""
|
271
|
-
result = set()
|
272
|
-
params = [h for h in self.parameters if h.get("in") == "query"]
|
273
|
-
for param in params:
|
274
|
-
# required params can be omitted to invalidate a request
|
275
|
-
if param["required"]:
|
276
|
-
result.add(param["name"])
|
277
|
-
continue
|
278
|
-
|
279
|
-
schema = resolve_schema(param["schema"])
|
280
|
-
if schema.get("type", None):
|
281
|
-
param_types = [schema]
|
282
|
-
else:
|
283
|
-
param_types = schema["types"]
|
284
|
-
for param_type in param_types:
|
285
|
-
# any basic non-string type except "null" can be invalidated by
|
286
|
-
# replacing it with a string
|
287
|
-
if param_type["type"] not in ["string", "array", "object", "null"]:
|
288
|
-
result.add(param["name"])
|
289
|
-
continue
|
290
|
-
# enums, strings and arrays with boundaries can be invalidated
|
291
|
-
if set(param_type.keys()).intersection(
|
292
|
-
{
|
293
|
-
"enum",
|
294
|
-
"minLength",
|
295
|
-
"maxLength",
|
296
|
-
"minItems",
|
297
|
-
"maxItems",
|
298
|
-
}
|
299
|
-
):
|
300
|
-
result.add(param["name"])
|
301
|
-
continue
|
302
|
-
# an array of basic non-string type can be invalidated by replacing the
|
303
|
-
# items in the array with strings
|
304
|
-
if param_type["type"] == "array" and param_type["items"][
|
305
|
-
"type"
|
306
|
-
] not in [
|
307
|
-
"string",
|
308
|
-
"array",
|
309
|
-
"object",
|
310
|
-
"null",
|
311
|
-
]:
|
312
|
-
result.add(param["name"])
|
313
|
-
return result
|
314
|
-
|
315
|
-
@property
|
316
|
-
def has_optional_headers(self) -> bool:
|
317
|
-
"""Whether or not any of the headers are optional."""
|
318
|
-
|
319
|
-
def is_optional_header(header: str) -> bool:
|
320
|
-
optional_headers = [
|
321
|
-
p.get("name")
|
322
|
-
for p in self.parameters
|
323
|
-
if p.get("in") == "header" and not p.get("required")
|
324
|
-
]
|
325
|
-
return header in optional_headers
|
326
|
-
|
327
|
-
return any(map(is_optional_header, self.headers))
|
328
|
-
|
329
|
-
@cached_property
|
330
|
-
def headers_that_can_be_invalidated(self) -> Set[str]:
|
331
|
-
"""
|
332
|
-
The header parameters that can be invalidated by violating data
|
333
|
-
restrictions or by not providing them in a request.
|
334
|
-
"""
|
335
|
-
result = set()
|
336
|
-
headers = [h for h in self.parameters if h.get("in") == "header"]
|
337
|
-
for header in headers:
|
338
|
-
# required headers can be omitted to invalidate a request
|
339
|
-
if header["required"]:
|
340
|
-
result.add(header["name"])
|
341
|
-
continue
|
342
|
-
|
343
|
-
schema = resolve_schema(header["schema"])
|
344
|
-
if schema.get("type", None):
|
345
|
-
header_types = [schema]
|
346
|
-
else:
|
347
|
-
header_types = schema["types"]
|
348
|
-
for header_type in header_types:
|
349
|
-
# any basic non-string type except "null" can be invalidated by
|
350
|
-
# replacing it with a string
|
351
|
-
if header_type["type"] not in ["string", "array", "object", "null"]:
|
352
|
-
result.add(header["name"])
|
353
|
-
continue
|
354
|
-
# enums, strings and arrays with boundaries can be invalidated
|
355
|
-
if set(header_type.keys()).intersection(
|
356
|
-
{
|
357
|
-
"enum",
|
358
|
-
"minLength",
|
359
|
-
"maxLength",
|
360
|
-
"minItems",
|
361
|
-
"maxItems",
|
362
|
-
}
|
363
|
-
):
|
364
|
-
result.add(header["name"])
|
365
|
-
continue
|
366
|
-
# an array of basic non-string type can be invalidated by replacing the
|
367
|
-
# items in the array with strings
|
368
|
-
if header_type["type"] == "array" and header_type["items"][
|
369
|
-
"type"
|
370
|
-
] not in [
|
371
|
-
"string",
|
372
|
-
"array",
|
373
|
-
"object",
|
374
|
-
"null",
|
375
|
-
]:
|
376
|
-
result.add(header["name"])
|
377
|
-
return result
|
378
|
-
|
379
|
-
def get_required_properties_dict(self) -> Dict[str, Any]:
|
380
|
-
"""Get the json-compatible dto data containing only the required properties."""
|
381
|
-
required_properties = self.dto_schema.get("required", [])
|
382
|
-
required_properties_dict: Dict[str, Any] = {}
|
383
|
-
for key, value in (self.dto.as_dict()).items():
|
384
|
-
if key in required_properties:
|
385
|
-
required_properties_dict[key] = value
|
386
|
-
return required_properties_dict
|
387
|
-
|
388
|
-
def get_minimal_body_dict(self) -> Dict[str, Any]:
|
389
|
-
required_properties_dict = self.get_required_properties_dict()
|
390
|
-
|
391
|
-
min_properties = self.dto_schema.get("minProperties", 0)
|
392
|
-
number_of_optional_properties_to_add = min_properties - len(
|
393
|
-
required_properties_dict
|
394
|
-
)
|
395
|
-
|
396
|
-
if number_of_optional_properties_to_add < 1:
|
397
|
-
return required_properties_dict
|
398
57
|
|
399
|
-
|
400
|
-
|
401
|
-
|
402
|
-
if k not in required_properties_dict
|
403
|
-
}
|
404
|
-
optional_properties_to_keep = sample(
|
405
|
-
sorted(optional_properties_dict), number_of_optional_properties_to_add
|
406
|
-
)
|
407
|
-
optional_properties_dict = {
|
408
|
-
k: v
|
409
|
-
for k, v in optional_properties_dict.items()
|
410
|
-
if k in optional_properties_to_keep
|
411
|
-
}
|
412
|
-
|
413
|
-
return {**required_properties_dict, **optional_properties_dict}
|
414
|
-
|
415
|
-
def get_required_params(self) -> Dict[str, str]:
|
416
|
-
"""Get the params dict containing only the required query parameters."""
|
417
|
-
required_parameters = [
|
418
|
-
p.get("name") for p in self.parameters if p.get("required")
|
419
|
-
]
|
420
|
-
return {k: v for k, v in self.params.items() if k in required_parameters}
|
421
|
-
|
422
|
-
def get_required_headers(self) -> Dict[str, str]:
|
423
|
-
"""Get the headers dict containing only the required headers."""
|
424
|
-
required_parameters = [
|
425
|
-
p.get("name") for p in self.parameters if p.get("required")
|
426
|
-
]
|
427
|
-
return {k: v for k, v in self.headers.items() if k in required_parameters}
|
428
|
-
|
429
|
-
|
430
|
-
@library(scope="SUITE", doc_format="ROBOT")
|
431
|
-
class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
432
|
-
"""
|
433
|
-
Main class providing the keywords and core logic to interact with an OpenAPI server.
|
434
|
-
|
435
|
-
Visit the [https://github.com/MarketSquare/robotframework-openapi-libcore | library page]
|
436
|
-
for an introduction.
|
437
|
-
"""
|
438
|
-
|
439
|
-
def __init__( # pylint: disable=too-many-arguments, too-many-locals, dangerous-default-value
|
58
|
+
@library(scope="SUITE", doc_format="HTML")
|
59
|
+
class OpenApiLibCore: # pylint: disable=too-many-public-methods
|
60
|
+
def __init__( # noqa: PLR0913, pylint: disable=dangerous-default-value
|
440
61
|
self,
|
441
62
|
source: str,
|
442
63
|
origin: str = "",
|
443
64
|
base_path: str = "",
|
444
|
-
response_validation: ValidationLevel = ValidationLevel.WARN,
|
65
|
+
response_validation: _validation.ValidationLevel = _validation.ValidationLevel.WARN,
|
445
66
|
disable_server_validation: bool = True,
|
446
|
-
mappings_path:
|
67
|
+
mappings_path: str | Path = "",
|
447
68
|
invalid_property_default_response: int = 422,
|
448
69
|
default_id_property_name: str = "id",
|
449
|
-
faker_locale:
|
70
|
+
faker_locale: str | list[str] = "",
|
450
71
|
require_body_for_invalid_url: bool = False,
|
451
72
|
recursion_limit: int = 1,
|
452
|
-
recursion_default:
|
73
|
+
recursion_default: JSON = {},
|
453
74
|
username: str = "",
|
454
75
|
password: str = "",
|
455
76
|
security_token: str = "",
|
456
|
-
auth:
|
457
|
-
cert:
|
458
|
-
verify_tls:
|
459
|
-
extra_headers:
|
460
|
-
cookies:
|
461
|
-
proxies:
|
77
|
+
auth: AuthBase | None = None,
|
78
|
+
cert: str | tuple[str, str] = "",
|
79
|
+
verify_tls: bool | str = True,
|
80
|
+
extra_headers: Mapping[str, str] = default_str_mapping,
|
81
|
+
cookies: MutableMapping[str, str] | CookieJar | None = None,
|
82
|
+
proxies: MutableMapping[str, str] | None = None,
|
462
83
|
) -> None:
|
463
|
-
"""
|
464
|
-
== Base parameters ==
|
465
|
-
|
466
|
-
=== source ===
|
467
|
-
An absolute path to an openapi.json or openapi.yaml file or an url to such a file.
|
468
|
-
|
469
|
-
=== origin ===
|
470
|
-
The server (and port) of the target server. E.g. ``https://localhost:8000``
|
471
|
-
|
472
|
-
=== base_path ===
|
473
|
-
The routing between ``origin`` and the endpoints as found in the ``paths``
|
474
|
-
section in the openapi document.
|
475
|
-
E.g. ``/petshop/v2``.
|
476
|
-
|
477
|
-
== Test case execution ==
|
478
|
-
|
479
|
-
=== response_validation ===
|
480
|
-
By default, a ``WARN`` is logged when the Response received after a Request does not
|
481
|
-
comply with the schema as defined in the openapi document for the given operation. The
|
482
|
-
following values are supported:
|
483
|
-
|
484
|
-
- ``DISABLED``: All Response validation errors will be ignored
|
485
|
-
- ``INFO``: Any Response validation erros will be logged at ``INFO`` level
|
486
|
-
- ``WARN``: Any Response validation erros will be logged at ``WARN`` level
|
487
|
-
- ``STRICT``: The Test Case will fail on any Response validation errors
|
488
|
-
|
489
|
-
=== disable_server_validation ===
|
490
|
-
If enabled by setting this parameter to ``True``, the Response validation will also
|
491
|
-
include possible errors for Requests made to a server address that is not defined in
|
492
|
-
the list of servers in the openapi document. This generally means that if there is a
|
493
|
-
mismatch, every Test Case will raise this error. Note that ``localhost`` and
|
494
|
-
``127.0.0.1`` are not considered the same by Response validation.
|
495
|
-
|
496
|
-
== API-specific configurations ==
|
497
|
-
|
498
|
-
=== mappings_path ===
|
499
|
-
See [https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html | this page]
|
500
|
-
for an in-depth explanation.
|
501
|
-
|
502
|
-
=== invalid_property_default_response ===
|
503
|
-
The default response code for requests with a JSON body that does not comply
|
504
|
-
with the schema.
|
505
|
-
Example: a value outside the specified range or a string value
|
506
|
-
for a property defined as integer in the schema.
|
507
|
-
|
508
|
-
=== default_id_property_name ===
|
509
|
-
The default name for the property that identifies a resource (i.e. a unique
|
510
|
-
entity) within the API.
|
511
|
-
The default value for this property name is ``id``.
|
512
|
-
If the target API uses a different name for all the resources within the API,
|
513
|
-
you can configure it globally using this property.
|
514
|
-
|
515
|
-
If different property names are used for the unique identifier for different
|
516
|
-
types of resources, an ``ID_MAPPING`` can be implemented using the ``mappings_path``.
|
517
|
-
|
518
|
-
=== faker_locale ===
|
519
|
-
A locale string or list of locale strings to pass to the Faker library to be
|
520
|
-
used in generation of string data for supported format types.
|
521
|
-
|
522
|
-
=== require_body_for_invalid_url ===
|
523
|
-
When a request is made against an invalid url, this usually is because of a "404" request;
|
524
|
-
a request for a resource that does not exist. Depending on API implementation, when a
|
525
|
-
request with a missing or invalid request body is made on a non-existent resource,
|
526
|
-
either a 404 or a 422 or 400 Response is normally returned. If the API being tested
|
527
|
-
processes the request body before checking if the requested resource exists, set
|
528
|
-
this parameter to True.
|
529
|
-
|
530
|
-
== Parsing parameters ==
|
531
|
-
|
532
|
-
=== recursion_limit ===
|
533
|
-
The recursion depth to which to fully parse recursive references before the
|
534
|
-
`recursion_default` is used to end the recursion.
|
535
|
-
|
536
|
-
=== recursion_default ===
|
537
|
-
The value that is used instead of the referenced schema when the
|
538
|
-
`recursion_limit` has been reached.
|
539
|
-
The default `{}` represents an empty object in JSON.
|
540
|
-
Depending on schema definitions, this may cause schema validation errors.
|
541
|
-
If this is the case, 'None' (``${NONE}`` in Robot Framework) or an empty list
|
542
|
-
can be tried as an alternative.
|
543
|
-
|
544
|
-
== Security-related parameters ==
|
545
|
-
_Note: these parameters are equivalent to those in the ``requests`` library._
|
546
|
-
|
547
|
-
=== username ===
|
548
|
-
The username to be used for Basic Authentication.
|
549
|
-
|
550
|
-
=== password ===
|
551
|
-
The password to be used for Basic Authentication.
|
552
|
-
|
553
|
-
=== security_token ===
|
554
|
-
The token to be used for token based security using the ``Authorization`` header.
|
555
|
-
|
556
|
-
=== auth ===
|
557
|
-
A [https://requests.readthedocs.io/en/latest/api/#authentication | requests ``AuthBase`` instance]
|
558
|
-
to be used for authentication instead of the ``username`` and ``password``.
|
559
|
-
|
560
|
-
=== cert ===
|
561
|
-
The SSL certificate to use with all requests.
|
562
|
-
If string: the path to ssl client cert file (.pem).
|
563
|
-
If tuple: the ('cert', 'key') pair.
|
564
|
-
|
565
|
-
=== verify_tls ===
|
566
|
-
Whether or not to verify the TLS / SSL certificate of the server.
|
567
|
-
If boolean: whether or not to verify the server TLS certificate.
|
568
|
-
If string: path to a CA bundle to use for verification.
|
569
|
-
|
570
|
-
=== extra_headers ===
|
571
|
-
A dictionary with extra / custom headers that will be send with every request.
|
572
|
-
This parameter can be used to send headers that are not documented in the
|
573
|
-
openapi document or to provide an API-key.
|
574
|
-
|
575
|
-
=== cookies ===
|
576
|
-
A dictionary or
|
577
|
-
[https://docs.python.org/3/library/http.cookiejar.html#http.cookiejar.CookieJar | CookieJar object]
|
578
|
-
to send with all requests.
|
579
|
-
|
580
|
-
=== proxies ===
|
581
|
-
A dictionary of 'protocol': 'proxy url' to use for all requests.
|
582
|
-
"""
|
583
84
|
self._source = source
|
584
85
|
self._origin = origin
|
585
86
|
self._base_path = base_path
|
586
87
|
self.response_validation = response_validation
|
587
88
|
self.disable_server_validation = disable_server_validation
|
588
89
|
self._recursion_limit = recursion_limit
|
589
|
-
self._recursion_default = recursion_default
|
90
|
+
self._recursion_default = deepcopy(recursion_default)
|
590
91
|
self.session = Session()
|
591
|
-
#
|
92
|
+
# Only username and password, security_token or auth object should be provided
|
592
93
|
# if multiple are provided, username and password take precedence
|
593
94
|
self.security_token = security_token
|
594
95
|
self.auth = auth
|
595
96
|
if username:
|
596
97
|
self.auth = HTTPBasicAuth(username, password)
|
597
|
-
#
|
598
|
-
#
|
599
|
-
if isinstance(cert,
|
600
|
-
cert =
|
98
|
+
# Requests only allows a string or a tuple[str, str], so ensure cert is a tuple
|
99
|
+
# if the passed argument is not a string.
|
100
|
+
if not isinstance(cert, str):
|
101
|
+
cert = (cert[0], cert[1])
|
601
102
|
self.cert = cert
|
602
103
|
self.verify = verify_tls
|
603
104
|
self.extra_headers = extra_headers
|
@@ -607,23 +108,27 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
607
108
|
if mappings_path and str(mappings_path) != ".":
|
608
109
|
mappings_path = Path(mappings_path)
|
609
110
|
if not mappings_path.is_file():
|
610
|
-
logger.
|
611
|
-
|
612
|
-
|
613
|
-
# intermediate variable to ensure path.append is possible so we'll never
|
614
|
-
# path.pop a location that we didn't append
|
111
|
+
logger.warn(f"mappings_path '{mappings_path}' is not a Python module.")
|
112
|
+
# Intermediate variable to ensure path.append is possible so we'll never
|
113
|
+
# path.pop a location that we didn't append.
|
615
114
|
mappings_folder = str(mappings_path.parent)
|
616
115
|
sys.path.append(mappings_folder)
|
617
116
|
mappings_module_name = mappings_path.stem
|
618
117
|
self.get_dto_class = get_dto_class(
|
619
118
|
mappings_module_name=mappings_module_name
|
620
119
|
)
|
120
|
+
self.get_path_dto_class = get_path_dto_class(
|
121
|
+
mappings_module_name=mappings_module_name
|
122
|
+
)
|
621
123
|
self.get_id_property_name = get_id_property_name(
|
622
124
|
mappings_module_name=mappings_module_name
|
623
125
|
)
|
624
126
|
sys.path.pop()
|
625
127
|
else:
|
626
128
|
self.get_dto_class = get_dto_class(mappings_module_name="no mapping")
|
129
|
+
self.get_path_dto_class = get_path_dto_class(
|
130
|
+
mappings_module_name="no mapping"
|
131
|
+
)
|
627
132
|
self.get_id_property_name = get_id_property_name(
|
628
133
|
mappings_module_name="no mapping"
|
629
134
|
)
|
@@ -634,10 +139,7 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
634
139
|
DEFAULT_ID_PROPERTY_NAME.id_property_name = default_id_property_name
|
635
140
|
self._server_validation_warning_logged = False
|
636
141
|
|
637
|
-
|
638
|
-
def origin(self) -> str:
|
639
|
-
return self._origin
|
640
|
-
|
142
|
+
# region: library configuration keywords
|
641
143
|
@keyword
|
642
144
|
def set_origin(self, origin: str) -> None:
|
643
145
|
"""
|
@@ -684,7 +186,7 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
684
186
|
self.auth = auth
|
685
187
|
|
686
188
|
@keyword
|
687
|
-
def set_extra_headers(self, extra_headers:
|
189
|
+
def set_extra_headers(self, extra_headers: dict[str, str]) -> None:
|
688
190
|
"""
|
689
191
|
Set the `extra_headers` used in requests after the library is imported.
|
690
192
|
|
@@ -693,681 +195,68 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
693
195
|
"""
|
694
196
|
self.extra_headers = extra_headers
|
695
197
|
|
696
|
-
|
697
|
-
|
698
|
-
return f"{self.origin}{self._base_path}"
|
699
|
-
|
700
|
-
@cached_property
|
701
|
-
def validation_spec(self) -> Spec:
|
702
|
-
_, validation_spec, _ = self._load_specs_and_validator()
|
703
|
-
return validation_spec
|
704
|
-
|
705
|
-
@property
|
706
|
-
def openapi_spec(self) -> Dict[str, Any]:
|
707
|
-
"""Return a deepcopy of the parsed openapi document."""
|
708
|
-
# protect the parsed openapi spec from being mutated by reference
|
709
|
-
return deepcopy(self._openapi_spec)
|
710
|
-
|
711
|
-
@cached_property
|
712
|
-
def _openapi_spec(self) -> Dict[str, Any]:
|
713
|
-
parser, _, _ = self._load_specs_and_validator()
|
714
|
-
return parser.specification
|
715
|
-
|
716
|
-
@cached_property
|
717
|
-
def response_validator(
|
718
|
-
self,
|
719
|
-
) -> Callable[[RequestsOpenAPIRequest, RequestsOpenAPIResponse], None]:
|
720
|
-
_, _, response_validator = self._load_specs_and_validator()
|
721
|
-
return response_validator
|
722
|
-
|
723
|
-
def _get_json_types_from_spec(self, spec: Dict[str, Any]) -> Set[str]:
|
724
|
-
json_types: Set[str] = set(self._get_json_types(spec))
|
725
|
-
return {json_type for json_type in json_types if json_type is not None}
|
726
|
-
|
727
|
-
def _get_json_types(self, item: Any) -> Generator[str, None, None]:
|
728
|
-
if isinstance(item, dict):
|
729
|
-
content_dict = item.get("content")
|
730
|
-
if content_dict is None:
|
731
|
-
for value in item.values():
|
732
|
-
yield from self._get_json_types(value)
|
733
|
-
|
734
|
-
else:
|
735
|
-
for content_type in content_dict:
|
736
|
-
if "json" in content_type:
|
737
|
-
content_type_without_charset, _, _ = content_type.partition(";")
|
738
|
-
yield content_type_without_charset
|
739
|
-
|
740
|
-
if isinstance(item, list):
|
741
|
-
for list_item in item:
|
742
|
-
yield from self._get_json_types(list_item)
|
743
|
-
|
744
|
-
def _load_specs_and_validator(
|
745
|
-
self,
|
746
|
-
) -> Tuple[
|
747
|
-
ResolvingParser,
|
748
|
-
Spec,
|
749
|
-
Callable[[RequestsOpenAPIRequest, RequestsOpenAPIResponse], None],
|
750
|
-
]:
|
751
|
-
try:
|
752
|
-
|
753
|
-
def recursion_limit_handler(
|
754
|
-
limit: int, refstring: str, recursions: Any
|
755
|
-
) -> Any:
|
756
|
-
return self._recursion_default
|
757
|
-
|
758
|
-
# Since parsing of the OAS and creating the Spec can take a long time,
|
759
|
-
# they are cached. This is done by storing them in an imported module that
|
760
|
-
# will have a global scope due to how the Python import system works. This
|
761
|
-
# ensures that in a Suite of Suites where multiple Suites use the same
|
762
|
-
# `source`, that OAS is only parsed / loaded once.
|
763
|
-
parser, validation_spec, response_validator = PARSER_CACHE.get(
|
764
|
-
self._source, (None, None, None)
|
765
|
-
)
|
766
|
-
|
767
|
-
if parser is None:
|
768
|
-
parser = ResolvingParser(
|
769
|
-
self._source,
|
770
|
-
backend="openapi-spec-validator",
|
771
|
-
recursion_limit=self._recursion_limit,
|
772
|
-
recursion_limit_handler=recursion_limit_handler,
|
773
|
-
)
|
774
|
-
|
775
|
-
if parser.specification is None: # pragma: no cover
|
776
|
-
BuiltIn().fatal_error(
|
777
|
-
"Source was loaded, but no specification was present after parsing."
|
778
|
-
)
|
779
|
-
|
780
|
-
validation_spec = Spec.from_dict(parser.specification)
|
781
|
-
|
782
|
-
json_types_from_spec: Set[str] = self._get_json_types_from_spec(
|
783
|
-
parser.specification
|
784
|
-
)
|
785
|
-
extra_deserializers = {
|
786
|
-
json_type: _json.loads for json_type in json_types_from_spec
|
787
|
-
}
|
788
|
-
config = Config(extra_media_type_deserializers=extra_deserializers)
|
789
|
-
openapi = OpenAPI(spec=validation_spec, config=config)
|
790
|
-
response_validator = openapi.validate_response
|
791
|
-
|
792
|
-
PARSER_CACHE[self._source] = (
|
793
|
-
parser,
|
794
|
-
validation_spec,
|
795
|
-
response_validator,
|
796
|
-
)
|
797
|
-
|
798
|
-
return parser, validation_spec, response_validator
|
799
|
-
|
800
|
-
except ResolutionError as exception:
|
801
|
-
BuiltIn().fatal_error(
|
802
|
-
f"ResolutionError while trying to load openapi spec: {exception}"
|
803
|
-
)
|
804
|
-
except ValidationError as exception:
|
805
|
-
BuiltIn().fatal_error(
|
806
|
-
f"ValidationError while trying to load openapi spec: {exception}"
|
807
|
-
)
|
808
|
-
|
809
|
-
def validate_response_vs_spec(
|
810
|
-
self, request: RequestsOpenAPIRequest, response: RequestsOpenAPIResponse
|
811
|
-
) -> None:
|
812
|
-
"""
|
813
|
-
Validate the reponse for a given request against the OpenAPI Spec that is
|
814
|
-
loaded during library initialization.
|
815
|
-
"""
|
816
|
-
self.response_validator(request=request, response=response)
|
817
|
-
|
818
|
-
def read_paths(self) -> Dict[str, Any]:
|
819
|
-
return self.openapi_spec["paths"]
|
820
|
-
|
821
|
-
@keyword
|
822
|
-
def get_valid_url(self, endpoint: str, method: str) -> str:
|
823
|
-
"""
|
824
|
-
This keyword returns a valid url for the given `endpoint` and `method`.
|
825
|
-
|
826
|
-
If the `endpoint` contains path parameters the Get Valid Id For Endpoint
|
827
|
-
keyword will be executed to retrieve valid ids for the path parameters.
|
828
|
-
|
829
|
-
> Note: if valid ids cannot be retrieved within the scope of the API, the
|
830
|
-
`PathPropertiesConstraint` Relation can be used. More information can be found
|
831
|
-
[https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html | here].
|
832
|
-
"""
|
833
|
-
method = method.lower()
|
834
|
-
try:
|
835
|
-
# endpoint can be partially resolved or provided by a PathPropertiesConstraint
|
836
|
-
parametrized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
|
837
|
-
_ = self.openapi_spec["paths"][parametrized_endpoint]
|
838
|
-
except KeyError:
|
839
|
-
raise ValueError(
|
840
|
-
f"{endpoint} not found in paths section of the OpenAPI document."
|
841
|
-
) from None
|
842
|
-
dto_class = self.get_dto_class(endpoint=endpoint, method=method)
|
843
|
-
relations = dto_class.get_relations()
|
844
|
-
paths = [p.path for p in relations if isinstance(p, PathPropertiesConstraint)]
|
845
|
-
if paths:
|
846
|
-
url = f"{self.base_url}{choice(paths)}"
|
847
|
-
return url
|
848
|
-
endpoint_parts = list(endpoint.split("/"))
|
849
|
-
for index, part in enumerate(endpoint_parts):
|
850
|
-
if part.startswith("{") and part.endswith("}"):
|
851
|
-
type_endpoint_parts = endpoint_parts[slice(index)]
|
852
|
-
type_endpoint = "/".join(type_endpoint_parts)
|
853
|
-
existing_id: Union[str, int, float] = run_keyword(
|
854
|
-
"get_valid_id_for_endpoint", type_endpoint, method
|
855
|
-
)
|
856
|
-
endpoint_parts[index] = str(existing_id)
|
857
|
-
resolved_endpoint = "/".join(endpoint_parts)
|
858
|
-
url = f"{self.base_url}{resolved_endpoint}"
|
859
|
-
return url
|
860
|
-
|
198
|
+
# endregion
|
199
|
+
# region: data generation keywords
|
861
200
|
@keyword
|
862
|
-
def
|
863
|
-
self,
|
864
|
-
|
865
|
-
|
866
|
-
|
867
|
-
|
868
|
-
|
869
|
-
|
870
|
-
"""
|
871
|
-
|
872
|
-
def dummy_transformer(
|
873
|
-
valid_id: Union[str, int, float]
|
874
|
-
) -> Union[str, int, float]:
|
875
|
-
return valid_id
|
876
|
-
|
877
|
-
method = method.lower()
|
878
|
-
url: str = run_keyword("get_valid_url", endpoint, method)
|
879
|
-
# Try to create a new resource to prevent conflicts caused by
|
880
|
-
# operations performed on the same resource by other test cases
|
881
|
-
request_data = self.get_request_data(endpoint=endpoint, method="post")
|
882
|
-
|
883
|
-
response: Response = run_keyword(
|
884
|
-
"authorized_request",
|
885
|
-
url,
|
886
|
-
"post",
|
887
|
-
request_data.get_required_params(),
|
888
|
-
request_data.get_required_headers(),
|
889
|
-
request_data.get_required_properties_dict(),
|
890
|
-
)
|
891
|
-
|
892
|
-
# determine the id property name for this path and whether or not a transformer is used
|
893
|
-
mapping = self.get_id_property_name(endpoint=endpoint)
|
894
|
-
if isinstance(mapping, str):
|
895
|
-
id_property = mapping
|
896
|
-
# set the transformer to a dummy callable that returns the original value so
|
897
|
-
# the transformer can be applied on any returned id
|
898
|
-
id_transformer = dummy_transformer
|
899
|
-
else:
|
900
|
-
id_property, id_transformer = mapping
|
901
|
-
|
902
|
-
if not response.ok:
|
903
|
-
# If a new resource cannot be created using POST, try to retrieve a
|
904
|
-
# valid id using a GET request.
|
905
|
-
try:
|
906
|
-
valid_id = choice(run_keyword("get_ids_from_url", url))
|
907
|
-
return id_transformer(valid_id)
|
908
|
-
except Exception as exception:
|
909
|
-
raise AssertionError(
|
910
|
-
f"Failed to get a valid id using GET on {url}"
|
911
|
-
) from exception
|
912
|
-
|
913
|
-
response_data = response.json()
|
914
|
-
if prepared_body := response.request.body:
|
915
|
-
if isinstance(prepared_body, bytes):
|
916
|
-
send_json = _json.loads(prepared_body.decode("UTF-8"))
|
917
|
-
else:
|
918
|
-
send_json = _json.loads(prepared_body)
|
919
|
-
else:
|
920
|
-
send_json = None
|
921
|
-
|
922
|
-
# no support for retrieving an id from an array returned on a POST request
|
923
|
-
if isinstance(response_data, list):
|
924
|
-
raise NotImplementedError(
|
925
|
-
f"Unexpected response body for POST request: expected an object but "
|
926
|
-
f"received an array ({response_data})"
|
927
|
-
)
|
928
|
-
|
929
|
-
# POST on /resource_type/{id}/array_item/ will return the updated {id} resource
|
930
|
-
# instead of a newly created resource. In this case, the send_json must be
|
931
|
-
# in the array of the 'array_item' property on {id}
|
932
|
-
send_path: str = response.request.path_url
|
933
|
-
response_href: Optional[str] = response_data.get("href", None)
|
934
|
-
if response_href and (send_path not in response_href) and send_json:
|
935
|
-
try:
|
936
|
-
property_to_check = send_path.replace(response_href, "")[1:]
|
937
|
-
item_list: List[Dict[str, Any]] = response_data[property_to_check]
|
938
|
-
# Use the (mandatory) id to get the POSTed resource from the list
|
939
|
-
[valid_id] = [
|
940
|
-
item[id_property]
|
941
|
-
for item in item_list
|
942
|
-
if item[id_property] == send_json[id_property]
|
943
|
-
]
|
944
|
-
except Exception as exception:
|
945
|
-
raise AssertionError(
|
946
|
-
f"Failed to get a valid id from {response_href}"
|
947
|
-
) from exception
|
948
|
-
else:
|
949
|
-
try:
|
950
|
-
valid_id = response_data[id_property]
|
951
|
-
except KeyError:
|
952
|
-
raise AssertionError(
|
953
|
-
f"Failed to get a valid id from {response_data}"
|
954
|
-
) from None
|
955
|
-
return id_transformer(valid_id)
|
956
|
-
|
957
|
-
@keyword
|
958
|
-
def get_ids_from_url(self, url: str) -> List[str]:
|
959
|
-
"""
|
960
|
-
Perform a GET request on the `url` and return the list of resource
|
961
|
-
`ids` from the response.
|
962
|
-
"""
|
963
|
-
endpoint = self.get_parameterized_endpoint_from_url(url)
|
964
|
-
request_data = self.get_request_data(endpoint=endpoint, method="get")
|
965
|
-
response = run_keyword(
|
966
|
-
"authorized_request",
|
967
|
-
url,
|
968
|
-
"get",
|
969
|
-
request_data.get_required_params(),
|
970
|
-
request_data.get_required_headers(),
|
971
|
-
)
|
972
|
-
response.raise_for_status()
|
973
|
-
response_data: Union[Dict[str, Any], List[Dict[str, Any]]] = response.json()
|
974
|
-
|
975
|
-
# determine the property name to use
|
976
|
-
mapping = self.get_id_property_name(endpoint=endpoint)
|
977
|
-
if isinstance(mapping, str):
|
978
|
-
id_property = mapping
|
979
|
-
else:
|
980
|
-
id_property, _ = mapping
|
981
|
-
|
982
|
-
if isinstance(response_data, list):
|
983
|
-
valid_ids: List[str] = [item[id_property] for item in response_data]
|
984
|
-
return valid_ids
|
985
|
-
# if the response is an object (dict), check if it's hal+json
|
986
|
-
if embedded := response_data.get("_embedded"):
|
987
|
-
# there should be 1 item in the dict that has a value that's a list
|
988
|
-
for value in embedded.values():
|
989
|
-
if isinstance(value, list):
|
990
|
-
valid_ids = [item[id_property] for item in value]
|
991
|
-
return valid_ids
|
992
|
-
if (valid_id := response_data.get(id_property)) is not None:
|
993
|
-
return [valid_id]
|
994
|
-
valid_ids = [item[id_property] for item in response_data["items"]]
|
995
|
-
return valid_ids
|
201
|
+
def get_request_values(
|
202
|
+
self,
|
203
|
+
path: str,
|
204
|
+
method: str,
|
205
|
+
overrides: Mapping[str, JSON] = default_json_mapping,
|
206
|
+
) -> RequestValues:
|
207
|
+
"""Return an object with all (valid) request values needed to make a request."""
|
208
|
+
json_data: dict[str, JSON] = {}
|
996
209
|
|
997
|
-
|
998
|
-
|
999
|
-
|
1000
|
-
|
1001
|
-
|
1002
|
-
|
1003
|
-
# against the parametrized endpoints in the paths section.
|
1004
|
-
spec_endpoint = self.get_parametrized_endpoint(endpoint)
|
1005
|
-
dto_class = self.get_dto_class(endpoint=spec_endpoint, method=method)
|
1006
|
-
try:
|
1007
|
-
method_spec = self.openapi_spec["paths"][spec_endpoint][method]
|
1008
|
-
except KeyError:
|
1009
|
-
logger.info(
|
1010
|
-
f"method '{method}' not supported on '{spec_endpoint}, using empty spec."
|
1011
|
-
)
|
1012
|
-
method_spec = {}
|
210
|
+
url: str = run_keyword("get_valid_url", path)
|
211
|
+
request_data: RequestData = run_keyword("get_request_data", path, method)
|
212
|
+
params = request_data.params
|
213
|
+
headers = request_data.headers
|
214
|
+
if request_data.has_body:
|
215
|
+
json_data = request_data.dto.as_dict()
|
1013
216
|
|
1014
|
-
|
1015
|
-
|
1016
|
-
|
1017
|
-
if (body_spec := method_spec.get("requestBody", None)) is None:
|
1018
|
-
if dto_class == DefaultDto:
|
1019
|
-
dto_instance: Dto = DefaultDto()
|
1020
|
-
else:
|
1021
|
-
dto_class = make_dataclass(
|
1022
|
-
cls_name=method_spec.get("operationId", dto_cls_name),
|
1023
|
-
fields=[],
|
1024
|
-
bases=(dto_class,),
|
1025
|
-
)
|
1026
|
-
dto_instance = dto_class()
|
1027
|
-
return RequestData(
|
1028
|
-
dto=dto_instance,
|
1029
|
-
parameters=parameters,
|
1030
|
-
params=params,
|
1031
|
-
headers=headers,
|
1032
|
-
has_body=False,
|
1033
|
-
)
|
1034
|
-
content_schema = resolve_schema(self.get_content_schema(body_spec))
|
1035
|
-
headers.update({"content-type": self.get_content_type(body_spec)})
|
1036
|
-
dto_data = self.get_json_data_for_dto_class(
|
1037
|
-
schema=content_schema,
|
1038
|
-
dto_class=dto_class,
|
1039
|
-
operation_id=method_spec.get("operationId", ""),
|
1040
|
-
)
|
1041
|
-
if dto_data is None:
|
1042
|
-
dto_instance = DefaultDto()
|
1043
|
-
else:
|
1044
|
-
fields = self.get_fields_from_dto_data(content_schema, dto_data)
|
1045
|
-
dto_class = make_dataclass(
|
1046
|
-
cls_name=method_spec.get("operationId", dto_cls_name),
|
1047
|
-
fields=fields,
|
1048
|
-
bases=(dto_class,),
|
1049
|
-
)
|
1050
|
-
dto_data = {get_safe_key(key): value for key, value in dto_data.items()}
|
1051
|
-
dto_instance = dto_class(**dto_data)
|
1052
|
-
return RequestData(
|
1053
|
-
dto=dto_instance,
|
1054
|
-
dto_schema=content_schema,
|
1055
|
-
parameters=parameters,
|
217
|
+
request_values = RequestValues(
|
218
|
+
url=url,
|
219
|
+
method=method,
|
1056
220
|
params=params,
|
1057
221
|
headers=headers,
|
222
|
+
json_data=json_data,
|
1058
223
|
)
|
1059
224
|
|
1060
|
-
|
1061
|
-
|
1062
|
-
|
1063
|
-
|
1064
|
-
|
1065
|
-
|
1066
|
-
|
1067
|
-
|
1068
|
-
|
1069
|
-
|
1070
|
-
def get_fields_from_dto_data(
|
1071
|
-
content_schema: Dict[str, Any], dto_data: Dict[str, Any]
|
1072
|
-
):
|
1073
|
-
# FIXME: annotation is not Pyhon 3.8-compatible
|
1074
|
-
# ) -> List[Union[str, Tuple[str, Type[Any]], Tuple[str, Type[Any], Field[Any]]]]:
|
1075
|
-
"""Get a dataclasses fields list based on the content_schema and dto_data."""
|
1076
|
-
fields: List[
|
1077
|
-
Union[str, Tuple[str, Type[Any]], Tuple[str, Type[Any], Field[Any]]]
|
1078
|
-
] = []
|
1079
|
-
for key, value in dto_data.items():
|
1080
|
-
required_properties = content_schema.get("required", [])
|
1081
|
-
safe_key = get_safe_key(key)
|
1082
|
-
metadata = {"original_property_name": key}
|
1083
|
-
if key in required_properties:
|
1084
|
-
# The fields list is used to create a dataclass, so non-default fields
|
1085
|
-
# must go before fields with a default
|
1086
|
-
fields.insert(0, (safe_key, type(value), field(metadata=metadata)))
|
1087
|
-
else:
|
1088
|
-
fields.append((safe_key, type(value), field(default=None, metadata=metadata))) # type: ignore[arg-type]
|
1089
|
-
return fields
|
1090
|
-
|
1091
|
-
def get_request_parameters(
|
1092
|
-
self, dto_class: Union[Dto, Type[Dto]], method_spec: Dict[str, Any]
|
1093
|
-
) -> Tuple[List[Dict[str, Any]], Dict[str, Any], Dict[str, str]]:
|
1094
|
-
"""Get the methods parameter spec and params and headers with valid data."""
|
1095
|
-
parameters = method_spec.get("parameters", [])
|
1096
|
-
parameter_relations = dto_class.get_parameter_relations()
|
1097
|
-
query_params = [p for p in parameters if p.get("in") == "query"]
|
1098
|
-
header_params = [p for p in parameters if p.get("in") == "header"]
|
1099
|
-
params = self.get_parameter_data(query_params, parameter_relations)
|
1100
|
-
headers = self.get_parameter_data(header_params, parameter_relations)
|
1101
|
-
return parameters, params, headers
|
1102
|
-
|
1103
|
-
@classmethod
|
1104
|
-
def get_content_schema(cls, body_spec: Dict[str, Any]) -> Dict[str, Any]:
|
1105
|
-
"""Get the content schema from the requestBody spec."""
|
1106
|
-
content_type = cls.get_content_type(body_spec)
|
1107
|
-
content_schema = body_spec["content"][content_type]["schema"]
|
1108
|
-
return resolve_schema(content_schema)
|
1109
|
-
|
1110
|
-
@staticmethod
|
1111
|
-
def get_content_type(body_spec: Dict[str, Any]) -> str:
|
1112
|
-
"""Get and validate the first supported content type from the requested body spec
|
1113
|
-
|
1114
|
-
Should be application/json like content type,
|
1115
|
-
e.g "application/json;charset=utf-8" or "application/merge-patch+json"
|
1116
|
-
"""
|
1117
|
-
content_types: List[str] = body_spec["content"].keys()
|
1118
|
-
json_regex = r"application/([a-z\-]+\+)?json(;\s?charset=(.+))?"
|
1119
|
-
for content_type in content_types:
|
1120
|
-
if re.search(json_regex, content_type):
|
1121
|
-
return content_type
|
1122
|
-
|
1123
|
-
# At present no supported for other types.
|
1124
|
-
raise NotImplementedError(
|
1125
|
-
f"Only content types like 'application/json' are supported. "
|
1126
|
-
f"Content types definded in the spec are '{content_types}'."
|
1127
|
-
)
|
1128
|
-
|
1129
|
-
def get_parametrized_endpoint(self, endpoint: str) -> str:
|
1130
|
-
"""
|
1131
|
-
Get the parametrized endpoint as found in the `paths` section of the openapi
|
1132
|
-
document from a (partially) resolved endpoint.
|
1133
|
-
"""
|
1134
|
-
|
1135
|
-
def match_parts(parts: List[str], spec_parts: List[str]) -> bool:
|
1136
|
-
for part, spec_part in zip_longest(parts, spec_parts, fillvalue="Filler"):
|
1137
|
-
if part == "Filler" or spec_part == "Filler":
|
1138
|
-
return False
|
1139
|
-
if part != spec_part and not spec_part.startswith("{"):
|
1140
|
-
return False
|
1141
|
-
return True
|
1142
|
-
|
1143
|
-
endpoint_parts = endpoint.split("/")
|
1144
|
-
# if the last part is empty, the path has a trailing `/` that
|
1145
|
-
# should be ignored during matching
|
1146
|
-
if endpoint_parts[-1] == "":
|
1147
|
-
_ = endpoint_parts.pop(-1)
|
1148
|
-
|
1149
|
-
spec_endpoints: List[str] = {**self.openapi_spec}["paths"].keys()
|
1150
|
-
|
1151
|
-
candidates: List[str] = []
|
1152
|
-
|
1153
|
-
for spec_endpoint in spec_endpoints:
|
1154
|
-
spec_endpoint_parts = spec_endpoint.split("/")
|
1155
|
-
# ignore trailing `/` the same way as for endpoint_parts
|
1156
|
-
if spec_endpoint_parts[-1] == "":
|
1157
|
-
_ = spec_endpoint_parts.pop(-1)
|
1158
|
-
if match_parts(endpoint_parts, spec_endpoint_parts):
|
1159
|
-
candidates.append(spec_endpoint)
|
1160
|
-
|
1161
|
-
if not candidates:
|
1162
|
-
raise ValueError(
|
1163
|
-
f"{endpoint} not found in paths section of the OpenAPI document."
|
1164
|
-
)
|
1165
|
-
|
1166
|
-
if len(candidates) == 1:
|
1167
|
-
return candidates[0]
|
1168
|
-
# Multiple matches can happen in APIs with overloaded endpoints, e.g.
|
1169
|
-
# /users/me
|
1170
|
-
# /users/${user_id}
|
1171
|
-
# In this case, find the closest (or exact) match
|
1172
|
-
exact_match = [c for c in candidates if c == endpoint]
|
1173
|
-
if exact_match:
|
1174
|
-
return exact_match[0]
|
1175
|
-
# TODO: Implement a decision mechanism when real-world examples become available
|
1176
|
-
# In the face of ambiguity, refuse the temptation to guess.
|
1177
|
-
raise ValueError(f"{endpoint} matched to multiple paths: {candidates}")
|
1178
|
-
|
1179
|
-
@staticmethod
|
1180
|
-
def get_parameter_data(
|
1181
|
-
parameters: List[Dict[str, Any]],
|
1182
|
-
parameter_relations: List[Relation],
|
1183
|
-
) -> Dict[str, str]:
|
1184
|
-
"""Generate a valid list of key-value pairs for all parameters."""
|
1185
|
-
result: Dict[str, str] = {}
|
1186
|
-
value: Any = None
|
1187
|
-
for parameter in parameters:
|
1188
|
-
parameter_name = parameter["name"]
|
1189
|
-
parameter_schema = resolve_schema(parameter["schema"])
|
1190
|
-
relations = [
|
1191
|
-
r for r in parameter_relations if r.property_name == parameter_name
|
1192
|
-
]
|
1193
|
-
if constrained_values := [
|
1194
|
-
r.values for r in relations if isinstance(r, PropertyValueConstraint)
|
1195
|
-
]:
|
1196
|
-
value = choice(*constrained_values)
|
1197
|
-
if value is IGNORE:
|
1198
|
-
continue
|
1199
|
-
result[parameter_name] = value
|
1200
|
-
continue
|
1201
|
-
value = value_utils.get_valid_value(parameter_schema)
|
1202
|
-
result[parameter_name] = value
|
1203
|
-
return result
|
1204
|
-
|
1205
|
-
@keyword
|
1206
|
-
def get_json_data_for_dto_class(
|
1207
|
-
self,
|
1208
|
-
schema: Dict[str, Any],
|
1209
|
-
dto_class: Union[Dto, Type[Dto]],
|
1210
|
-
operation_id: str = "",
|
1211
|
-
) -> Optional[Dict[str, Any]]:
|
1212
|
-
"""
|
1213
|
-
Generate a valid (json-compatible) dict for all the `dto_class` properties.
|
1214
|
-
"""
|
1215
|
-
|
1216
|
-
def get_constrained_values(property_name: str) -> List[Any]:
|
1217
|
-
relations = dto_class.get_relations()
|
1218
|
-
values_list = [
|
1219
|
-
c.values
|
1220
|
-
for c in relations
|
1221
|
-
if (
|
1222
|
-
isinstance(c, PropertyValueConstraint)
|
1223
|
-
and c.property_name == property_name
|
1224
|
-
)
|
1225
|
-
]
|
1226
|
-
# values should be empty or contain 1 list of allowed values
|
1227
|
-
return values_list.pop() if values_list else []
|
1228
|
-
|
1229
|
-
def get_dependent_id(
|
1230
|
-
property_name: str, operation_id: str
|
1231
|
-
) -> Optional[Union[str, int, float]]:
|
1232
|
-
relations = dto_class.get_relations()
|
1233
|
-
# multiple get paths are possible based on the operation being performed
|
1234
|
-
id_get_paths = [
|
1235
|
-
(d.get_path, d.operation_id)
|
1236
|
-
for d in relations
|
1237
|
-
if (isinstance(d, IdDependency) and d.property_name == property_name)
|
1238
|
-
]
|
1239
|
-
if not id_get_paths:
|
1240
|
-
return None
|
1241
|
-
if len(id_get_paths) == 1:
|
1242
|
-
id_get_path, _ = id_get_paths.pop()
|
225
|
+
for name, value in overrides.items():
|
226
|
+
if name.startswith(("body_", "header_", "query_")):
|
227
|
+
location, _, name_ = name.partition("_")
|
228
|
+
oas_name = get_oas_name_from_safe_name(name_)
|
229
|
+
if location == "body":
|
230
|
+
request_values.override_body_value(name=oas_name, value=value)
|
231
|
+
if location == "header":
|
232
|
+
request_values.override_header_value(name=oas_name, value=value)
|
233
|
+
if location == "query":
|
234
|
+
request_values.override_param_value(name=oas_name, value=str(value))
|
1243
235
|
else:
|
1244
|
-
|
1245
|
-
|
1246
|
-
path
|
1247
|
-
for path, operation in id_get_paths
|
1248
|
-
if operation == operation_id
|
1249
|
-
]
|
1250
|
-
# There could be multiple get_paths, but not one for the current operation
|
1251
|
-
except ValueError:
|
1252
|
-
return None
|
1253
|
-
valid_id = self.get_valid_id_for_endpoint(
|
1254
|
-
endpoint=id_get_path, method="get"
|
1255
|
-
)
|
1256
|
-
logger.debug(f"get_dependent_id for {id_get_path} returned {valid_id}")
|
1257
|
-
return valid_id
|
1258
|
-
|
1259
|
-
json_data: Dict[str, Any] = {}
|
1260
|
-
|
1261
|
-
property_names = []
|
1262
|
-
for property_name in schema.get("properties", []):
|
1263
|
-
if constrained_values := get_constrained_values(property_name):
|
1264
|
-
# do not add properties that are configured to be ignored
|
1265
|
-
if IGNORE in constrained_values:
|
1266
|
-
continue
|
1267
|
-
property_names.append(property_name)
|
1268
|
-
|
1269
|
-
max_properties = schema.get("maxProperties")
|
1270
|
-
if max_properties and len(property_names) > max_properties:
|
1271
|
-
required_properties = schema.get("required", [])
|
1272
|
-
number_of_optional_properties = max_properties - len(required_properties)
|
1273
|
-
optional_properties = [
|
1274
|
-
name for name in property_names if name not in required_properties
|
1275
|
-
]
|
1276
|
-
selected_optional_properties = sample(
|
1277
|
-
optional_properties, number_of_optional_properties
|
1278
|
-
)
|
1279
|
-
property_names = required_properties + selected_optional_properties
|
1280
|
-
|
1281
|
-
for property_name in property_names:
|
1282
|
-
properties_schema = schema["properties"][property_name]
|
1283
|
-
|
1284
|
-
property_type = properties_schema.get("type")
|
1285
|
-
if property_type is None:
|
1286
|
-
property_types = properties_schema.get("types")
|
1287
|
-
if property_types is None:
|
1288
|
-
if properties_schema.get("properties") is not None:
|
1289
|
-
nested_data = self.get_json_data_for_dto_class(
|
1290
|
-
schema=properties_schema,
|
1291
|
-
dto_class=DefaultDto,
|
1292
|
-
)
|
1293
|
-
json_data[property_name] = nested_data
|
1294
|
-
continue
|
1295
|
-
selected_type_schema = choice(property_types)
|
1296
|
-
property_type = selected_type_schema["type"]
|
1297
|
-
if properties_schema.get("readOnly", False):
|
1298
|
-
continue
|
1299
|
-
if constrained_values := get_constrained_values(property_name):
|
1300
|
-
json_data[property_name] = choice(constrained_values)
|
1301
|
-
continue
|
1302
|
-
if (
|
1303
|
-
dependent_id := get_dependent_id(
|
1304
|
-
property_name=property_name, operation_id=operation_id
|
1305
|
-
)
|
1306
|
-
) is not None:
|
1307
|
-
json_data[property_name] = dependent_id
|
1308
|
-
continue
|
1309
|
-
if property_type == "object":
|
1310
|
-
object_data = self.get_json_data_for_dto_class(
|
1311
|
-
schema=properties_schema,
|
1312
|
-
dto_class=DefaultDto,
|
1313
|
-
operation_id="",
|
1314
|
-
)
|
1315
|
-
json_data[property_name] = object_data
|
1316
|
-
continue
|
1317
|
-
if property_type == "array":
|
1318
|
-
array_data = self.get_json_data_for_dto_class(
|
1319
|
-
schema=properties_schema["items"],
|
1320
|
-
dto_class=DefaultDto,
|
1321
|
-
operation_id=operation_id,
|
1322
|
-
)
|
1323
|
-
json_data[property_name] = [array_data]
|
1324
|
-
continue
|
1325
|
-
json_data[property_name] = value_utils.get_valid_value(properties_schema)
|
1326
|
-
|
1327
|
-
return json_data
|
1328
|
-
|
1329
|
-
@keyword
|
1330
|
-
def get_invalidated_url(self, valid_url: str) -> Optional[str]:
|
1331
|
-
"""
|
1332
|
-
Return an url with all the path parameters in the `valid_url` replaced by a
|
1333
|
-
random UUID.
|
236
|
+
oas_name = get_oas_name_from_safe_name(name)
|
237
|
+
request_values.override_request_value(name=oas_name, value=value)
|
1334
238
|
|
1335
|
-
|
1336
|
-
"""
|
1337
|
-
parameterized_endpoint = self.get_parameterized_endpoint_from_url(valid_url)
|
1338
|
-
parameterized_url = self.base_url + parameterized_endpoint
|
1339
|
-
valid_url_parts = list(reversed(valid_url.split("/")))
|
1340
|
-
parameterized_parts = reversed(parameterized_url.split("/"))
|
1341
|
-
for index, (parameterized_part, _) in enumerate(
|
1342
|
-
zip(parameterized_parts, valid_url_parts)
|
1343
|
-
):
|
1344
|
-
if parameterized_part.startswith("{") and parameterized_part.endswith("}"):
|
1345
|
-
valid_url_parts[index] = uuid4().hex
|
1346
|
-
valid_url_parts.reverse()
|
1347
|
-
invalid_url = "/".join(valid_url_parts)
|
1348
|
-
return invalid_url
|
1349
|
-
raise ValueError(f"{parameterized_endpoint} could not be invalidated.")
|
239
|
+
return request_values
|
1350
240
|
|
1351
241
|
@keyword
|
1352
|
-
def
|
1353
|
-
"""
|
1354
|
-
|
1355
|
-
|
1356
|
-
|
1357
|
-
|
1358
|
-
|
1359
|
-
|
1360
|
-
|
1361
|
-
return parameterized_endpoint
|
242
|
+
def get_request_data(self, path: str, method: str) -> RequestData:
|
243
|
+
"""Return an object with valid request data for body, headers and query params."""
|
244
|
+
return _data_generation.get_request_data(
|
245
|
+
path=path,
|
246
|
+
method=method,
|
247
|
+
get_dto_class=self.get_dto_class,
|
248
|
+
get_id_property_name=self.get_id_property_name,
|
249
|
+
openapi_spec=self.openapi_spec,
|
250
|
+
)
|
1362
251
|
|
1363
252
|
@keyword
|
1364
|
-
def
|
253
|
+
def get_invalid_body_data(
|
1365
254
|
self,
|
1366
255
|
url: str,
|
1367
256
|
method: str,
|
1368
257
|
status_code: int,
|
1369
258
|
request_data: RequestData,
|
1370
|
-
) ->
|
259
|
+
) -> dict[str, JSON]:
|
1371
260
|
"""
|
1372
261
|
Return `json_data` based on the `dto` on the `request_data` that will cause
|
1373
262
|
the provided `status_code` for the `method` operation on the `url`.
|
@@ -1375,318 +264,152 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
1375
264
|
> Note: applicable UniquePropertyValueConstraint and IdReference Relations are
|
1376
265
|
considered before changes to `json_data` are made.
|
1377
266
|
"""
|
1378
|
-
|
1379
|
-
|
1380
|
-
|
1381
|
-
|
1382
|
-
|
1383
|
-
|
1384
|
-
|
1385
|
-
json_data = request_data.dto.get_invalidated_data(
|
1386
|
-
schema=request_data.dto_schema,
|
1387
|
-
status_code=status_code,
|
1388
|
-
invalid_property_default_code=self.invalid_property_default_response,
|
1389
|
-
)
|
1390
|
-
return json_data
|
1391
|
-
resource_relation = choice(data_relations)
|
1392
|
-
if isinstance(resource_relation, UniquePropertyValueConstraint):
|
1393
|
-
json_data = run_keyword(
|
1394
|
-
"get_json_data_with_conflict",
|
1395
|
-
url,
|
1396
|
-
method,
|
1397
|
-
request_data.dto,
|
1398
|
-
status_code,
|
1399
|
-
)
|
1400
|
-
elif isinstance(resource_relation, IdReference):
|
1401
|
-
run_keyword("ensure_in_use", url, resource_relation)
|
1402
|
-
json_data = request_data.dto.as_dict()
|
1403
|
-
else:
|
1404
|
-
json_data = request_data.dto.get_invalidated_data(
|
1405
|
-
schema=request_data.dto_schema,
|
1406
|
-
status_code=status_code,
|
1407
|
-
invalid_property_default_code=self.invalid_property_default_response,
|
1408
|
-
)
|
1409
|
-
return json_data
|
267
|
+
return _data_invalidation.get_invalid_body_data(
|
268
|
+
url=url,
|
269
|
+
method=method,
|
270
|
+
status_code=status_code,
|
271
|
+
request_data=request_data,
|
272
|
+
invalid_property_default_response=self.invalid_property_default_response,
|
273
|
+
)
|
1410
274
|
|
1411
275
|
@keyword
|
1412
276
|
def get_invalidated_parameters(
|
1413
277
|
self,
|
1414
278
|
status_code: int,
|
1415
279
|
request_data: RequestData,
|
1416
|
-
) ->
|
280
|
+
) -> tuple[dict[str, JSON], dict[str, JSON]]:
|
1417
281
|
"""
|
1418
282
|
Returns a version of `params, headers` as present on `request_data` that has
|
1419
283
|
been modified to cause the provided `status_code`.
|
1420
284
|
"""
|
1421
|
-
|
1422
|
-
|
1423
|
-
|
1424
|
-
|
1425
|
-
|
1426
|
-
relations_for_status_code = [
|
1427
|
-
r
|
1428
|
-
for r in relations
|
1429
|
-
if isinstance(r, PropertyValueConstraint)
|
1430
|
-
and (
|
1431
|
-
r.error_code == status_code or r.invalid_value_error_code == status_code
|
1432
|
-
)
|
1433
|
-
]
|
1434
|
-
parameters_to_ignore = {
|
1435
|
-
r.property_name
|
1436
|
-
for r in relations_for_status_code
|
1437
|
-
if r.invalid_value_error_code == status_code and r.invalid_value == IGNORE
|
1438
|
-
}
|
1439
|
-
relation_property_names = {r.property_name for r in relations_for_status_code}
|
1440
|
-
if not relation_property_names:
|
1441
|
-
if status_code != self.invalid_property_default_response:
|
1442
|
-
raise ValueError(
|
1443
|
-
f"No relations to cause status_code {status_code} found."
|
1444
|
-
)
|
1445
|
-
|
1446
|
-
# ensure we're not modifying mutable properties
|
1447
|
-
params = deepcopy(request_data.params)
|
1448
|
-
headers = deepcopy(request_data.headers)
|
285
|
+
return _data_invalidation.get_invalidated_parameters(
|
286
|
+
status_code=status_code,
|
287
|
+
request_data=request_data,
|
288
|
+
invalid_property_default_response=self.invalid_property_default_response,
|
289
|
+
)
|
1449
290
|
|
1450
|
-
|
1451
|
-
|
1452
|
-
|
1453
|
-
|
1454
|
-
|
1455
|
-
|
1456
|
-
|
1457
|
-
|
1458
|
-
|
1459
|
-
|
1460
|
-
|
1461
|
-
|
1462
|
-
|
1463
|
-
|
1464
|
-
|
1465
|
-
|
1466
|
-
# in this specific schema
|
1467
|
-
request_data_parameter_names = [p.get("name") for p in request_data.parameters]
|
1468
|
-
additional_relation_property_names = {
|
1469
|
-
n for n in relation_property_names if n not in request_data_parameter_names
|
1470
|
-
}
|
1471
|
-
if additional_relation_property_names:
|
1472
|
-
logger.warning(
|
1473
|
-
f"get_parameter_relations_for_error_code yielded properties that are "
|
1474
|
-
f"not defined in the schema: {additional_relation_property_names}\n"
|
1475
|
-
f"These properties will be ignored for parameter invalidation."
|
1476
|
-
)
|
1477
|
-
parameter_names = parameter_names - additional_relation_property_names
|
291
|
+
@keyword
|
292
|
+
def get_json_data_with_conflict(
|
293
|
+
self, url: str, method: str, dto: Dto, conflict_status_code: int
|
294
|
+
) -> dict[str, JSON]:
|
295
|
+
"""
|
296
|
+
Return `json_data` based on the `UniquePropertyValueConstraint` that must be
|
297
|
+
returned by the `get_relations` implementation on the `dto` for the given
|
298
|
+
`conflict_status_code`.
|
299
|
+
"""
|
300
|
+
return _data_invalidation.get_json_data_with_conflict(
|
301
|
+
url=url,
|
302
|
+
base_url=self.base_url,
|
303
|
+
method=method,
|
304
|
+
dto=dto,
|
305
|
+
conflict_status_code=conflict_status_code,
|
306
|
+
)
|
1478
307
|
|
1479
|
-
|
1480
|
-
|
1481
|
-
|
1482
|
-
|
308
|
+
# endregion
|
309
|
+
# region: path-related keywords
|
310
|
+
@keyword
|
311
|
+
def get_valid_url(self, path: str) -> str:
|
312
|
+
"""
|
313
|
+
This keyword returns a valid url for the given `path`.
|
1483
314
|
|
1484
|
-
|
1485
|
-
|
315
|
+
If the `path` contains path parameters the Get Valid Id For Path
|
316
|
+
keyword will be executed to retrieve valid ids for the path parameters.
|
1486
317
|
|
1487
|
-
|
1488
|
-
|
1489
|
-
|
1490
|
-
|
1491
|
-
|
1492
|
-
|
1493
|
-
|
1494
|
-
|
1495
|
-
|
1496
|
-
f"{parameter_to_invalidate} not found in provided parameters."
|
1497
|
-
) from None
|
1498
|
-
|
1499
|
-
# get the invalid_value for the chosen parameter
|
1500
|
-
try:
|
1501
|
-
[invalid_value_for_error_code] = [
|
1502
|
-
r.invalid_value
|
1503
|
-
for r in relations_for_status_code
|
1504
|
-
if r.property_name == parameter_to_invalidate
|
1505
|
-
and r.invalid_value_error_code == status_code
|
1506
|
-
]
|
1507
|
-
except ValueError:
|
1508
|
-
invalid_value_for_error_code = NOT_SET
|
1509
|
-
|
1510
|
-
# get the constraint values if available for the chosen parameter
|
1511
|
-
try:
|
1512
|
-
[values_from_constraint] = [
|
1513
|
-
r.values
|
1514
|
-
for r in relations_for_status_code
|
1515
|
-
if r.property_name == parameter_to_invalidate
|
1516
|
-
]
|
1517
|
-
except ValueError:
|
1518
|
-
values_from_constraint = []
|
1519
|
-
|
1520
|
-
# if the parameter was not provided, add it to params / headers
|
1521
|
-
params, headers = self.ensure_parameter_in_parameters(
|
1522
|
-
parameter_to_invalidate=parameter_to_invalidate,
|
1523
|
-
params=params,
|
1524
|
-
headers=headers,
|
1525
|
-
parameter_data=parameter_data,
|
1526
|
-
values_from_constraint=values_from_constraint,
|
318
|
+
> Note: if valid ids cannot be retrieved within the scope of the API, the
|
319
|
+
`PathPropertiesConstraint` Relation can be used. More information can be found
|
320
|
+
[https://marketsquare.github.io/robotframework-openapitools/advanced_use.html | here].
|
321
|
+
"""
|
322
|
+
return _path_functions.get_valid_url(
|
323
|
+
path=path,
|
324
|
+
base_url=self.base_url,
|
325
|
+
get_path_dto_class=self.get_path_dto_class,
|
326
|
+
openapi_spec=self.openapi_spec,
|
1527
327
|
)
|
1528
328
|
|
1529
|
-
|
1530
|
-
|
1531
|
-
|
1532
|
-
|
1533
|
-
if parameter_to_invalidate in params.keys():
|
1534
|
-
valid_value = params[parameter_to_invalidate]
|
1535
|
-
else:
|
1536
|
-
valid_value = headers[parameter_to_invalidate]
|
1537
|
-
|
1538
|
-
value_schema = resolve_schema(parameter_data["schema"])
|
1539
|
-
invalid_value = value_utils.get_invalid_value(
|
1540
|
-
value_schema=value_schema,
|
1541
|
-
current_value=valid_value,
|
1542
|
-
values_from_constraint=values_from_constraint,
|
1543
|
-
)
|
1544
|
-
logger.debug(f"{parameter_to_invalidate} changed to {invalid_value}")
|
329
|
+
@keyword
|
330
|
+
def get_valid_id_for_path(self, path: str) -> str | int | float:
|
331
|
+
"""
|
332
|
+
Support keyword that returns the `id` for an existing resource at `path`.
|
1545
333
|
|
1546
|
-
|
1547
|
-
|
1548
|
-
|
1549
|
-
|
1550
|
-
|
1551
|
-
|
334
|
+
To prevent resource conflicts with other test cases, a new resource is created
|
335
|
+
(by a POST operation) if possible.
|
336
|
+
"""
|
337
|
+
return _path_functions.get_valid_id_for_path(
|
338
|
+
path=path, get_id_property_name=self.get_id_property_name
|
339
|
+
)
|
1552
340
|
|
1553
|
-
@
|
1554
|
-
def
|
1555
|
-
parameter_to_invalidate: str,
|
1556
|
-
params: Dict[str, Any],
|
1557
|
-
headers: Dict[str, str],
|
1558
|
-
parameter_data: Dict[str, Any],
|
1559
|
-
values_from_constraint: List[Any],
|
1560
|
-
) -> Tuple[Dict[str, Any], Dict[str, str]]:
|
341
|
+
@keyword
|
342
|
+
def get_parameterized_path_from_url(self, url: str) -> str:
|
1561
343
|
"""
|
1562
|
-
|
1563
|
-
value to params or headers if not originally present.
|
344
|
+
Return the path as found in the `paths` section based on the given `url`.
|
1564
345
|
"""
|
1565
|
-
|
1566
|
-
|
1567
|
-
|
1568
|
-
)
|
1569
|
-
|
1570
|
-
|
1571
|
-
|
1572
|
-
|
1573
|
-
valid_value = value_utils.get_valid_value(parameter_schema)
|
1574
|
-
if (
|
1575
|
-
parameter_data["in"] == "query"
|
1576
|
-
and parameter_to_invalidate not in params.keys()
|
1577
|
-
):
|
1578
|
-
params[parameter_to_invalidate] = valid_value
|
1579
|
-
if (
|
1580
|
-
parameter_data["in"] == "header"
|
1581
|
-
and parameter_to_invalidate not in headers.keys()
|
1582
|
-
):
|
1583
|
-
headers[parameter_to_invalidate] = valid_value
|
1584
|
-
return params, headers
|
346
|
+
path = url.replace(self.base_url, "")
|
347
|
+
path_parts = path.split("/")
|
348
|
+
# first part will be '' since a path starts with /
|
349
|
+
path_parts.pop(0)
|
350
|
+
parameterized_path = _path_functions.get_parametrized_path(
|
351
|
+
path=path, openapi_spec=self.openapi_spec
|
352
|
+
)
|
353
|
+
return parameterized_path
|
1585
354
|
|
1586
355
|
@keyword
|
1587
|
-
def
|
356
|
+
def get_ids_from_url(self, url: str) -> list[str]:
|
1588
357
|
"""
|
1589
|
-
|
1590
|
-
|
358
|
+
Perform a GET request on the `url` and return the list of resource
|
359
|
+
`ids` from the response.
|
1591
360
|
"""
|
1592
|
-
|
1593
|
-
|
1594
|
-
endpoint = url.replace(self.base_url, "")
|
1595
|
-
endpoint_parts = endpoint.split("/")
|
1596
|
-
parameterized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
|
1597
|
-
parameterized_endpoint_parts = parameterized_endpoint.split("/")
|
1598
|
-
for part, param_part in zip(
|
1599
|
-
reversed(endpoint_parts), reversed(parameterized_endpoint_parts)
|
1600
|
-
):
|
1601
|
-
if param_part.endswith("}"):
|
1602
|
-
resource_id = part
|
1603
|
-
break
|
1604
|
-
if not resource_id:
|
1605
|
-
raise ValueError(f"The provided url ({url}) does not contain an id.")
|
1606
|
-
request_data = self.get_request_data(
|
1607
|
-
method="post", endpoint=resource_relation.post_path
|
1608
|
-
)
|
1609
|
-
json_data = request_data.dto.as_dict()
|
1610
|
-
json_data[resource_relation.property_name] = resource_id
|
1611
|
-
post_url: str = run_keyword(
|
1612
|
-
"get_valid_url",
|
1613
|
-
resource_relation.post_path,
|
1614
|
-
"post",
|
361
|
+
return _path_functions.get_ids_from_url(
|
362
|
+
url=url, get_id_property_name=self.get_id_property_name
|
1615
363
|
)
|
1616
|
-
|
1617
|
-
|
1618
|
-
|
1619
|
-
|
1620
|
-
|
1621
|
-
|
1622
|
-
|
364
|
+
|
365
|
+
@keyword
|
366
|
+
def get_invalidated_url(
|
367
|
+
self,
|
368
|
+
valid_url: str,
|
369
|
+
path: str = "",
|
370
|
+
expected_status_code: int = 404,
|
371
|
+
) -> str:
|
372
|
+
"""
|
373
|
+
Return an url with all the path parameters in the `valid_url` replaced by a
|
374
|
+
random UUID if no PathPropertiesConstraint is mapped for the `"get"` operation
|
375
|
+
on the mapped `path` and `expected_status_code`.
|
376
|
+
If a PathPropertiesConstraint is mapped, the `invalid_value` is returned.
|
377
|
+
|
378
|
+
Raises: ValueError if the valid_url cannot be invalidated.
|
379
|
+
"""
|
380
|
+
return _path_invalidation.get_invalidated_url(
|
381
|
+
valid_url=valid_url,
|
382
|
+
path=path,
|
383
|
+
base_url=self.base_url,
|
384
|
+
get_path_dto_class=self.get_path_dto_class,
|
385
|
+
expected_status_code=expected_status_code,
|
1623
386
|
)
|
1624
|
-
if not response.ok:
|
1625
|
-
logger.debug(
|
1626
|
-
f"POST on {post_url} with json {json_data} failed: {response.json()}"
|
1627
|
-
)
|
1628
|
-
response.raise_for_status()
|
1629
387
|
|
388
|
+
# endregion
|
389
|
+
# region: resource relations keywords
|
1630
390
|
@keyword
|
1631
|
-
def
|
1632
|
-
self, url: str, method: str, dto: Dto, conflict_status_code: int
|
1633
|
-
) -> Dict[str, Any]:
|
391
|
+
def ensure_in_use(self, url: str, resource_relation: IdReference) -> None:
|
1634
392
|
"""
|
1635
|
-
|
1636
|
-
|
1637
|
-
`conflict_status_code`.
|
393
|
+
Ensure that the (right-most) `id` of the resource referenced by the `url`
|
394
|
+
is used by the resource defined by the `resource_relation`.
|
1638
395
|
"""
|
1639
|
-
|
1640
|
-
|
1641
|
-
|
1642
|
-
|
1643
|
-
|
1644
|
-
if isinstance(r, UniquePropertyValueConstraint)
|
1645
|
-
]
|
1646
|
-
for relation in unique_property_value_constraints:
|
1647
|
-
json_data[relation.property_name] = relation.value
|
1648
|
-
# create a new resource that the original request will conflict with
|
1649
|
-
if method in ["patch", "put"]:
|
1650
|
-
post_url_parts = url.split("/")[:-1]
|
1651
|
-
post_url = "/".join(post_url_parts)
|
1652
|
-
# the PATCH or PUT may use a different dto than required for POST
|
1653
|
-
# so a valid POST dto must be constructed
|
1654
|
-
endpoint = post_url.replace(self.base_url, "")
|
1655
|
-
request_data = self.get_request_data(endpoint=endpoint, method="post")
|
1656
|
-
post_json = request_data.dto.as_dict()
|
1657
|
-
for key in post_json.keys():
|
1658
|
-
if key in json_data:
|
1659
|
-
post_json[key] = json_data.get(key)
|
1660
|
-
else:
|
1661
|
-
post_url = url
|
1662
|
-
post_json = json_data
|
1663
|
-
endpoint = post_url.replace(self.base_url, "")
|
1664
|
-
request_data = self.get_request_data(endpoint=endpoint, method="post")
|
1665
|
-
response: Response = run_keyword(
|
1666
|
-
"authorized_request",
|
1667
|
-
post_url,
|
1668
|
-
"post",
|
1669
|
-
request_data.params,
|
1670
|
-
request_data.headers,
|
1671
|
-
post_json,
|
1672
|
-
)
|
1673
|
-
# conflicting resource may already exist
|
1674
|
-
assert (
|
1675
|
-
response.ok or response.status_code == conflict_status_code
|
1676
|
-
), f"get_json_data_with_conflict received {response.status_code}: {response.json()}"
|
1677
|
-
return json_data
|
1678
|
-
raise ValueError(
|
1679
|
-
f"No UniquePropertyValueConstraint in the get_relations list on dto {dto}."
|
396
|
+
_resource_relations.ensure_in_use(
|
397
|
+
url=url,
|
398
|
+
base_url=self.base_url,
|
399
|
+
openapi_spec=self.openapi_spec,
|
400
|
+
resource_relation=resource_relation,
|
1680
401
|
)
|
1681
402
|
|
403
|
+
# endregion
|
404
|
+
# region: request keywords
|
1682
405
|
@keyword
|
1683
406
|
def authorized_request( # pylint: disable=too-many-arguments
|
1684
407
|
self,
|
1685
408
|
url: str,
|
1686
409
|
method: str,
|
1687
|
-
params:
|
1688
|
-
headers:
|
1689
|
-
json_data:
|
410
|
+
params: dict[str, Any] | None = None,
|
411
|
+
headers: dict[str, str] | None = None,
|
412
|
+
json_data: JSON = None,
|
1690
413
|
data: Any = None,
|
1691
414
|
files: Any = None,
|
1692
415
|
) -> Response:
|
@@ -1701,7 +424,7 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
1701
424
|
> Note: provided username / password or auth objects take precedence over token
|
1702
425
|
based security
|
1703
426
|
"""
|
1704
|
-
headers = headers if headers else {}
|
427
|
+
headers = deepcopy(headers) if headers else {}
|
1705
428
|
if self.extra_headers:
|
1706
429
|
headers.update(self.extra_headers)
|
1707
430
|
# if both an auth object and a token are available, auth takes precedence
|
@@ -1726,90 +449,64 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
1726
449
|
logger.debug(f"Response text: {response.text}")
|
1727
450
|
return response
|
1728
451
|
|
452
|
+
# endregion
|
453
|
+
# region: validation keywords
|
1729
454
|
@keyword
|
1730
455
|
def perform_validated_request(
|
1731
456
|
self,
|
1732
457
|
path: str,
|
1733
458
|
status_code: int,
|
1734
459
|
request_values: RequestValues,
|
1735
|
-
original_data:
|
460
|
+
original_data: Mapping[str, JSON] = default_json_mapping,
|
1736
461
|
) -> None:
|
1737
462
|
"""
|
1738
463
|
This keyword first calls the Authorized Request keyword, then the Validate
|
1739
464
|
Response keyword and finally validates, for `DELETE` operations, whether
|
1740
465
|
the target resource was indeed deleted (OK response) or not (error responses).
|
1741
466
|
"""
|
1742
|
-
|
1743
|
-
|
1744
|
-
|
1745
|
-
request_values
|
1746
|
-
|
1747
|
-
request_values.headers,
|
1748
|
-
request_values.json_data,
|
467
|
+
_validation.perform_validated_request(
|
468
|
+
path=path,
|
469
|
+
status_code=status_code,
|
470
|
+
request_values=request_values,
|
471
|
+
original_data=original_data,
|
1749
472
|
)
|
1750
|
-
if response.status_code != status_code:
|
1751
|
-
try:
|
1752
|
-
response_json = response.json()
|
1753
|
-
except Exception as _: # pylint: disable=broad-except
|
1754
|
-
logger.info(
|
1755
|
-
f"Failed to get json content from response. "
|
1756
|
-
f"Response text was: {response.text}"
|
1757
|
-
)
|
1758
|
-
response_json = {}
|
1759
|
-
if not response.ok:
|
1760
|
-
if description := response_json.get("detail"):
|
1761
|
-
pass
|
1762
|
-
else:
|
1763
|
-
description = response_json.get(
|
1764
|
-
"message", "response contains no message or detail."
|
1765
|
-
)
|
1766
|
-
logger.error(f"{response.reason}: {description}")
|
1767
|
-
|
1768
|
-
logger.debug(
|
1769
|
-
f"\nSend: {_json.dumps(request_values.json_data, indent=4, sort_keys=True)}"
|
1770
|
-
f"\nGot: {_json.dumps(response_json, indent=4, sort_keys=True)}"
|
1771
|
-
)
|
1772
|
-
raise AssertionError(
|
1773
|
-
f"Response status_code {response.status_code} was not {status_code}"
|
1774
|
-
)
|
1775
473
|
|
1776
|
-
|
474
|
+
@keyword
|
475
|
+
def validate_response_using_validator(self, response: Response) -> None:
|
476
|
+
"""
|
477
|
+
Validate the `response` against the OpenAPI Spec that is
|
478
|
+
loaded during library initialization.
|
479
|
+
"""
|
480
|
+
_validation.validate_response_using_validator(
|
481
|
+
response=response,
|
482
|
+
response_validator=self.response_validator,
|
483
|
+
)
|
1777
484
|
|
1778
|
-
|
1779
|
-
|
1780
|
-
|
1781
|
-
|
1782
|
-
|
1783
|
-
|
1784
|
-
|
1785
|
-
|
1786
|
-
|
1787
|
-
|
1788
|
-
|
1789
|
-
|
1790
|
-
|
1791
|
-
|
1792
|
-
logger.warning(
|
1793
|
-
f"Unexpected response after deleting resource: Status_code "
|
1794
|
-
f"{get_response.status_code} was received after trying to get {request_values.url} "
|
1795
|
-
f"after sucessfully deleting it."
|
1796
|
-
)
|
1797
|
-
elif not get_response.ok:
|
1798
|
-
raise AssertionError(
|
1799
|
-
f"Resource could not be retrieved after failed deletion. "
|
1800
|
-
f"Url was {request_values.url}, status_code was {get_response.status_code}"
|
1801
|
-
)
|
485
|
+
@keyword
|
486
|
+
def assert_href_to_resource_is_valid(
|
487
|
+
self, href: str, referenced_resource: dict[str, JSON]
|
488
|
+
) -> None:
|
489
|
+
"""
|
490
|
+
Attempt to GET the resource referenced by the `href` and validate it's equal
|
491
|
+
to the provided `referenced_resource` object / dictionary.
|
492
|
+
"""
|
493
|
+
_validation.assert_href_to_resource_is_valid(
|
494
|
+
href=href,
|
495
|
+
origin=self.origin,
|
496
|
+
base_url=self.base_url,
|
497
|
+
referenced_resource=referenced_resource,
|
498
|
+
)
|
1802
499
|
|
1803
500
|
@keyword
|
1804
501
|
def validate_response(
|
1805
502
|
self,
|
1806
503
|
path: str,
|
1807
504
|
response: Response,
|
1808
|
-
original_data:
|
505
|
+
original_data: Mapping[str, JSON] = default_json_mapping,
|
1809
506
|
) -> None:
|
1810
507
|
"""
|
1811
508
|
Validate the `response` by performing the following validations:
|
1812
|
-
- validate the `response` against the openapi schema for the `
|
509
|
+
- validate the `response` against the openapi schema for the `path`
|
1813
510
|
- validate that the response does not contain extra properties
|
1814
511
|
- validate that a href, if present, refers to the correct resource
|
1815
512
|
- validate that the value for a property that is in the response is equal to
|
@@ -1817,375 +514,163 @@ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
|
|
1817
514
|
- validate that no `original_data` is preserved when performing a PUT operation
|
1818
515
|
- validate that a PATCH operation only updates the provided properties
|
1819
516
|
"""
|
1820
|
-
|
1821
|
-
assert not response.content
|
1822
|
-
return None
|
1823
|
-
|
1824
|
-
try:
|
1825
|
-
self._validate_response_against_spec(response)
|
1826
|
-
except OpenAPIError as exception:
|
1827
|
-
raise Failure(f"Response did not pass schema validation: {exception}")
|
1828
|
-
|
1829
|
-
request_method = response.request.method
|
1830
|
-
if request_method is None:
|
1831
|
-
logger.warning(
|
1832
|
-
f"Could not validate response for path {path}; no method found "
|
1833
|
-
f"on the request property of the provided response."
|
1834
|
-
)
|
1835
|
-
return None
|
1836
|
-
|
1837
|
-
response_spec = self._get_response_spec(
|
517
|
+
_validation.validate_response(
|
1838
518
|
path=path,
|
1839
|
-
|
1840
|
-
|
519
|
+
response=response,
|
520
|
+
response_validator=self.response_validator,
|
521
|
+
server_validation_warning_logged=self._server_validation_warning_logged,
|
522
|
+
disable_server_validation=self.disable_server_validation,
|
523
|
+
invalid_property_default_response=self.invalid_property_default_response,
|
524
|
+
response_validation=self.response_validation,
|
525
|
+
openapi_spec=self.openapi_spec,
|
526
|
+
original_data=original_data,
|
1841
527
|
)
|
1842
528
|
|
1843
|
-
|
1844
|
-
|
529
|
+
@staticmethod
|
530
|
+
@keyword
|
531
|
+
def validate_send_response(
|
532
|
+
response: Response,
|
533
|
+
original_data: Mapping[str, JSON] = default_json_mapping,
|
534
|
+
) -> None:
|
535
|
+
"""
|
536
|
+
Validate that each property that was send that is in the response has the value
|
537
|
+
that was send.
|
538
|
+
In case a PATCH request, validate that only the properties that were patched
|
539
|
+
have changed and that other properties are still at their pre-patch values.
|
540
|
+
"""
|
541
|
+
_validation.validate_send_response(
|
542
|
+
response=response, original_data=original_data
|
543
|
+
)
|
1845
544
|
|
1846
|
-
|
1847
|
-
logger.warning(
|
1848
|
-
"The response cannot be validated: 'content' not specified in the OAS."
|
1849
|
-
)
|
1850
|
-
return None
|
1851
|
-
|
1852
|
-
# multiple content types can be specified in the OAS
|
1853
|
-
content_types = list(response_spec["content"].keys())
|
1854
|
-
supported_types = [
|
1855
|
-
ct for ct in content_types if ct.partition(";")[0].endswith("json")
|
1856
|
-
]
|
1857
|
-
if not supported_types:
|
1858
|
-
raise NotImplementedError(
|
1859
|
-
f"The content_types '{content_types}' are not supported. "
|
1860
|
-
f"Only json types are currently supported."
|
1861
|
-
)
|
1862
|
-
content_type = supported_types[0]
|
1863
|
-
mime_type = content_type.partition(";")[0]
|
545
|
+
# endregion
|
1864
546
|
|
1865
|
-
|
1866
|
-
|
1867
|
-
|
1868
|
-
f"does not match '{mime_type}' as specified in the OpenAPI document."
|
1869
|
-
)
|
547
|
+
@property
|
548
|
+
def origin(self) -> str:
|
549
|
+
return self._origin
|
1870
550
|
|
1871
|
-
|
1872
|
-
|
1873
|
-
|
1874
|
-
)
|
551
|
+
@property
|
552
|
+
def base_url(self) -> str:
|
553
|
+
return f"{self.origin}{self._base_path}"
|
1875
554
|
|
1876
|
-
|
1877
|
-
|
1878
|
-
|
1879
|
-
|
555
|
+
@cached_property
|
556
|
+
def validation_spec(self) -> Spec:
|
557
|
+
_, validation_spec, _ = self._load_specs_and_validator()
|
558
|
+
return validation_spec
|
559
|
+
|
560
|
+
@property
|
561
|
+
def openapi_spec(self) -> OpenApiObject:
|
562
|
+
"""Return a deepcopy of the parsed openapi document."""
|
563
|
+
# protect the parsed openapi spec from being mutated by reference
|
564
|
+
return deepcopy(self._openapi_spec)
|
565
|
+
|
566
|
+
@cached_property
|
567
|
+
def _openapi_spec(self) -> OpenApiObject:
|
568
|
+
parser, _, _ = self._load_specs_and_validator()
|
569
|
+
spec_model = OpenApiObject.model_validate(parser.specification)
|
570
|
+
register_path_parameters(spec_model.paths)
|
571
|
+
return spec_model
|
572
|
+
|
573
|
+
@cached_property
|
574
|
+
def response_validator(
|
575
|
+
self,
|
576
|
+
) -> ResponseValidatorType:
|
577
|
+
_, _, response_validator = self._load_specs_and_validator()
|
578
|
+
return response_validator
|
579
|
+
|
580
|
+
def _get_json_types_from_spec(self, spec: dict[str, JSON]) -> set[str]:
|
581
|
+
json_types: set[str] = set(self._get_json_types(spec))
|
582
|
+
return {json_type for json_type in json_types if json_type is not None}
|
583
|
+
|
584
|
+
def _get_json_types(self, item: object) -> Generator[str, None, None]:
|
585
|
+
if isinstance(item, dict):
|
586
|
+
content_dict = item.get("content")
|
587
|
+
if content_dict is None:
|
588
|
+
for value in item.values():
|
589
|
+
yield from self._get_json_types(value)
|
1880
590
|
|
1881
|
-
if list_item_schema := response_schema.get("items"):
|
1882
|
-
if not isinstance(json_response, list):
|
1883
|
-
raise AssertionError(
|
1884
|
-
f"Response schema violation: the schema specifies an array as "
|
1885
|
-
f"response type but the response was of type {type(json_response)}."
|
1886
|
-
)
|
1887
|
-
type_of_list_items = list_item_schema.get("type")
|
1888
|
-
if type_of_list_items == "object":
|
1889
|
-
for resource in json_response:
|
1890
|
-
run_keyword(
|
1891
|
-
"validate_resource_properties", resource, list_item_schema
|
1892
|
-
)
|
1893
591
|
else:
|
1894
|
-
for
|
1895
|
-
|
1896
|
-
|
1897
|
-
|
1898
|
-
|
1899
|
-
|
1900
|
-
|
1901
|
-
|
1902
|
-
|
1903
|
-
|
1904
|
-
|
1905
|
-
|
1906
|
-
|
1907
|
-
|
1908
|
-
|
1909
|
-
|
1910
|
-
|
1911
|
-
|
1912
|
-
|
1913
|
-
|
1914
|
-
|
1915
|
-
|
1916
|
-
params = request_data.params
|
1917
|
-
headers = request_data.headers
|
1918
|
-
get_response = run_keyword("authorized_request", url, "GET", params, headers)
|
1919
|
-
assert (
|
1920
|
-
get_response.json() == json_response
|
1921
|
-
), f"{get_response.json()} not equal to original {json_response}"
|
592
|
+
for content_type in content_dict:
|
593
|
+
if "json" in content_type:
|
594
|
+
content_type_without_charset, _, _ = content_type.partition(";")
|
595
|
+
yield content_type_without_charset
|
596
|
+
|
597
|
+
if isinstance(item, list):
|
598
|
+
for list_item in item:
|
599
|
+
yield from self._get_json_types(list_item)
|
600
|
+
|
601
|
+
def _load_specs_and_validator(
|
602
|
+
self,
|
603
|
+
) -> tuple[
|
604
|
+
ResolvingParser,
|
605
|
+
Spec,
|
606
|
+
ResponseValidatorType,
|
607
|
+
]:
|
608
|
+
def recursion_limit_handler(
|
609
|
+
limit: int, # pylint: disable=unused-argument
|
610
|
+
refstring: str, # pylint: disable=unused-argument
|
611
|
+
recursions: JSON, # pylint: disable=unused-argument
|
612
|
+
) -> JSON:
|
613
|
+
return self._recursion_default # pragma: no cover
|
1922
614
|
|
1923
|
-
def _validate_response_against_spec(self, response: Response) -> None:
|
1924
615
|
try:
|
1925
|
-
|
1926
|
-
|
1927
|
-
|
1928
|
-
|
1929
|
-
|
1930
|
-
|
1931
|
-
|
1932
|
-
|
1933
|
-
|
1934
|
-
|
1935
|
-
|
1936
|
-
[
|
1937
|
-
f"{list(error.schema_path)}: {error.message}"
|
1938
|
-
for error in validation_errors
|
1939
|
-
]
|
616
|
+
# Since parsing of the OAS and creating the Spec can take a long time,
|
617
|
+
# they are cached. This is done by storing them in an imported module that
|
618
|
+
# will have a global scope due to how the Python import system works. This
|
619
|
+
# ensures that in a Suite of Suites where multiple Suites use the same
|
620
|
+
# `source`, that OAS is only parsed / loaded once.
|
621
|
+
cached_parser = PARSER_CACHE.get(self._source, None)
|
622
|
+
if cached_parser:
|
623
|
+
return (
|
624
|
+
cached_parser.parser,
|
625
|
+
cached_parser.validation_spec,
|
626
|
+
cached_parser.response_validator,
|
1940
627
|
)
|
1941
|
-
else:
|
1942
|
-
error_message = str(exception)
|
1943
|
-
|
1944
|
-
if isinstance(exception, ServerNotFound):
|
1945
|
-
if not self._server_validation_warning_logged:
|
1946
|
-
logger.warning(
|
1947
|
-
f"ServerNotFound was raised during response validation. "
|
1948
|
-
f"Due to this, no full response validation will be performed."
|
1949
|
-
f"\nThe original error was: {error_message}"
|
1950
|
-
)
|
1951
|
-
self._server_validation_warning_logged = True
|
1952
|
-
if self.disable_server_validation:
|
1953
|
-
return
|
1954
|
-
if response.status_code == self.invalid_property_default_response:
|
1955
|
-
logger.debug(error_message)
|
1956
|
-
return
|
1957
|
-
if self.response_validation == ValidationLevel.STRICT:
|
1958
|
-
logger.error(error_message)
|
1959
|
-
raise exception
|
1960
|
-
if self.response_validation == ValidationLevel.WARN:
|
1961
|
-
logger.warning(error_message)
|
1962
|
-
elif self.response_validation == ValidationLevel.INFO:
|
1963
|
-
logger.info(error_message)
|
1964
|
-
|
1965
|
-
@keyword
|
1966
|
-
def validate_resource_properties(
|
1967
|
-
self, resource: Dict[str, Any], schema: Dict[str, Any]
|
1968
|
-
) -> None:
|
1969
|
-
"""
|
1970
|
-
Validate that the `resource` does not contain any properties that are not
|
1971
|
-
defined in the `schema_properties`.
|
1972
|
-
"""
|
1973
|
-
schema_properties = schema.get("properties", {})
|
1974
|
-
property_names_from_schema = set(schema_properties.keys())
|
1975
|
-
property_names_in_resource = set(resource.keys())
|
1976
|
-
|
1977
|
-
if property_names_from_schema != property_names_in_resource:
|
1978
|
-
# The additionalProperties property determines whether properties with
|
1979
|
-
# unspecified names are allowed. This property can be boolean or an object
|
1980
|
-
# (dict) that specifies the type of any additional properties.
|
1981
|
-
additional_properties = schema.get("additionalProperties", True)
|
1982
|
-
if isinstance(additional_properties, bool):
|
1983
|
-
allow_additional_properties = additional_properties
|
1984
|
-
allowed_additional_properties_type = None
|
1985
|
-
else:
|
1986
|
-
allow_additional_properties = True
|
1987
|
-
allowed_additional_properties_type = additional_properties["type"]
|
1988
628
|
|
1989
|
-
|
1990
|
-
|
1991
|
-
|
1992
|
-
|
1993
|
-
|
1994
|
-
if allowed_additional_properties_type:
|
1995
|
-
extra_properties = {
|
1996
|
-
key: value
|
1997
|
-
for key, value in resource.items()
|
1998
|
-
if key in extra_property_names
|
1999
|
-
}
|
2000
|
-
self._validate_type_of_extra_properties(
|
2001
|
-
extra_properties=extra_properties,
|
2002
|
-
expected_type=allowed_additional_properties_type,
|
2003
|
-
)
|
2004
|
-
# If allowed, validation should not fail on extra properties
|
2005
|
-
extra_property_names = set()
|
2006
|
-
|
2007
|
-
required_properties = set(schema.get("required", []))
|
2008
|
-
missing_properties = required_properties.difference(
|
2009
|
-
property_names_in_resource
|
629
|
+
parser = ResolvingParser(
|
630
|
+
self._source,
|
631
|
+
backend="openapi-spec-validator",
|
632
|
+
recursion_limit=self._recursion_limit,
|
633
|
+
recursion_limit_handler=recursion_limit_handler,
|
2010
634
|
)
|
2011
635
|
|
2012
|
-
if
|
2013
|
-
|
2014
|
-
|
2015
|
-
if extra_property_names
|
2016
|
-
else ""
|
2017
|
-
)
|
2018
|
-
missing = (
|
2019
|
-
f"\n\tRequired properties missing in response: {missing_properties}"
|
2020
|
-
if missing_properties
|
2021
|
-
else ""
|
2022
|
-
)
|
2023
|
-
raise AssertionError(
|
2024
|
-
f"Response schema violation: the response contains properties that are "
|
2025
|
-
f"not specified in the schema or does not contain properties that are "
|
2026
|
-
f"required according to the schema."
|
2027
|
-
f"\n\tReceived in the response: {property_names_in_resource}"
|
2028
|
-
f"\n\tDefined in the schema: {property_names_from_schema}"
|
2029
|
-
f"{extra}{missing}"
|
636
|
+
if parser.specification is None: # pragma: no cover
|
637
|
+
raise FatalError(
|
638
|
+
"Source was loaded, but no specification was present after parsing."
|
2030
639
|
)
|
2031
640
|
|
2032
|
-
|
2033
|
-
def _validate_value_type(value: Any, expected_type: str) -> None:
|
2034
|
-
type_mapping = {
|
2035
|
-
"string": str,
|
2036
|
-
"number": float,
|
2037
|
-
"integer": int,
|
2038
|
-
"boolean": bool,
|
2039
|
-
"array": list,
|
2040
|
-
"object": dict,
|
2041
|
-
}
|
2042
|
-
python_type = type_mapping.get(expected_type, None)
|
2043
|
-
if python_type is None:
|
2044
|
-
raise AssertionError(
|
2045
|
-
f"Validation of type '{expected_type}' is not supported."
|
2046
|
-
)
|
2047
|
-
if not isinstance(value, python_type):
|
2048
|
-
raise AssertionError(f"{value} is not of type {expected_type}")
|
641
|
+
validation_spec = Spec.from_dict(parser.specification) # pyright: ignore[reportArgumentType]
|
2049
642
|
|
2050
|
-
|
2051
|
-
|
2052
|
-
extra_properties: Dict[str, Any], expected_type: str
|
2053
|
-
) -> None:
|
2054
|
-
type_mapping = {
|
2055
|
-
"string": str,
|
2056
|
-
"number": float,
|
2057
|
-
"integer": int,
|
2058
|
-
"boolean": bool,
|
2059
|
-
"array": list,
|
2060
|
-
"object": dict,
|
2061
|
-
}
|
2062
|
-
|
2063
|
-
python_type = type_mapping.get(expected_type, None)
|
2064
|
-
if python_type is None:
|
2065
|
-
logger.warning(
|
2066
|
-
f"Additonal properties were not validated: "
|
2067
|
-
f"type '{expected_type}' is not supported."
|
643
|
+
json_types_from_spec: set[str] = self._get_json_types_from_spec(
|
644
|
+
parser.specification
|
2068
645
|
)
|
2069
|
-
|
2070
|
-
|
2071
|
-
|
2072
|
-
|
2073
|
-
|
2074
|
-
|
2075
|
-
|
2076
|
-
|
2077
|
-
|
2078
|
-
|
2079
|
-
|
646
|
+
extra_deserializers = {
|
647
|
+
json_type: _json.loads for json_type in json_types_from_spec
|
648
|
+
}
|
649
|
+
config = Config(extra_media_type_deserializers=extra_deserializers) # type: ignore[arg-type]
|
650
|
+
openapi = OpenAPI(spec=validation_spec, config=config)
|
651
|
+
response_validator: ResponseValidatorType = openapi.validate_response # type: ignore[assignment]
|
652
|
+
|
653
|
+
PARSER_CACHE[self._source] = CachedParser(
|
654
|
+
parser=parser,
|
655
|
+
validation_spec=validation_spec,
|
656
|
+
response_validator=response_validator,
|
2080
657
|
)
|
2081
658
|
|
2082
|
-
|
2083
|
-
@keyword
|
2084
|
-
def validate_send_response(
|
2085
|
-
response: Response, original_data: Optional[Dict[str, Any]] = None
|
2086
|
-
) -> None:
|
2087
|
-
"""
|
2088
|
-
Validate that each property that was send that is in the response has the value
|
2089
|
-
that was send.
|
2090
|
-
In case a PATCH request, validate that only the properties that were patched
|
2091
|
-
have changed and that other properties are still at their pre-patch values.
|
2092
|
-
"""
|
659
|
+
return parser, validation_spec, response_validator
|
2093
660
|
|
2094
|
-
|
2095
|
-
|
2096
|
-
|
2097
|
-
|
2098
|
-
|
2099
|
-
|
2100
|
-
|
2101
|
-
|
2102
|
-
|
2103
|
-
|
2104
|
-
|
2105
|
-
|
2106
|
-
|
2107
|
-
|
2108
|
-
|
2109
|
-
|
2110
|
-
# sometimes, a property in the request is not in the response, e.g. a password
|
2111
|
-
if send_property_name not in received_dict.keys():
|
2112
|
-
continue
|
2113
|
-
if send_property_value is not None:
|
2114
|
-
# if a None value is send, the target property should be cleared or
|
2115
|
-
# reverted to the default value (which cannot be specified in the
|
2116
|
-
# openapi document)
|
2117
|
-
received_value = received_dict[send_property_name]
|
2118
|
-
# In case of lists / arrays, the send values are often appended to
|
2119
|
-
# existing data
|
2120
|
-
if isinstance(received_value, list):
|
2121
|
-
validate_list_response(
|
2122
|
-
send_list=send_property_value, received_list=received_value
|
2123
|
-
)
|
2124
|
-
continue
|
2125
|
-
|
2126
|
-
# when dealing with objects, we'll need to iterate the properties
|
2127
|
-
if isinstance(received_value, dict):
|
2128
|
-
validate_dict_response(
|
2129
|
-
send_dict=send_property_value, received_dict=received_value
|
2130
|
-
)
|
2131
|
-
continue
|
2132
|
-
|
2133
|
-
assert received_value == send_property_value, (
|
2134
|
-
f"Received value for {send_property_name} '{received_value}' does not "
|
2135
|
-
f"match '{send_property_value}' in the {response.request.method} request."
|
2136
|
-
f"\nSend: {_json.dumps(send_json, indent=4, sort_keys=True)}"
|
2137
|
-
f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
|
2138
|
-
)
|
2139
|
-
|
2140
|
-
if response.request.body is None:
|
2141
|
-
logger.warning(
|
2142
|
-
"Could not validate send response; the body of the request property "
|
2143
|
-
"on the provided response was None."
|
2144
|
-
)
|
2145
|
-
return None
|
2146
|
-
if isinstance(response.request.body, bytes):
|
2147
|
-
send_json = _json.loads(response.request.body.decode("UTF-8"))
|
2148
|
-
else:
|
2149
|
-
send_json = _json.loads(response.request.body)
|
2150
|
-
|
2151
|
-
response_data = response.json()
|
2152
|
-
# POST on /resource_type/{id}/array_item/ will return the updated {id} resource
|
2153
|
-
# instead of a newly created resource. In this case, the send_json must be
|
2154
|
-
# in the array of the 'array_item' property on {id}
|
2155
|
-
send_path: str = response.request.path_url
|
2156
|
-
response_path = response_data.get("href", None)
|
2157
|
-
if response_path and send_path not in response_path:
|
2158
|
-
property_to_check = send_path.replace(response_path, "")[1:]
|
2159
|
-
if response_data.get(property_to_check) and isinstance(
|
2160
|
-
response_data[property_to_check], list
|
2161
|
-
):
|
2162
|
-
item_list: List[Dict[str, Any]] = response_data[property_to_check]
|
2163
|
-
# Use the (mandatory) id to get the POSTed resource from the list
|
2164
|
-
[response_data] = [
|
2165
|
-
item for item in item_list if item["id"] == send_json["id"]
|
2166
|
-
]
|
2167
|
-
|
2168
|
-
# incoming arguments are dictionaries, so they can be validated as such
|
2169
|
-
validate_dict_response(send_dict=send_json, received_dict=response_data)
|
2170
|
-
|
2171
|
-
# In case of PATCH requests, ensure that only send properties have changed
|
2172
|
-
if original_data:
|
2173
|
-
for send_property_name, send_value in original_data.items():
|
2174
|
-
if send_property_name not in send_json.keys():
|
2175
|
-
assert send_value == response_data[send_property_name], (
|
2176
|
-
f"Received value for {send_property_name} '{response_data[send_property_name]}' does not "
|
2177
|
-
f"match '{send_value}' in the pre-patch data"
|
2178
|
-
f"\nPre-patch: {_json.dumps(original_data, indent=4, sort_keys=True)}"
|
2179
|
-
f"\nGot: {_json.dumps(response_data, indent=4, sort_keys=True)}"
|
2180
|
-
)
|
2181
|
-
return None
|
2182
|
-
|
2183
|
-
def _get_response_spec(
|
2184
|
-
self, path: str, method: str, status_code: int
|
2185
|
-
) -> Dict[str, Any]:
|
2186
|
-
method = method.lower()
|
2187
|
-
status = str(status_code)
|
2188
|
-
spec: Dict[str, Any] = {**self.openapi_spec}["paths"][path][method][
|
2189
|
-
"responses"
|
2190
|
-
][status]
|
2191
|
-
return spec
|
661
|
+
except ResolutionError as exception: # pragma: no cover
|
662
|
+
raise FatalError(
|
663
|
+
f"ResolutionError while trying to load openapi spec: {exception}"
|
664
|
+
) from exception
|
665
|
+
except ValidationError as exception: # pragma: no cover
|
666
|
+
raise FatalError(
|
667
|
+
f"ValidationError while trying to load openapi spec: {exception}"
|
668
|
+
) from exception
|
669
|
+
|
670
|
+
def read_paths(self) -> dict[str, PathItemObject]:
|
671
|
+
return self.openapi_spec.paths
|
672
|
+
|
673
|
+
__init__.__doc__ = OPENAPILIBCORE_INIT_DOCSTRING
|
674
|
+
|
675
|
+
|
676
|
+
OpenApiLibCore.__doc__ = OPENAPILIBCORE_LIBRARY_DOCSTRING
|