robotframework-openapitools 0.1.1__py3-none-any.whl → 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1492 +1,1525 @@
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
- import json as _json
122
- import sys
123
- from copy import deepcopy
124
- from dataclasses import Field, dataclass, field, make_dataclass
125
- from functools import cached_property
126
- from itertools import zip_longest
127
- from logging import getLogger
128
- from pathlib import Path
129
- from random import choice
130
- from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union
131
- from uuid import uuid4
132
-
133
- from openapi_core import Spec, validate_response
134
- from openapi_core.contrib.requests import (
135
- RequestsOpenAPIRequest,
136
- RequestsOpenAPIResponse,
137
- )
138
- from prance import ResolvingParser, ValidationError
139
- from prance.util.url import ResolutionError
140
- from requests import Response, Session
141
- from requests.auth import AuthBase, HTTPBasicAuth
142
- from requests.cookies import RequestsCookieJar as CookieJar
143
- from robot.api.deco import keyword, library
144
- from robot.libraries.BuiltIn import BuiltIn
145
-
146
- from OpenApiLibCore import value_utils
147
- from OpenApiLibCore.dto_base import (
148
- NOT_SET,
149
- Dto,
150
- IdDependency,
151
- IdReference,
152
- PathPropertiesConstraint,
153
- PropertyValueConstraint,
154
- Relation,
155
- UniquePropertyValueConstraint,
156
- resolve_schema,
157
- )
158
- from OpenApiLibCore.dto_utils import (
159
- DEFAULT_ID_PROPERTY_NAME,
160
- DefaultDto,
161
- get_dto_class,
162
- get_id_property_name,
163
- )
164
- from OpenApiLibCore.oas_cache import PARSER_CACHE
165
- from OpenApiLibCore.value_utils import FAKE, IGNORE, JSON
166
-
167
- run_keyword = BuiltIn().run_keyword
168
-
169
- logger = getLogger(__name__)
170
-
171
-
172
- def get_safe_key(key: str) -> str:
173
- """
174
- Helper function to convert a valid JSON property name to a string that can be used
175
- as a Python variable or function / method name.
176
- """
177
- key = key.replace("-", "_")
178
- key = key.replace("@", "_")
179
- if key[0].isdigit():
180
- key = f"_{key}"
181
- return key
182
-
183
-
184
- @dataclass
185
- class RequestValues:
186
- """Helper class to hold parameter values needed to make a request."""
187
-
188
- url: str
189
- method: str
190
- params: Optional[Dict[str, Any]]
191
- headers: Optional[Dict[str, str]]
192
- json_data: Optional[Dict[str, Any]]
193
-
194
-
195
- @dataclass
196
- class RequestData:
197
- """Helper class to manage parameters used when making requests."""
198
-
199
- dto: Union[Dto, DefaultDto] = field(default_factory=DefaultDto)
200
- dto_schema: Dict[str, Any] = field(default_factory=dict)
201
- parameters: List[Dict[str, Any]] = field(default_factory=list)
202
- params: Dict[str, Any] = field(default_factory=dict)
203
- headers: Dict[str, Any] = field(default_factory=dict)
204
-
205
- def __post_init__(self) -> None:
206
- # prevent modification by reference
207
- self.dto_schema = deepcopy(self.dto_schema)
208
- self.parameters = deepcopy(self.parameters)
209
- self.params = deepcopy(self.params)
210
- self.headers = deepcopy(self.headers)
211
-
212
- @property
213
- def has_optional_properties(self) -> bool:
214
- """Whether or not the dto data (json data) contains optional properties."""
215
-
216
- def is_required_property(property_name: str) -> bool:
217
- return property_name in self.dto_schema.get("required", [])
218
-
219
- properties = (self.dto.as_dict()).keys()
220
- return not all(map(is_required_property, properties))
221
-
222
- @property
223
- def has_optional_params(self) -> bool:
224
- """Whether or not any of the query parameters are optional."""
225
-
226
- def is_optional_param(query_param: str) -> bool:
227
- optional_params = [
228
- p.get("name")
229
- for p in self.parameters
230
- if p.get("in") == "query" and not p.get("required")
231
- ]
232
- return query_param in optional_params
233
-
234
- return any(map(is_optional_param, self.params))
235
-
236
- @cached_property
237
- def params_that_can_be_invalidated(self) -> Set[str]:
238
- """
239
- The query parameters that can be invalidated by violating data
240
- restrictions, data type or by not providing them in a request.
241
- """
242
- result = set()
243
- params = [h for h in self.parameters if h.get("in") == "query"]
244
- for param in params:
245
- # required params can be omitted to invalidate a request
246
- if param["required"]:
247
- result.add(param["name"])
248
- continue
249
-
250
- schema = resolve_schema(param["schema"])
251
- if schema.get("type", None):
252
- param_types = [schema]
253
- else:
254
- param_types = schema["types"]
255
- for param_type in param_types:
256
- # any basic non-string type except "null" can be invalidated by
257
- # replacing it with a string
258
- if param_type["type"] not in ["string", "array", "object", "null"]:
259
- result.add(param["name"])
260
- continue
261
- # enums, strings and arrays with boundaries can be invalidated
262
- if set(param_type.keys()).intersection(
263
- {
264
- "enum",
265
- "minLength",
266
- "maxLength",
267
- "minItems",
268
- "maxItems",
269
- }
270
- ):
271
- result.add(param["name"])
272
- continue
273
- # an array of basic non-string type can be invalidated by replacing the
274
- # items in the array with strings
275
- if param_type["type"] == "array" and param_type["items"][
276
- "type"
277
- ] not in [
278
- "string",
279
- "array",
280
- "object",
281
- "null",
282
- ]:
283
- result.add(param["name"])
284
- return result
285
-
286
- @property
287
- def has_optional_headers(self) -> bool:
288
- """Whether or not any of the headers are optional."""
289
-
290
- def is_optional_header(header: str) -> bool:
291
- optional_headers = [
292
- p.get("name")
293
- for p in self.parameters
294
- if p.get("in") == "header" and not p.get("required")
295
- ]
296
- return header in optional_headers
297
-
298
- return any(map(is_optional_header, self.headers))
299
-
300
- @cached_property
301
- def headers_that_can_be_invalidated(self) -> Set[str]:
302
- """
303
- The header parameters that can be invalidated by violating data
304
- restrictions or by not providing them in a request.
305
- """
306
- result = set()
307
- headers = [h for h in self.parameters if h.get("in") == "header"]
308
- for header in headers:
309
- # required headers can be omitted to invalidate a request
310
- if header["required"]:
311
- result.add(header["name"])
312
- continue
313
-
314
- schema = resolve_schema(header["schema"])
315
- if schema.get("type", None):
316
- header_types = [schema]
317
- else:
318
- header_types = schema["types"]
319
- for header_type in header_types:
320
- # any basic non-string type except "null" can be invalidated by
321
- # replacing it with a string
322
- if header_type["type"] not in ["string", "array", "object", "null"]:
323
- result.add(header["name"])
324
- continue
325
- # enums, strings and arrays with boundaries can be invalidated
326
- if set(header_type.keys()).intersection(
327
- {
328
- "enum",
329
- "minLength",
330
- "maxLength",
331
- "minItems",
332
- "maxItems",
333
- }
334
- ):
335
- result.add(header["name"])
336
- continue
337
- # an array of basic non-string type can be invalidated by replacing the
338
- # items in the array with strings
339
- if header_type["type"] == "array" and header_type["items"][
340
- "type"
341
- ] not in [
342
- "string",
343
- "array",
344
- "object",
345
- "null",
346
- ]:
347
- result.add(header["name"])
348
- return result
349
-
350
- def get_required_properties_dict(self) -> Dict[str, Any]:
351
- """Get the json-compatible dto data containing only the required properties."""
352
- required_properties = self.dto_schema.get("required", [])
353
- required_properties_dict: Dict[str, Any] = {}
354
- for key, value in (self.dto.as_dict()).items():
355
- if key in required_properties:
356
- required_properties_dict[key] = value
357
- return required_properties_dict
358
-
359
- def get_required_params(self) -> Dict[str, str]:
360
- """Get the params dict containing only the required query parameters."""
361
- required_parameters = [
362
- p.get("name") for p in self.parameters if p.get("required")
363
- ]
364
- return {k: v for k, v in self.params.items() if k in required_parameters}
365
-
366
- def get_required_headers(self) -> Dict[str, str]:
367
- """Get the headers dict containing only the required headers."""
368
- required_parameters = [
369
- p.get("name") for p in self.parameters if p.get("required")
370
- ]
371
- return {k: v for k, v in self.headers.items() if k in required_parameters}
372
-
373
-
374
- @library(scope="TEST SUITE", doc_format="ROBOT")
375
- class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
376
- """
377
- Main class providing the keywords and core logic to interact with an OpenAPI server.
378
-
379
- Visit the [https://github.com/MarketSquare/robotframework-openapi-libcore | library page]
380
- for an introduction.
381
- """
382
-
383
- def __init__( # pylint: disable=too-many-arguments, too-many-locals, dangerous-default-value
384
- self,
385
- source: str,
386
- origin: str = "",
387
- base_path: str = "",
388
- mappings_path: Union[str, Path] = "",
389
- invalid_property_default_response: int = 422,
390
- default_id_property_name: str = "id",
391
- faker_locale: Optional[Union[str, List[str]]] = None,
392
- recursion_limit: int = 1,
393
- recursion_default: Any = {},
394
- username: str = "",
395
- password: str = "",
396
- security_token: str = "",
397
- auth: Optional[AuthBase] = None,
398
- cert: Optional[Union[str, Tuple[str, str]]] = None,
399
- verify_tls: Optional[Union[bool, str]] = True,
400
- extra_headers: Optional[Dict[str, str]] = None,
401
- cookies: Optional[Union[Dict[str, str], CookieJar]] = None,
402
- proxies: Optional[Dict[str, str]] = None,
403
- ) -> None:
404
- """
405
- == Base parameters ==
406
-
407
- === source ===
408
- An absolute path to an openapi.json or openapi.yaml file or an url to such a file.
409
-
410
- === origin ===
411
- The server (and port) of the target server. E.g. ``https://localhost:8000``
412
-
413
- === base_path ===
414
- The routing between ``origin`` and the endpoints as found in the ``paths``
415
- section in the openapi document.
416
- E.g. ``/petshop/v2``.
417
-
418
- == API-specific configurations ==
419
-
420
- === mappings_path ===
421
- See [https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html | this page]
422
- for an in-depth explanation.
423
-
424
- === invalid_property_default_response ===
425
- The default response code for requests with a JSON body that does not comply
426
- with the schema.
427
- Example: a value outside the specified range or a string value
428
- for a property defined as integer in the schema.
429
-
430
- === default_id_property_name ===
431
- The default name for the property that identifies a resource (i.e. a unique
432
- entity) within the API.
433
- The default value for this property name is ``id``.
434
- If the target API uses a different name for all the resources within the API,
435
- you can configure it globally using this property.
436
-
437
- If different property names are used for the unique identifier for different
438
- types of resources, an ``ID_MAPPING`` can be implemented using the ``mappings_path``.
439
-
440
- === faker_locale ===
441
- A locale string or list of locale strings to pass to the Faker library to be
442
- used in generation of string data for supported format types.
443
-
444
- == Parsing parameters ==
445
-
446
- === recursion_limit ===
447
- The recursion depth to which to fully parse recursive references before the
448
- `recursion_default` is used to end the recursion.
449
-
450
- === recursion_default ===
451
- The value that is used instead of the referenced schema when the
452
- `recursion_limit` has been reached.
453
- The default `{}` represents an empty object in JSON.
454
- Depending on schema definitions, this may cause schema validation errors.
455
- If this is the case, 'None' (``${NONE}`` in Robot Framework) or an empty list
456
- can be tried as an alternative.
457
-
458
- == Security-related parameters ==
459
- _Note: these parameters are equivalent to those in the ``requests`` library._
460
-
461
- === username ===
462
- The username to be used for Basic Authentication.
463
-
464
- === password ===
465
- The password to be used for Basic Authentication.
466
-
467
- === security_token ===
468
- The token to be used for token based security using the ``Authorization`` header.
469
-
470
- === auth ===
471
- A [https://requests.readthedocs.io/en/latest/api/#authentication | requests ``AuthBase`` instance]
472
- to be used for authentication instead of the ``username`` and ``password``.
473
-
474
- === cert ===
475
- The SSL certificate to use with all requests.
476
- If string: the path to ssl client cert file (.pem).
477
- If tuple: the ('cert', 'key') pair.
478
-
479
- === verify_tls ===
480
- Whether or not to verify the TLS / SSL certificate of the server.
481
- If boolean: whether or not to verify the server TLS certificate.
482
- If string: path to a CA bundle to use for verification.
483
-
484
- === extra_headers ===
485
- A dictionary with extra / custom headers that will be send with every request.
486
- This parameter can be used to send headers that are not documented in the
487
- openapi document or to provide an API-key.
488
-
489
- === cookies ===
490
- A dictionary or
491
- [https://docs.python.org/3/library/http.cookiejar.html#http.cookiejar.CookieJar | CookieJar object]
492
- to send with all requests.
493
-
494
- === proxies ===
495
- A dictionary of 'protocol': 'proxy url' to use for all requests.
496
- """
497
- self._source = source
498
- self._origin = origin
499
- self._base_path = base_path
500
- self._recursion_limit = recursion_limit
501
- self._recursion_default = recursion_default
502
- self.session = Session()
503
- # only username and password, security_token or auth object should be provided
504
- # if multiple are provided, username and password take precedence
505
- self.security_token = security_token
506
- self.auth = auth
507
- if username and password:
508
- self.auth = HTTPBasicAuth(username, password)
509
- # Robot Framework does not allow users to create tuples and requests
510
- # does not accept lists, so perform the conversion here
511
- if isinstance(cert, list):
512
- cert = tuple(cert)
513
- self.cert = cert
514
- self.verify = verify_tls
515
- self.extra_headers = extra_headers
516
- self.cookies = cookies
517
- self.proxies = proxies
518
- self.invalid_property_default_response = invalid_property_default_response
519
- if mappings_path and str(mappings_path) != ".":
520
- mappings_path = Path(mappings_path)
521
- if not mappings_path.is_file():
522
- logger.warning(
523
- f"mappings_path '{mappings_path}' is not a Python module."
524
- )
525
- # intermediate variable to ensure path.append is possible so we'll never
526
- # path.pop a location that we didn't append
527
- mappings_folder = str(mappings_path.parent)
528
- sys.path.append(mappings_folder)
529
- mappings_module_name = mappings_path.stem
530
- self.get_dto_class = get_dto_class(
531
- mappings_module_name=mappings_module_name
532
- )
533
- self.get_id_property_name = get_id_property_name(
534
- mappings_module_name=mappings_module_name
535
- )
536
- sys.path.pop()
537
- else:
538
- self.get_dto_class = get_dto_class(mappings_module_name="no mapping")
539
- self.get_id_property_name = get_id_property_name(
540
- mappings_module_name="no mapping"
541
- )
542
- if faker_locale:
543
- FAKE.set_locale(locale=faker_locale)
544
- # update the globally available DEFAULT_ID_PROPERTY_NAME to the provided value
545
- DEFAULT_ID_PROPERTY_NAME.id_property_name = default_id_property_name
546
-
547
- @property
548
- def origin(self) -> str:
549
- return self._origin
550
-
551
- @keyword
552
- def set_origin(self, origin: str) -> None:
553
- """
554
- Update the `origin` after the library is imported.
555
-
556
- This can be done during the `Suite setup` when using DataDriver in situations
557
- where the OpenAPI document is available on disk but the target host address is
558
- not known before the test starts.
559
-
560
- In combination with OpenApiLibCore, the `origin` can be used at any point to
561
- target another server that hosts an API that complies to the same OAS.
562
- """
563
- self._origin = origin
564
-
565
- @property
566
- def base_url(self) -> str:
567
- return f"{self.origin}{self._base_path}"
568
-
569
- @cached_property
570
- def validation_spec(self) -> Spec:
571
- return Spec.from_dict(self.openapi_spec)
572
-
573
- @property
574
- def openapi_spec(self) -> Dict[str, Any]:
575
- """Return a deepcopy of the parsed openapi document."""
576
- # protect the parsed openapi spec from being mutated by reference
577
- return deepcopy(self._openapi_spec)
578
-
579
- @cached_property
580
- def _openapi_spec(self) -> Dict[str, Any]:
581
- parser = self._load_parser()
582
- return parser.specification
583
-
584
- def _load_parser(self) -> ResolvingParser:
585
- try:
586
-
587
- def recursion_limit_handler(
588
- limit: int, refstring: str, recursions: Any
589
- ) -> Any:
590
- return self._recursion_default
591
-
592
- # Since parsing of the OAS and creating the Spec can take a long time,
593
- # they are cached. This is done by storing them in an imported module that
594
- # will have a global scope due to how the Python import system works. This
595
- # ensures that in a Suite of Suites where multiple Suites use the same
596
- # `source`, that OAS is only parsed / loaded once.
597
- parser = PARSER_CACHE.get(self._source, None)
598
- if parser is None:
599
- parser = ResolvingParser(
600
- self._source,
601
- backend="openapi-spec-validator",
602
- recursion_limit=self._recursion_limit,
603
- recursion_limit_handler=recursion_limit_handler,
604
- )
605
-
606
- if parser.specification is None: # pragma: no cover
607
- BuiltIn().fatal_error(
608
- "Source was loaded, but no specification was present after parsing."
609
- )
610
-
611
- PARSER_CACHE[self._source] = parser
612
-
613
- return parser
614
-
615
- except ResolutionError as exception:
616
- BuiltIn().fatal_error(
617
- f"ResolutionError while trying to load openapi spec: {exception}"
618
- )
619
- except ValidationError as exception:
620
- BuiltIn().fatal_error(
621
- f"ValidationError while trying to load openapi spec: {exception}"
622
- )
623
-
624
- def validate_response_vs_spec(
625
- self, request: RequestsOpenAPIRequest, response: RequestsOpenAPIResponse
626
- ) -> None:
627
- """
628
- Validate the reponse for a given request against the OpenAPI Spec that is
629
- loaded during library initialization.
630
- """
631
- _ = validate_response(
632
- spec=self.validation_spec,
633
- request=request,
634
- response=response,
635
- )
636
-
637
- @keyword
638
- def get_valid_url(self, endpoint: str, method: str) -> str:
639
- """
640
- This keyword returns a valid url for the given `endpoint` and `method`.
641
-
642
- If the `endpoint` contains path parameters the Get Valid Id For Endpoint
643
- keyword will be executed to retrieve valid ids for the path parameters.
644
-
645
- > Note: if valid ids cannot be retrieved within the scope of the API, the
646
- `PathPropertiesConstraint` Relation can be used. More information can be found
647
- [https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html | here].
648
- """
649
- method = method.lower()
650
- try:
651
- # endpoint can be partially resolved or provided by a PathPropertiesConstraint
652
- parametrized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
653
- _ = self.openapi_spec["paths"][parametrized_endpoint]
654
- except KeyError:
655
- raise ValueError(
656
- f"{endpoint} not found in paths section of the OpenAPI document."
657
- ) from None
658
- dto_class = self.get_dto_class(endpoint=endpoint, method=method)
659
- relations = dto_class.get_relations()
660
- paths = [p.path for p in relations if isinstance(p, PathPropertiesConstraint)]
661
- if paths:
662
- url = f"{self.base_url}{choice(paths)}"
663
- return url
664
- endpoint_parts = list(endpoint.split("/"))
665
- for index, part in enumerate(endpoint_parts):
666
- if part.startswith("{") and part.endswith("}"):
667
- type_endpoint_parts = endpoint_parts[slice(index)]
668
- type_endpoint = "/".join(type_endpoint_parts)
669
- existing_id: Union[str, int, float] = run_keyword(
670
- "get_valid_id_for_endpoint", type_endpoint, method
671
- )
672
- endpoint_parts[index] = str(existing_id)
673
- resolved_endpoint = "/".join(endpoint_parts)
674
- url = f"{self.base_url}{resolved_endpoint}"
675
- return url
676
-
677
- @keyword
678
- def get_valid_id_for_endpoint(
679
- self, endpoint: str, method: str
680
- ) -> Union[str, int, float]:
681
- """
682
- Support keyword that returns the `id` for an existing resource at `endpoint`.
683
-
684
- To prevent resource conflicts with other test cases, a new resource is created
685
- (POST) if possible.
686
- """
687
-
688
- def dummy_transformer(
689
- valid_id: Union[str, int, float]
690
- ) -> Union[str, int, float]:
691
- return valid_id
692
-
693
- method = method.lower()
694
- url: str = run_keyword("get_valid_url", endpoint, method)
695
- # Try to create a new resource to prevent conflicts caused by
696
- # operations performed on the same resource by other test cases
697
- request_data = self.get_request_data(endpoint=endpoint, method="post")
698
-
699
- response: Response = run_keyword(
700
- "authorized_request",
701
- url,
702
- "post",
703
- request_data.get_required_params(),
704
- request_data.get_required_headers(),
705
- request_data.get_required_properties_dict(),
706
- )
707
-
708
- # determine the id property name for this path and whether or not a transformer is used
709
- mapping = self.get_id_property_name(endpoint=endpoint)
710
- if isinstance(mapping, str):
711
- id_property = mapping
712
- # set the transformer to a dummy callable that returns the original value so
713
- # the transformer can be applied on any returned id
714
- id_transformer = dummy_transformer
715
- else:
716
- id_property, id_transformer = mapping
717
-
718
- if not response.ok:
719
- # If a new resource cannot be created using POST, try to retrieve a
720
- # valid id using a GET request.
721
- try:
722
- valid_id = choice(run_keyword("get_ids_from_url", url))
723
- return id_transformer(valid_id)
724
- except Exception as exception:
725
- raise AssertionError(
726
- f"Failed to get a valid id using GET on {url}"
727
- ) from exception
728
-
729
- response_data = response.json()
730
- if prepared_body := response.request.body:
731
- if isinstance(prepared_body, bytes):
732
- send_json = _json.loads(prepared_body.decode("UTF-8"))
733
- else:
734
- send_json = _json.loads(prepared_body)
735
- else:
736
- send_json = None
737
-
738
- # no support for retrieving an id from an array returned on a POST request
739
- if isinstance(response_data, list):
740
- raise NotImplementedError(
741
- f"Unexpected response body for POST request: expected an object but "
742
- f"received an array ({response_data})"
743
- )
744
-
745
- # POST on /resource_type/{id}/array_item/ will return the updated {id} resource
746
- # instead of a newly created resource. In this case, the send_json must be
747
- # in the array of the 'array_item' property on {id}
748
- send_path: str = response.request.path_url
749
- response_href: Optional[str] = response_data.get("href", None)
750
- if response_href and (send_path not in response_href) and send_json:
751
- try:
752
- property_to_check = send_path.replace(response_href, "")[1:]
753
- item_list: List[Dict[str, Any]] = response_data[property_to_check]
754
- # Use the (mandatory) id to get the POSTed resource from the list
755
- [valid_id] = [
756
- item[id_property]
757
- for item in item_list
758
- if item[id_property] == send_json[id_property]
759
- ]
760
- except Exception as exception:
761
- raise AssertionError(
762
- f"Failed to get a valid id from {response_href}"
763
- ) from exception
764
- else:
765
- try:
766
- valid_id = response_data[id_property]
767
- except KeyError:
768
- raise AssertionError(
769
- f"Failed to get a valid id from {response_data}"
770
- ) from None
771
- return id_transformer(valid_id)
772
-
773
- @keyword
774
- def get_ids_from_url(self, url: str) -> List[str]:
775
- """
776
- Perform a GET request on the `url` and return the list of resource
777
- `ids` from the response.
778
- """
779
- endpoint = self.get_parameterized_endpoint_from_url(url)
780
- request_data = self.get_request_data(endpoint=endpoint, method="get")
781
- response = run_keyword(
782
- "authorized_request",
783
- url,
784
- "get",
785
- request_data.get_required_params(),
786
- request_data.get_required_headers(),
787
- )
788
- response.raise_for_status()
789
- response_data: Union[Dict[str, Any], List[Dict[str, Any]]] = response.json()
790
-
791
- # determine the property name to use
792
- mapping = self.get_id_property_name(endpoint=endpoint)
793
- if isinstance(mapping, str):
794
- id_property = mapping
795
- else:
796
- id_property, _ = mapping
797
-
798
- if isinstance(response_data, list):
799
- valid_ids: List[str] = [item[id_property] for item in response_data]
800
- return valid_ids
801
- # if the response is an object (dict), check if it's hal+json
802
- if embedded := response_data.get("_embedded"):
803
- # there should be 1 item in the dict that has a value that's a list
804
- for value in embedded.values():
805
- if isinstance(value, list):
806
- valid_ids = [item[id_property] for item in value]
807
- return valid_ids
808
- if (valid_id := response_data.get(id_property)) is not None:
809
- return [valid_id]
810
- valid_ids = [item[id_property] for item in response_data["items"]]
811
- return valid_ids
812
-
813
- @keyword
814
- def get_request_data(self, endpoint: str, method: str) -> RequestData:
815
- """Return an object with valid request data for body, headers and query params."""
816
- method = method.lower()
817
- dto_cls_name = self._get_dto_cls_name(endpoint=endpoint, method=method)
818
- # The endpoint can contain already resolved Ids that have to be matched
819
- # against the parametrized endpoints in the paths section.
820
- spec_endpoint = self.get_parametrized_endpoint(endpoint)
821
- dto_class = self.get_dto_class(endpoint=spec_endpoint, method=method)
822
- try:
823
- method_spec = self.openapi_spec["paths"][spec_endpoint][method]
824
- except KeyError:
825
- logger.info(
826
- f"method '{method}' not supported on '{spec_endpoint}, using empty spec."
827
- )
828
- method_spec = {}
829
-
830
- parameters, params, headers = self.get_request_parameters(
831
- dto_class=dto_class, method_spec=method_spec
832
- )
833
- if (body_spec := method_spec.get("requestBody", None)) is None:
834
- if dto_class == DefaultDto:
835
- dto_instance: Dto = DefaultDto()
836
- else:
837
- dto_class = make_dataclass(
838
- cls_name=method_spec.get("operationId", dto_cls_name),
839
- fields=[],
840
- bases=(dto_class,),
841
- )
842
- dto_instance = dto_class()
843
- return RequestData(
844
- dto=dto_instance,
845
- parameters=parameters,
846
- params=params,
847
- headers=headers,
848
- )
849
- content_schema = resolve_schema(self.get_content_schema(body_spec))
850
- dto_data = self.get_json_data_for_dto_class(
851
- schema=content_schema,
852
- dto_class=dto_class,
853
- operation_id=method_spec.get("operationId", ""),
854
- )
855
- if dto_data is None:
856
- dto_instance = DefaultDto()
857
- else:
858
- fields = self.get_fields_from_dto_data(content_schema, dto_data)
859
- dto_class = make_dataclass(
860
- cls_name=method_spec.get("operationId", dto_cls_name),
861
- fields=fields,
862
- bases=(dto_class,),
863
- )
864
- dto_data = {get_safe_key(key): value for key, value in dto_data.items()}
865
- dto_instance = dto_class(**dto_data)
866
- return RequestData(
867
- dto=dto_instance,
868
- dto_schema=content_schema,
869
- parameters=parameters,
870
- params=params,
871
- headers=headers,
872
- )
873
-
874
- @staticmethod
875
- def _get_dto_cls_name(endpoint: str, method: str) -> str:
876
- method = method.capitalize()
877
- path = endpoint.translate({ord(i): None for i in "{}"})
878
- path_parts = path.split("/")
879
- path_parts = [p.capitalize() for p in path_parts]
880
- result = "".join([method, *path_parts])
881
- return result
882
-
883
- @staticmethod
884
- def get_fields_from_dto_data(
885
- content_schema: Dict[str, Any], dto_data: Dict[str, Any]
886
- ):
887
- # FIXME: annotation is not Pyhon 3.8-compatible
888
- # ) -> List[Union[str, Tuple[str, Type[Any]], Tuple[str, Type[Any], Field[Any]]]]:
889
- """Get a dataclasses fields list based on the content_schema and dto_data."""
890
- fields: List[
891
- Union[str, Tuple[str, Type[Any]], Tuple[str, Type[Any], Field[Any]]]
892
- ] = []
893
- for key, value in dto_data.items():
894
- required_properties = content_schema.get("required", [])
895
- safe_key = get_safe_key(key)
896
- metadata = {"original_property_name": key}
897
- if key in required_properties:
898
- # The fields list is used to create a dataclass, so non-default fields
899
- # must go before fields with a default
900
- fields.insert(0, (safe_key, type(value), field(metadata=metadata)))
901
- else:
902
- fields.append((safe_key, type(value), field(default=None, metadata=metadata))) # type: ignore[arg-type]
903
- return fields
904
-
905
- def get_request_parameters(
906
- self, dto_class: Union[Dto, Type[Dto]], method_spec: Dict[str, Any]
907
- ) -> Tuple[List[Dict[str, Any]], Dict[str, Any], Dict[str, str]]:
908
- """Get the methods parameter spec and params and headers with valid data."""
909
- parameters = method_spec.get("parameters", [])
910
- parameter_relations = dto_class.get_parameter_relations()
911
- query_params = [p for p in parameters if p.get("in") == "query"]
912
- header_params = [p for p in parameters if p.get("in") == "header"]
913
- params = self.get_parameter_data(query_params, parameter_relations)
914
- headers = self.get_parameter_data(header_params, parameter_relations)
915
- return parameters, params, headers
916
-
917
- @staticmethod
918
- def get_content_schema(body_spec: Dict[str, Any]) -> Dict[str, Any]:
919
- """Get the content schema from the requestBody spec."""
920
- content_types = body_spec["content"].keys()
921
- if "application/json" not in content_types:
922
- # At present no supported for other types.
923
- raise NotImplementedError(
924
- f"Only content type 'application/json' is supported. "
925
- f"Content types definded in the spec are '{content_types}'."
926
- )
927
- content_schema = body_spec["content"]["application/json"]["schema"]
928
- return resolve_schema(content_schema)
929
-
930
- def get_parametrized_endpoint(self, endpoint: str) -> str:
931
- """
932
- Get the parametrized endpoint as found in the `paths` section of the openapi
933
- document from a (partially) resolved endpoint.
934
- """
935
-
936
- def match_parts(parts: List[str], spec_parts: List[str]) -> bool:
937
- for part, spec_part in zip_longest(parts, spec_parts, fillvalue="Filler"):
938
- if part == "Filler" or spec_part == "Filler":
939
- return False
940
- if part != spec_part and not spec_part.startswith("{"):
941
- return False
942
- return True
943
-
944
- endpoint_parts = endpoint.split("/")
945
- # if the last part is empty, the path has a trailing `/` that
946
- # should be ignored during matching
947
- if endpoint_parts[-1] == "":
948
- _ = endpoint_parts.pop(-1)
949
-
950
- spec_endpoints: List[str] = {**self.openapi_spec}["paths"].keys()
951
-
952
- candidates: List[str] = []
953
-
954
- for spec_endpoint in spec_endpoints:
955
- spec_endpoint_parts = spec_endpoint.split("/")
956
- # ignore trailing `/` the same way as for endpoint_parts
957
- if spec_endpoint_parts[-1] == "":
958
- _ = spec_endpoint_parts.pop(-1)
959
- if match_parts(endpoint_parts, spec_endpoint_parts):
960
- candidates.append(spec_endpoint)
961
-
962
- if not candidates:
963
- raise ValueError(
964
- f"{endpoint} not found in paths section of the OpenAPI document."
965
- )
966
-
967
- if len(candidates) == 1:
968
- return candidates[0]
969
- # Multiple matches can happen in APIs with overloaded endpoints, e.g.
970
- # /users/me
971
- # /users/${user_id}
972
- # In this case, find the closest (or exact) match
973
- exact_match = [c for c in candidates if c == endpoint]
974
- if exact_match:
975
- return exact_match[0]
976
- # TODO: Implement a decision mechanism when real-world examples become available
977
- # In the face of ambiguity, refuse the temptation to guess.
978
- raise ValueError(f"{endpoint} matched to multiple paths: {candidates}")
979
-
980
- @staticmethod
981
- def get_parameter_data(
982
- parameters: List[Dict[str, Any]],
983
- parameter_relations: List[Relation],
984
- ) -> Dict[str, str]:
985
- """Generate a valid list of key-value pairs for all parameters."""
986
- result: Dict[str, str] = {}
987
- value: Any = None
988
- for parameter in parameters:
989
- parameter_name = parameter["name"]
990
- parameter_schema = resolve_schema(parameter["schema"])
991
- relations = [
992
- r for r in parameter_relations if r.property_name == parameter_name
993
- ]
994
- if constrained_values := [
995
- r.values for r in relations if isinstance(r, PropertyValueConstraint)
996
- ]:
997
- value = choice(*constrained_values)
998
- if value is IGNORE:
999
- continue
1000
- result[parameter_name] = value
1001
- continue
1002
- value = value_utils.get_valid_value(parameter_schema)
1003
- result[parameter_name] = value
1004
- return result
1005
-
1006
- @keyword
1007
- def get_json_data_for_dto_class(
1008
- self,
1009
- schema: Dict[str, Any],
1010
- dto_class: Union[Dto, Type[Dto]],
1011
- operation_id: str = "",
1012
- ) -> Optional[Dict[str, Any]]:
1013
- """
1014
- Generate a valid (json-compatible) dict for all the `dto_class` properties.
1015
- """
1016
-
1017
- def get_constrained_values(property_name: str) -> List[Any]:
1018
- relations = dto_class.get_relations()
1019
- values_list = [
1020
- c.values
1021
- for c in relations
1022
- if (
1023
- isinstance(c, PropertyValueConstraint)
1024
- and c.property_name == property_name
1025
- )
1026
- ]
1027
- # values should be empty or contain 1 list of allowed values
1028
- return values_list.pop() if values_list else []
1029
-
1030
- def get_dependent_id(
1031
- property_name: str, operation_id: str
1032
- ) -> Optional[Union[str, int, float]]:
1033
- relations = dto_class.get_relations()
1034
- # multiple get paths are possible based on the operation being performed
1035
- id_get_paths = [
1036
- (d.get_path, d.operation_id)
1037
- for d in relations
1038
- if (isinstance(d, IdDependency) and d.property_name == property_name)
1039
- ]
1040
- if not id_get_paths:
1041
- return None
1042
- if len(id_get_paths) == 1:
1043
- id_get_path, _ = id_get_paths.pop()
1044
- else:
1045
- try:
1046
- [id_get_path] = [
1047
- path
1048
- for path, operation in id_get_paths
1049
- if operation == operation_id
1050
- ]
1051
- # There could be multiple get_paths, but not one for the current operation
1052
- except ValueError:
1053
- return None
1054
- valid_id = self.get_valid_id_for_endpoint(
1055
- endpoint=id_get_path, method="get"
1056
- )
1057
- logger.debug(f"get_dependent_id for {id_get_path} returned {valid_id}")
1058
- return valid_id
1059
-
1060
- json_data: Dict[str, Any] = {}
1061
-
1062
- for property_name in schema.get("properties", []):
1063
- properties_schema = schema["properties"][property_name]
1064
-
1065
- property_type = properties_schema.get("type")
1066
- if not property_type:
1067
- selected_type_schema = choice(properties_schema["types"])
1068
- property_type = selected_type_schema["type"]
1069
- if properties_schema.get("readOnly", False):
1070
- continue
1071
- if constrained_values := get_constrained_values(property_name):
1072
- # do not add properties that are configured to be ignored
1073
- if IGNORE in constrained_values:
1074
- continue
1075
- json_data[property_name] = choice(constrained_values)
1076
- continue
1077
- if (
1078
- dependent_id := get_dependent_id(
1079
- property_name=property_name, operation_id=operation_id
1080
- )
1081
- ) is not None:
1082
- json_data[property_name] = dependent_id
1083
- continue
1084
- if property_type == "object":
1085
- object_data = self.get_json_data_for_dto_class(
1086
- schema=properties_schema,
1087
- dto_class=DefaultDto,
1088
- operation_id="",
1089
- )
1090
- json_data[property_name] = object_data
1091
- continue
1092
- if property_type == "array":
1093
- array_data = self.get_json_data_for_dto_class(
1094
- schema=properties_schema["items"],
1095
- dto_class=DefaultDto,
1096
- operation_id=operation_id,
1097
- )
1098
- json_data[property_name] = [array_data]
1099
- continue
1100
- json_data[property_name] = value_utils.get_valid_value(properties_schema)
1101
- return json_data
1102
-
1103
- @keyword
1104
- def get_invalidated_url(self, valid_url: str) -> Optional[str]:
1105
- """
1106
- Return an url with all the path parameters in the `valid_url` replaced by a
1107
- random UUID.
1108
-
1109
- Raises ValueError if the valid_url cannot be invalidated.
1110
- """
1111
- parameterized_endpoint = self.get_parameterized_endpoint_from_url(valid_url)
1112
- parameterized_url = self.base_url + parameterized_endpoint
1113
- valid_url_parts = list(reversed(valid_url.split("/")))
1114
- parameterized_parts = reversed(parameterized_url.split("/"))
1115
- for index, (parameterized_part, _) in enumerate(
1116
- zip(parameterized_parts, valid_url_parts)
1117
- ):
1118
- if parameterized_part.startswith("{") and parameterized_part.endswith("}"):
1119
- valid_url_parts[index] = uuid4().hex
1120
- valid_url_parts.reverse()
1121
- invalid_url = "/".join(valid_url_parts)
1122
- return invalid_url
1123
- raise ValueError(f"{parameterized_endpoint} could not be invalidated.")
1124
-
1125
- @keyword
1126
- def get_parameterized_endpoint_from_url(self, url: str) -> str:
1127
- """
1128
- Return the endpoint as found in the `paths` section based on the given `url`.
1129
- """
1130
- endpoint = url.replace(self.base_url, "")
1131
- endpoint_parts = endpoint.split("/")
1132
- # first part will be '' since an endpoint starts with /
1133
- endpoint_parts.pop(0)
1134
- parameterized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
1135
- return parameterized_endpoint
1136
-
1137
- @keyword
1138
- def get_invalid_json_data(
1139
- self,
1140
- url: str,
1141
- method: str,
1142
- status_code: int,
1143
- request_data: RequestData,
1144
- ) -> Dict[str, Any]:
1145
- """
1146
- Return `json_data` based on the `dto` on the `request_data` that will cause
1147
- the provided `status_code` for the `method` operation on the `url`.
1148
-
1149
- > Note: applicable UniquePropertyValueConstraint and IdReference Relations are
1150
- considered before changes to `json_data` are made.
1151
- """
1152
- method = method.lower()
1153
- data_relations = request_data.dto.get_relations_for_error_code(status_code)
1154
- if not data_relations:
1155
- if not request_data.dto_schema:
1156
- raise ValueError(
1157
- "Failed to invalidate: no data_relations and empty schema."
1158
- )
1159
- json_data = request_data.dto.get_invalidated_data(
1160
- schema=request_data.dto_schema,
1161
- status_code=status_code,
1162
- invalid_property_default_code=self.invalid_property_default_response,
1163
- )
1164
- return json_data
1165
- resource_relation = choice(data_relations)
1166
- if isinstance(resource_relation, UniquePropertyValueConstraint):
1167
- json_data = run_keyword(
1168
- "get_json_data_with_conflict",
1169
- url,
1170
- method,
1171
- request_data.dto,
1172
- status_code,
1173
- )
1174
- elif isinstance(resource_relation, IdReference):
1175
- run_keyword("ensure_in_use", url, resource_relation)
1176
- json_data = request_data.dto.as_dict()
1177
- else:
1178
- json_data = request_data.dto.get_invalidated_data(
1179
- schema=request_data.dto_schema,
1180
- status_code=status_code,
1181
- invalid_property_default_code=self.invalid_property_default_response,
1182
- )
1183
- return json_data
1184
-
1185
- @keyword
1186
- def get_invalidated_parameters(
1187
- self,
1188
- status_code: int,
1189
- request_data: RequestData,
1190
- ) -> Tuple[Dict[str, Any], Dict[str, str]]:
1191
- """
1192
- Returns a version of `params, headers` as present on `request_data` that has
1193
- been modified to cause the provided `status_code`.
1194
- """
1195
- if not request_data.parameters:
1196
- raise ValueError("No params or headers to invalidate.")
1197
-
1198
- # ensure the status_code can be triggered
1199
- relations = request_data.dto.get_parameter_relations_for_error_code(status_code)
1200
- relations_for_status_code = [
1201
- r
1202
- for r in relations
1203
- if isinstance(r, PropertyValueConstraint)
1204
- and (
1205
- r.error_code == status_code or r.invalid_value_error_code == status_code
1206
- )
1207
- ]
1208
- parameters_to_ignore = {
1209
- r.property_name
1210
- for r in relations_for_status_code
1211
- if r.invalid_value_error_code == status_code and r.invalid_value == IGNORE
1212
- }
1213
- relation_property_names = {r.property_name for r in relations_for_status_code}
1214
- if not relation_property_names:
1215
- if status_code != self.invalid_property_default_response:
1216
- raise ValueError(
1217
- f"No relations to cause status_code {status_code} found."
1218
- )
1219
-
1220
- # ensure we're not modifying mutable properties
1221
- params = deepcopy(request_data.params)
1222
- headers = deepcopy(request_data.headers)
1223
-
1224
- if status_code == self.invalid_property_default_response:
1225
- # take the params and headers that can be invalidated based on data type
1226
- # and expand the set with properties that can be invalided by relations
1227
- parameter_names = set(request_data.params_that_can_be_invalidated).union(
1228
- request_data.headers_that_can_be_invalidated
1229
- )
1230
- parameter_names.update(relation_property_names)
1231
- if not parameter_names:
1232
- raise ValueError(
1233
- "None of the query parameters and headers can be invalidated."
1234
- )
1235
- else:
1236
- # non-default status_codes can only be the result of a Relation
1237
- parameter_names = relation_property_names
1238
-
1239
- # Dto mappings may contain generic mappings for properties that are not present
1240
- # in this specific schema
1241
- request_data_parameter_names = [p.get("name") for p in request_data.parameters]
1242
- additional_relation_property_names = {
1243
- n for n in relation_property_names if n not in request_data_parameter_names
1244
- }
1245
- if additional_relation_property_names:
1246
- logger.warning(
1247
- f"get_parameter_relations_for_error_code yielded properties that are "
1248
- f"not defined in the schema: {additional_relation_property_names}\n"
1249
- f"These properties will be ignored for parameter invalidation."
1250
- )
1251
- parameter_names = parameter_names - additional_relation_property_names
1252
-
1253
- if not parameter_names:
1254
- raise ValueError(
1255
- f"No parameter can be changed to cause status_code {status_code}."
1256
- )
1257
-
1258
- parameter_names = parameter_names - parameters_to_ignore
1259
- parameter_to_invalidate = choice(tuple(parameter_names))
1260
-
1261
- # check for invalid parameters in the provided request_data
1262
- try:
1263
- [parameter_data] = [
1264
- data
1265
- for data in request_data.parameters
1266
- if data["name"] == parameter_to_invalidate
1267
- ]
1268
- except Exception:
1269
- raise ValueError(
1270
- f"{parameter_to_invalidate} not found in provided parameters."
1271
- ) from None
1272
-
1273
- # get the invalid_value for the chosen parameter
1274
- try:
1275
- [invalid_value_for_error_code] = [
1276
- r.invalid_value
1277
- for r in relations_for_status_code
1278
- if r.property_name == parameter_to_invalidate
1279
- and r.invalid_value_error_code == status_code
1280
- ]
1281
- except ValueError:
1282
- invalid_value_for_error_code = NOT_SET
1283
-
1284
- # get the constraint values if available for the chosen parameter
1285
- try:
1286
- [values_from_constraint] = [
1287
- r.values
1288
- for r in relations_for_status_code
1289
- if r.property_name == parameter_to_invalidate
1290
- ]
1291
- except ValueError:
1292
- values_from_constraint = []
1293
-
1294
- # if the parameter was not provided, add it to params / headers
1295
- params, headers = self.ensure_parameter_in_parameters(
1296
- parameter_to_invalidate=parameter_to_invalidate,
1297
- params=params,
1298
- headers=headers,
1299
- parameter_data=parameter_data,
1300
- values_from_constraint=values_from_constraint,
1301
- )
1302
-
1303
- # determine the invalid_value
1304
- if invalid_value_for_error_code != NOT_SET:
1305
- invalid_value = invalid_value_for_error_code
1306
- else:
1307
- if parameter_to_invalidate in params.keys():
1308
- valid_value = params[parameter_to_invalidate]
1309
- else:
1310
- valid_value = headers[parameter_to_invalidate]
1311
-
1312
- value_schema = resolve_schema(parameter_data["schema"])
1313
- invalid_value = value_utils.get_invalid_value(
1314
- value_schema=value_schema,
1315
- current_value=valid_value,
1316
- values_from_constraint=values_from_constraint,
1317
- )
1318
- logger.debug(f"{parameter_to_invalidate} changed to {invalid_value}")
1319
-
1320
- # update the params / headers and return
1321
- if parameter_to_invalidate in params.keys():
1322
- params[parameter_to_invalidate] = invalid_value
1323
- else:
1324
- headers[parameter_to_invalidate] = invalid_value
1325
- return params, headers
1326
-
1327
- @staticmethod
1328
- def ensure_parameter_in_parameters(
1329
- parameter_to_invalidate: str,
1330
- params: Dict[str, Any],
1331
- headers: Dict[str, str],
1332
- parameter_data: Dict[str, Any],
1333
- values_from_constraint: List[Any],
1334
- ) -> Tuple[Dict[str, Any], Dict[str, str]]:
1335
- """
1336
- Returns the params, headers tuple with parameter_to_invalidate with a valid
1337
- value to params or headers if not originally present.
1338
- """
1339
- if (
1340
- parameter_to_invalidate not in params.keys()
1341
- and parameter_to_invalidate not in headers.keys()
1342
- ):
1343
- if values_from_constraint:
1344
- valid_value = choice(values_from_constraint)
1345
- else:
1346
- parameter_schema = resolve_schema(parameter_data["schema"])
1347
- valid_value = value_utils.get_valid_value(parameter_schema)
1348
- if (
1349
- parameter_data["in"] == "query"
1350
- and parameter_to_invalidate not in params.keys()
1351
- ):
1352
- params[parameter_to_invalidate] = valid_value
1353
- if (
1354
- parameter_data["in"] == "header"
1355
- and parameter_to_invalidate not in headers.keys()
1356
- ):
1357
- headers[parameter_to_invalidate] = valid_value
1358
- return params, headers
1359
-
1360
- @keyword
1361
- def ensure_in_use(self, url: str, resource_relation: IdReference) -> None:
1362
- """
1363
- Ensure that the (right-most) `id` of the resource referenced by the `url`
1364
- is used by the resource defined by the `resource_relation`.
1365
- """
1366
- resource_id = ""
1367
-
1368
- endpoint = url.replace(self.base_url, "")
1369
- endpoint_parts = endpoint.split("/")
1370
- parameterized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
1371
- parameterized_endpoint_parts = parameterized_endpoint.split("/")
1372
- for part, param_part in zip(
1373
- reversed(endpoint_parts), reversed(parameterized_endpoint_parts)
1374
- ):
1375
- if param_part.endswith("}"):
1376
- resource_id = part
1377
- break
1378
- if not resource_id:
1379
- raise ValueError(f"The provided url ({url}) does not contain an id.")
1380
- request_data = self.get_request_data(
1381
- method="post", endpoint=resource_relation.post_path
1382
- )
1383
- json_data = request_data.dto.as_dict()
1384
- json_data[resource_relation.property_name] = resource_id
1385
- post_url: str = run_keyword(
1386
- "get_valid_url",
1387
- resource_relation.post_path,
1388
- "post",
1389
- )
1390
- response: Response = run_keyword(
1391
- "authorized_request",
1392
- post_url,
1393
- "post",
1394
- request_data.params,
1395
- request_data.headers,
1396
- json_data,
1397
- )
1398
- if not response.ok:
1399
- logger.debug(
1400
- f"POST on {post_url} with json {json_data} failed: {response.json()}"
1401
- )
1402
- response.raise_for_status()
1403
-
1404
- @keyword
1405
- def get_json_data_with_conflict(
1406
- self, url: str, method: str, dto: Dto, conflict_status_code: int
1407
- ) -> Dict[str, Any]:
1408
- """
1409
- Return `json_data` based on the `UniquePropertyValueConstraint` that must be
1410
- returned by the `get_relations` implementation on the `dto` for the given
1411
- `conflict_status_code`.
1412
- """
1413
- method = method.lower()
1414
- json_data = dto.as_dict()
1415
- unique_property_value_constraints = [
1416
- r
1417
- for r in dto.get_relations()
1418
- if isinstance(r, UniquePropertyValueConstraint)
1419
- ]
1420
- for relation in unique_property_value_constraints:
1421
- json_data[relation.property_name] = relation.value
1422
- # create a new resource that the original request will conflict with
1423
- if method in ["patch", "put"]:
1424
- post_url_parts = url.split("/")[:-1]
1425
- post_url = "/".join(post_url_parts)
1426
- # the PATCH or PUT may use a different dto than required for POST
1427
- # so a valid POST dto must be constructed
1428
- endpoint = post_url.replace(self.base_url, "")
1429
- request_data = self.get_request_data(endpoint=endpoint, method="post")
1430
- post_json = request_data.dto.as_dict()
1431
- for key in post_json.keys():
1432
- if key in json_data:
1433
- post_json[key] = json_data.get(key)
1434
- else:
1435
- post_url = url
1436
- post_json = json_data
1437
- endpoint = post_url.replace(self.base_url, "")
1438
- request_data = self.get_request_data(endpoint=endpoint, method="post")
1439
- response: Response = run_keyword(
1440
- "authorized_request",
1441
- post_url,
1442
- "post",
1443
- request_data.params,
1444
- request_data.headers,
1445
- post_json,
1446
- )
1447
- # conflicting resource may already exist
1448
- assert (
1449
- response.ok or response.status_code == conflict_status_code
1450
- ), f"get_json_data_with_conflict received {response.status_code}: {response.json()}"
1451
- return json_data
1452
- raise ValueError(
1453
- f"No UniquePropertyValueConstraint in the get_relations list on dto {dto}."
1454
- )
1455
-
1456
- @keyword
1457
- def authorized_request( # pylint: disable=too-many-arguments
1458
- self,
1459
- url: str,
1460
- method: str,
1461
- params: Optional[Dict[str, Any]] = None,
1462
- headers: Optional[Dict[str, str]] = None,
1463
- json_data: Optional[JSON] = None,
1464
- ) -> Response:
1465
- """
1466
- Perform a request using the security token or authentication set in the library.
1467
-
1468
- > Note: provided username / password or auth objects take precedence over token
1469
- based security
1470
- """
1471
- headers = headers if headers else {}
1472
- if self.extra_headers:
1473
- headers.update(self.extra_headers)
1474
- # if both an auth object and a token are available, auth takes precedence
1475
- if self.security_token and not self.auth:
1476
- security_header = {"Authorization": self.security_token}
1477
- headers.update(security_header)
1478
- headers = {k: str(v) for k, v in headers.items()}
1479
- response = self.session.request(
1480
- url=url,
1481
- method=method,
1482
- params=params,
1483
- headers=headers,
1484
- json=json_data,
1485
- cookies=self.cookies,
1486
- auth=self.auth,
1487
- proxies=self.proxies,
1488
- verify=self.verify,
1489
- cert=self.cert,
1490
- )
1491
- logger.debug(f"Response text: {response.text}")
1492
- return response
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
+ import json as _json
122
+ import re
123
+ import sys
124
+ from copy import deepcopy
125
+ from dataclasses import Field, dataclass, field, make_dataclass
126
+ from functools import cached_property
127
+ from itertools import zip_longest
128
+ from logging import getLogger
129
+ from pathlib import Path
130
+ from random import choice
131
+ from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union
132
+ from uuid import uuid4
133
+
134
+ from openapi_core import Config, OpenAPI, Spec
135
+ from openapi_core.contrib.requests import (
136
+ RequestsOpenAPIRequest,
137
+ RequestsOpenAPIResponse,
138
+ )
139
+ from prance import ResolvingParser, ValidationError
140
+ from prance.util.url import ResolutionError
141
+ from requests import Response, Session
142
+ from requests.auth import AuthBase, HTTPBasicAuth
143
+ from requests.cookies import RequestsCookieJar as CookieJar
144
+ from robot.api.deco import keyword, library
145
+ from robot.libraries.BuiltIn import BuiltIn
146
+
147
+ from OpenApiLibCore import value_utils
148
+ from OpenApiLibCore.dto_base import (
149
+ NOT_SET,
150
+ Dto,
151
+ IdDependency,
152
+ IdReference,
153
+ PathPropertiesConstraint,
154
+ PropertyValueConstraint,
155
+ Relation,
156
+ UniquePropertyValueConstraint,
157
+ resolve_schema,
158
+ )
159
+ from OpenApiLibCore.dto_utils import (
160
+ DEFAULT_ID_PROPERTY_NAME,
161
+ DefaultDto,
162
+ get_dto_class,
163
+ get_id_property_name,
164
+ )
165
+ from OpenApiLibCore.oas_cache import PARSER_CACHE
166
+ from OpenApiLibCore.value_utils import FAKE, IGNORE, JSON
167
+
168
+ run_keyword = BuiltIn().run_keyword
169
+
170
+ logger = getLogger(__name__)
171
+
172
+
173
+ def get_safe_key(key: str) -> str:
174
+ """
175
+ Helper function to convert a valid JSON property name to a string that can be used
176
+ as a Python variable or function / method name.
177
+ """
178
+ key = key.replace("-", "_")
179
+ key = key.replace("@", "_")
180
+ if key[0].isdigit():
181
+ key = f"_{key}"
182
+ return key
183
+
184
+
185
+ @dataclass
186
+ class RequestValues:
187
+ """Helper class to hold parameter values needed to make a request."""
188
+
189
+ url: str
190
+ method: str
191
+ params: Optional[Dict[str, Any]]
192
+ headers: Optional[Dict[str, str]]
193
+ json_data: Optional[Dict[str, Any]]
194
+
195
+
196
+ @dataclass
197
+ class RequestData:
198
+ """Helper class to manage parameters used when making requests."""
199
+
200
+ dto: Union[Dto, DefaultDto] = field(default_factory=DefaultDto)
201
+ dto_schema: Dict[str, Any] = field(default_factory=dict)
202
+ parameters: List[Dict[str, Any]] = field(default_factory=list)
203
+ params: Dict[str, Any] = field(default_factory=dict)
204
+ headers: Dict[str, Any] = field(default_factory=dict)
205
+ has_body: bool = True
206
+
207
+ def __post_init__(self) -> None:
208
+ # prevent modification by reference
209
+ self.dto_schema = deepcopy(self.dto_schema)
210
+ self.parameters = deepcopy(self.parameters)
211
+ self.params = deepcopy(self.params)
212
+ self.headers = deepcopy(self.headers)
213
+
214
+ @property
215
+ def has_optional_properties(self) -> bool:
216
+ """Whether or not the dto data (json data) contains optional properties."""
217
+
218
+ def is_required_property(property_name: str) -> bool:
219
+ return property_name in self.dto_schema.get("required", [])
220
+
221
+ properties = (self.dto.as_dict()).keys()
222
+ return not all(map(is_required_property, properties))
223
+
224
+ @property
225
+ def has_optional_params(self) -> bool:
226
+ """Whether or not any of the query parameters are optional."""
227
+
228
+ def is_optional_param(query_param: str) -> bool:
229
+ optional_params = [
230
+ p.get("name")
231
+ for p in self.parameters
232
+ if p.get("in") == "query" and not p.get("required")
233
+ ]
234
+ return query_param in optional_params
235
+
236
+ return any(map(is_optional_param, self.params))
237
+
238
+ @cached_property
239
+ def params_that_can_be_invalidated(self) -> Set[str]:
240
+ """
241
+ The query parameters that can be invalidated by violating data
242
+ restrictions, data type or by not providing them in a request.
243
+ """
244
+ result = set()
245
+ params = [h for h in self.parameters if h.get("in") == "query"]
246
+ for param in params:
247
+ # required params can be omitted to invalidate a request
248
+ if param["required"]:
249
+ result.add(param["name"])
250
+ continue
251
+
252
+ schema = resolve_schema(param["schema"])
253
+ if schema.get("type", None):
254
+ param_types = [schema]
255
+ else:
256
+ param_types = schema["types"]
257
+ for param_type in param_types:
258
+ # any basic non-string type except "null" can be invalidated by
259
+ # replacing it with a string
260
+ if param_type["type"] not in ["string", "array", "object", "null"]:
261
+ result.add(param["name"])
262
+ continue
263
+ # enums, strings and arrays with boundaries can be invalidated
264
+ if set(param_type.keys()).intersection(
265
+ {
266
+ "enum",
267
+ "minLength",
268
+ "maxLength",
269
+ "minItems",
270
+ "maxItems",
271
+ }
272
+ ):
273
+ result.add(param["name"])
274
+ continue
275
+ # an array of basic non-string type can be invalidated by replacing the
276
+ # items in the array with strings
277
+ if param_type["type"] == "array" and param_type["items"][
278
+ "type"
279
+ ] not in [
280
+ "string",
281
+ "array",
282
+ "object",
283
+ "null",
284
+ ]:
285
+ result.add(param["name"])
286
+ return result
287
+
288
+ @property
289
+ def has_optional_headers(self) -> bool:
290
+ """Whether or not any of the headers are optional."""
291
+
292
+ def is_optional_header(header: str) -> bool:
293
+ optional_headers = [
294
+ p.get("name")
295
+ for p in self.parameters
296
+ if p.get("in") == "header" and not p.get("required")
297
+ ]
298
+ return header in optional_headers
299
+
300
+ return any(map(is_optional_header, self.headers))
301
+
302
+ @cached_property
303
+ def headers_that_can_be_invalidated(self) -> Set[str]:
304
+ """
305
+ The header parameters that can be invalidated by violating data
306
+ restrictions or by not providing them in a request.
307
+ """
308
+ result = set()
309
+ headers = [h for h in self.parameters if h.get("in") == "header"]
310
+ for header in headers:
311
+ # required headers can be omitted to invalidate a request
312
+ if header["required"]:
313
+ result.add(header["name"])
314
+ continue
315
+
316
+ schema = resolve_schema(header["schema"])
317
+ if schema.get("type", None):
318
+ header_types = [schema]
319
+ else:
320
+ header_types = schema["types"]
321
+ for header_type in header_types:
322
+ # any basic non-string type except "null" can be invalidated by
323
+ # replacing it with a string
324
+ if header_type["type"] not in ["string", "array", "object", "null"]:
325
+ result.add(header["name"])
326
+ continue
327
+ # enums, strings and arrays with boundaries can be invalidated
328
+ if set(header_type.keys()).intersection(
329
+ {
330
+ "enum",
331
+ "minLength",
332
+ "maxLength",
333
+ "minItems",
334
+ "maxItems",
335
+ }
336
+ ):
337
+ result.add(header["name"])
338
+ continue
339
+ # an array of basic non-string type can be invalidated by replacing the
340
+ # items in the array with strings
341
+ if header_type["type"] == "array" and header_type["items"][
342
+ "type"
343
+ ] not in [
344
+ "string",
345
+ "array",
346
+ "object",
347
+ "null",
348
+ ]:
349
+ result.add(header["name"])
350
+ return result
351
+
352
+ def get_required_properties_dict(self) -> Dict[str, Any]:
353
+ """Get the json-compatible dto data containing only the required properties."""
354
+ required_properties = self.dto_schema.get("required", [])
355
+ required_properties_dict: Dict[str, Any] = {}
356
+ for key, value in (self.dto.as_dict()).items():
357
+ if key in required_properties:
358
+ required_properties_dict[key] = value
359
+ return required_properties_dict
360
+
361
+ def get_required_params(self) -> Dict[str, str]:
362
+ """Get the params dict containing only the required query parameters."""
363
+ required_parameters = [
364
+ p.get("name") for p in self.parameters if p.get("required")
365
+ ]
366
+ return {k: v for k, v in self.params.items() if k in required_parameters}
367
+
368
+ def get_required_headers(self) -> Dict[str, str]:
369
+ """Get the headers dict containing only the required headers."""
370
+ required_parameters = [
371
+ p.get("name") for p in self.parameters if p.get("required")
372
+ ]
373
+ return {k: v for k, v in self.headers.items() if k in required_parameters}
374
+
375
+
376
+ @library(scope="TEST SUITE", doc_format="ROBOT")
377
+ class OpenApiLibCore: # pylint: disable=too-many-instance-attributes
378
+ """
379
+ Main class providing the keywords and core logic to interact with an OpenAPI server.
380
+
381
+ Visit the [https://github.com/MarketSquare/robotframework-openapi-libcore | library page]
382
+ for an introduction.
383
+ """
384
+
385
+ def __init__( # pylint: disable=too-many-arguments, too-many-locals, dangerous-default-value
386
+ self,
387
+ source: str,
388
+ origin: str = "",
389
+ base_path: str = "",
390
+ mappings_path: Union[str, Path] = "",
391
+ invalid_property_default_response: int = 422,
392
+ default_id_property_name: str = "id",
393
+ faker_locale: Optional[Union[str, List[str]]] = None,
394
+ recursion_limit: int = 1,
395
+ recursion_default: Any = {},
396
+ username: str = "",
397
+ password: str = "",
398
+ security_token: str = "",
399
+ auth: Optional[AuthBase] = None,
400
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
401
+ verify_tls: Optional[Union[bool, str]] = True,
402
+ extra_headers: Optional[Dict[str, str]] = None,
403
+ cookies: Optional[Union[Dict[str, str], CookieJar]] = None,
404
+ proxies: Optional[Dict[str, str]] = None,
405
+ ) -> None:
406
+ """
407
+ == Base parameters ==
408
+
409
+ === source ===
410
+ An absolute path to an openapi.json or openapi.yaml file or an url to such a file.
411
+
412
+ === origin ===
413
+ The server (and port) of the target server. E.g. ``https://localhost:8000``
414
+
415
+ === base_path ===
416
+ The routing between ``origin`` and the endpoints as found in the ``paths``
417
+ section in the openapi document.
418
+ E.g. ``/petshop/v2``.
419
+
420
+ == API-specific configurations ==
421
+
422
+ === mappings_path ===
423
+ See [https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html | this page]
424
+ for an in-depth explanation.
425
+
426
+ === invalid_property_default_response ===
427
+ The default response code for requests with a JSON body that does not comply
428
+ with the schema.
429
+ Example: a value outside the specified range or a string value
430
+ for a property defined as integer in the schema.
431
+
432
+ === default_id_property_name ===
433
+ The default name for the property that identifies a resource (i.e. a unique
434
+ entity) within the API.
435
+ The default value for this property name is ``id``.
436
+ If the target API uses a different name for all the resources within the API,
437
+ you can configure it globally using this property.
438
+
439
+ If different property names are used for the unique identifier for different
440
+ types of resources, an ``ID_MAPPING`` can be implemented using the ``mappings_path``.
441
+
442
+ === faker_locale ===
443
+ A locale string or list of locale strings to pass to the Faker library to be
444
+ used in generation of string data for supported format types.
445
+
446
+ == Parsing parameters ==
447
+
448
+ === recursion_limit ===
449
+ The recursion depth to which to fully parse recursive references before the
450
+ `recursion_default` is used to end the recursion.
451
+
452
+ === recursion_default ===
453
+ The value that is used instead of the referenced schema when the
454
+ `recursion_limit` has been reached.
455
+ The default `{}` represents an empty object in JSON.
456
+ Depending on schema definitions, this may cause schema validation errors.
457
+ If this is the case, 'None' (``${NONE}`` in Robot Framework) or an empty list
458
+ can be tried as an alternative.
459
+
460
+ == Security-related parameters ==
461
+ _Note: these parameters are equivalent to those in the ``requests`` library._
462
+
463
+ === username ===
464
+ The username to be used for Basic Authentication.
465
+
466
+ === password ===
467
+ The password to be used for Basic Authentication.
468
+
469
+ === security_token ===
470
+ The token to be used for token based security using the ``Authorization`` header.
471
+
472
+ === auth ===
473
+ A [https://requests.readthedocs.io/en/latest/api/#authentication | requests ``AuthBase`` instance]
474
+ to be used for authentication instead of the ``username`` and ``password``.
475
+
476
+ === cert ===
477
+ The SSL certificate to use with all requests.
478
+ If string: the path to ssl client cert file (.pem).
479
+ If tuple: the ('cert', 'key') pair.
480
+
481
+ === verify_tls ===
482
+ Whether or not to verify the TLS / SSL certificate of the server.
483
+ If boolean: whether or not to verify the server TLS certificate.
484
+ If string: path to a CA bundle to use for verification.
485
+
486
+ === extra_headers ===
487
+ A dictionary with extra / custom headers that will be send with every request.
488
+ This parameter can be used to send headers that are not documented in the
489
+ openapi document or to provide an API-key.
490
+
491
+ === cookies ===
492
+ A dictionary or
493
+ [https://docs.python.org/3/library/http.cookiejar.html#http.cookiejar.CookieJar | CookieJar object]
494
+ to send with all requests.
495
+
496
+ === proxies ===
497
+ A dictionary of 'protocol': 'proxy url' to use for all requests.
498
+ """
499
+ self._source = source
500
+ self._origin = origin
501
+ self._base_path = base_path
502
+ self._recursion_limit = recursion_limit
503
+ self._recursion_default = recursion_default
504
+ self.session = Session()
505
+ # only username and password, security_token or auth object should be provided
506
+ # if multiple are provided, username and password take precedence
507
+ self.security_token = security_token
508
+ self.auth = auth
509
+ if username and password:
510
+ self.auth = HTTPBasicAuth(username, password)
511
+ # Robot Framework does not allow users to create tuples and requests
512
+ # does not accept lists, so perform the conversion here
513
+ if isinstance(cert, list):
514
+ cert = tuple(cert)
515
+ self.cert = cert
516
+ self.verify = verify_tls
517
+ self.extra_headers = extra_headers
518
+ self.cookies = cookies
519
+ self.proxies = proxies
520
+ self.invalid_property_default_response = invalid_property_default_response
521
+ if mappings_path and str(mappings_path) != ".":
522
+ mappings_path = Path(mappings_path)
523
+ if not mappings_path.is_file():
524
+ logger.warning(
525
+ f"mappings_path '{mappings_path}' is not a Python module."
526
+ )
527
+ # intermediate variable to ensure path.append is possible so we'll never
528
+ # path.pop a location that we didn't append
529
+ mappings_folder = str(mappings_path.parent)
530
+ sys.path.append(mappings_folder)
531
+ mappings_module_name = mappings_path.stem
532
+ self.get_dto_class = get_dto_class(
533
+ mappings_module_name=mappings_module_name
534
+ )
535
+ self.get_id_property_name = get_id_property_name(
536
+ mappings_module_name=mappings_module_name
537
+ )
538
+ sys.path.pop()
539
+ else:
540
+ self.get_dto_class = get_dto_class(mappings_module_name="no mapping")
541
+ self.get_id_property_name = get_id_property_name(
542
+ mappings_module_name="no mapping"
543
+ )
544
+ if faker_locale:
545
+ FAKE.set_locale(locale=faker_locale)
546
+ # update the globally available DEFAULT_ID_PROPERTY_NAME to the provided value
547
+ DEFAULT_ID_PROPERTY_NAME.id_property_name = default_id_property_name
548
+
549
+ @property
550
+ def origin(self) -> str:
551
+ return self._origin
552
+
553
+ @keyword
554
+ def set_origin(self, origin: str) -> None:
555
+ """
556
+ Update the `origin` after the library is imported.
557
+
558
+ This can be done during the `Suite setup` when using DataDriver in situations
559
+ where the OpenAPI document is available on disk but the target host address is
560
+ not known before the test starts.
561
+
562
+ In combination with OpenApiLibCore, the `origin` can be used at any point to
563
+ target another server that hosts an API that complies to the same OAS.
564
+ """
565
+ self._origin = origin
566
+
567
+ @property
568
+ def base_url(self) -> str:
569
+ return f"{self.origin}{self._base_path}"
570
+
571
+ @cached_property
572
+ def validation_spec(self) -> Spec:
573
+ return Spec.from_dict(self.openapi_spec)
574
+
575
+ @property
576
+ def openapi_spec(self) -> Dict[str, Any]:
577
+ """Return a deepcopy of the parsed openapi document."""
578
+ # protect the parsed openapi spec from being mutated by reference
579
+ return deepcopy(self._openapi_spec)
580
+
581
+ @cached_property
582
+ def _openapi_spec(self) -> Dict[str, Any]:
583
+ parser = self._load_parser()
584
+ return parser.specification
585
+
586
+ def read_paths(self) -> Dict[str, Any]:
587
+ return self.openapi_spec["paths"]
588
+
589
+ def _load_parser(self) -> ResolvingParser:
590
+ try:
591
+
592
+ def recursion_limit_handler(
593
+ limit: int, refstring: str, recursions: Any
594
+ ) -> Any:
595
+ return self._recursion_default
596
+
597
+ # Since parsing of the OAS and creating the Spec can take a long time,
598
+ # they are cached. This is done by storing them in an imported module that
599
+ # will have a global scope due to how the Python import system works. This
600
+ # ensures that in a Suite of Suites where multiple Suites use the same
601
+ # `source`, that OAS is only parsed / loaded once.
602
+ parser = PARSER_CACHE.get(self._source, None)
603
+ if parser is None:
604
+ parser = ResolvingParser(
605
+ self._source,
606
+ backend="openapi-spec-validator",
607
+ recursion_limit=self._recursion_limit,
608
+ recursion_limit_handler=recursion_limit_handler,
609
+ )
610
+
611
+ if parser.specification is None: # pragma: no cover
612
+ BuiltIn().fatal_error(
613
+ "Source was loaded, but no specification was present after parsing."
614
+ )
615
+
616
+ PARSER_CACHE[self._source] = parser
617
+
618
+ return parser
619
+
620
+ except ResolutionError as exception:
621
+ BuiltIn().fatal_error(
622
+ f"ResolutionError while trying to load openapi spec: {exception}"
623
+ )
624
+ except ValidationError as exception:
625
+ BuiltIn().fatal_error(
626
+ f"ValidationError while trying to load openapi spec: {exception}"
627
+ )
628
+
629
+ def validate_response_vs_spec(
630
+ self, request: RequestsOpenAPIRequest, response: RequestsOpenAPIResponse
631
+ ) -> None:
632
+ """
633
+ Validate the reponse for a given request against the OpenAPI Spec that is
634
+ loaded during library initialization.
635
+ """
636
+ if response.content_type == "application/json":
637
+ config = None
638
+ else:
639
+ extra_deserializer = {response.content_type: _json.loads}
640
+ config = Config(extra_media_type_deserializers=extra_deserializer)
641
+
642
+ OpenAPI(spec=self.validation_spec, config=config).validate_response(
643
+ request, response
644
+ )
645
+
646
+ @keyword
647
+ def get_valid_url(self, endpoint: str, method: str) -> str:
648
+ """
649
+ This keyword returns a valid url for the given `endpoint` and `method`.
650
+
651
+ If the `endpoint` contains path parameters the Get Valid Id For Endpoint
652
+ keyword will be executed to retrieve valid ids for the path parameters.
653
+
654
+ > Note: if valid ids cannot be retrieved within the scope of the API, the
655
+ `PathPropertiesConstraint` Relation can be used. More information can be found
656
+ [https://marketsquare.github.io/robotframework-openapi-libcore/advanced_use.html | here].
657
+ """
658
+ method = method.lower()
659
+ try:
660
+ # endpoint can be partially resolved or provided by a PathPropertiesConstraint
661
+ parametrized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
662
+ _ = self.openapi_spec["paths"][parametrized_endpoint]
663
+ except KeyError:
664
+ raise ValueError(
665
+ f"{endpoint} not found in paths section of the OpenAPI document."
666
+ ) from None
667
+ dto_class = self.get_dto_class(endpoint=endpoint, method=method)
668
+ relations = dto_class.get_relations()
669
+ paths = [p.path for p in relations if isinstance(p, PathPropertiesConstraint)]
670
+ if paths:
671
+ url = f"{self.base_url}{choice(paths)}"
672
+ return url
673
+ endpoint_parts = list(endpoint.split("/"))
674
+ for index, part in enumerate(endpoint_parts):
675
+ if part.startswith("{") and part.endswith("}"):
676
+ type_endpoint_parts = endpoint_parts[slice(index)]
677
+ type_endpoint = "/".join(type_endpoint_parts)
678
+ existing_id: Union[str, int, float] = run_keyword(
679
+ "get_valid_id_for_endpoint", type_endpoint, method
680
+ )
681
+ endpoint_parts[index] = str(existing_id)
682
+ resolved_endpoint = "/".join(endpoint_parts)
683
+ url = f"{self.base_url}{resolved_endpoint}"
684
+ return url
685
+
686
+ @keyword
687
+ def get_valid_id_for_endpoint(
688
+ self, endpoint: str, method: str
689
+ ) -> Union[str, int, float]:
690
+ """
691
+ Support keyword that returns the `id` for an existing resource at `endpoint`.
692
+
693
+ To prevent resource conflicts with other test cases, a new resource is created
694
+ (POST) if possible.
695
+ """
696
+
697
+ def dummy_transformer(
698
+ valid_id: Union[str, int, float]
699
+ ) -> Union[str, int, float]:
700
+ return valid_id
701
+
702
+ method = method.lower()
703
+ url: str = run_keyword("get_valid_url", endpoint, method)
704
+ # Try to create a new resource to prevent conflicts caused by
705
+ # operations performed on the same resource by other test cases
706
+ request_data = self.get_request_data(endpoint=endpoint, method="post")
707
+
708
+ response: Response = run_keyword(
709
+ "authorized_request",
710
+ url,
711
+ "post",
712
+ request_data.get_required_params(),
713
+ request_data.get_required_headers(),
714
+ request_data.get_required_properties_dict(),
715
+ )
716
+
717
+ # determine the id property name for this path and whether or not a transformer is used
718
+ mapping = self.get_id_property_name(endpoint=endpoint)
719
+ if isinstance(mapping, str):
720
+ id_property = mapping
721
+ # set the transformer to a dummy callable that returns the original value so
722
+ # the transformer can be applied on any returned id
723
+ id_transformer = dummy_transformer
724
+ else:
725
+ id_property, id_transformer = mapping
726
+
727
+ if not response.ok:
728
+ # If a new resource cannot be created using POST, try to retrieve a
729
+ # valid id using a GET request.
730
+ try:
731
+ valid_id = choice(run_keyword("get_ids_from_url", url))
732
+ return id_transformer(valid_id)
733
+ except Exception as exception:
734
+ raise AssertionError(
735
+ f"Failed to get a valid id using GET on {url}"
736
+ ) from exception
737
+
738
+ response_data = response.json()
739
+ if prepared_body := response.request.body:
740
+ if isinstance(prepared_body, bytes):
741
+ send_json = _json.loads(prepared_body.decode("UTF-8"))
742
+ else:
743
+ send_json = _json.loads(prepared_body)
744
+ else:
745
+ send_json = None
746
+
747
+ # no support for retrieving an id from an array returned on a POST request
748
+ if isinstance(response_data, list):
749
+ raise NotImplementedError(
750
+ f"Unexpected response body for POST request: expected an object but "
751
+ f"received an array ({response_data})"
752
+ )
753
+
754
+ # POST on /resource_type/{id}/array_item/ will return the updated {id} resource
755
+ # instead of a newly created resource. In this case, the send_json must be
756
+ # in the array of the 'array_item' property on {id}
757
+ send_path: str = response.request.path_url
758
+ response_href: Optional[str] = response_data.get("href", None)
759
+ if response_href and (send_path not in response_href) and send_json:
760
+ try:
761
+ property_to_check = send_path.replace(response_href, "")[1:]
762
+ item_list: List[Dict[str, Any]] = response_data[property_to_check]
763
+ # Use the (mandatory) id to get the POSTed resource from the list
764
+ [valid_id] = [
765
+ item[id_property]
766
+ for item in item_list
767
+ if item[id_property] == send_json[id_property]
768
+ ]
769
+ except Exception as exception:
770
+ raise AssertionError(
771
+ f"Failed to get a valid id from {response_href}"
772
+ ) from exception
773
+ else:
774
+ try:
775
+ valid_id = response_data[id_property]
776
+ except KeyError:
777
+ raise AssertionError(
778
+ f"Failed to get a valid id from {response_data}"
779
+ ) from None
780
+ return id_transformer(valid_id)
781
+
782
+ @keyword
783
+ def get_ids_from_url(self, url: str) -> List[str]:
784
+ """
785
+ Perform a GET request on the `url` and return the list of resource
786
+ `ids` from the response.
787
+ """
788
+ endpoint = self.get_parameterized_endpoint_from_url(url)
789
+ request_data = self.get_request_data(endpoint=endpoint, method="get")
790
+ response = run_keyword(
791
+ "authorized_request",
792
+ url,
793
+ "get",
794
+ request_data.get_required_params(),
795
+ request_data.get_required_headers(),
796
+ )
797
+ response.raise_for_status()
798
+ response_data: Union[Dict[str, Any], List[Dict[str, Any]]] = response.json()
799
+
800
+ # determine the property name to use
801
+ mapping = self.get_id_property_name(endpoint=endpoint)
802
+ if isinstance(mapping, str):
803
+ id_property = mapping
804
+ else:
805
+ id_property, _ = mapping
806
+
807
+ if isinstance(response_data, list):
808
+ valid_ids: List[str] = [item[id_property] for item in response_data]
809
+ return valid_ids
810
+ # if the response is an object (dict), check if it's hal+json
811
+ if embedded := response_data.get("_embedded"):
812
+ # there should be 1 item in the dict that has a value that's a list
813
+ for value in embedded.values():
814
+ if isinstance(value, list):
815
+ valid_ids = [item[id_property] for item in value]
816
+ return valid_ids
817
+ if (valid_id := response_data.get(id_property)) is not None:
818
+ return [valid_id]
819
+ valid_ids = [item[id_property] for item in response_data["items"]]
820
+ return valid_ids
821
+
822
+ @keyword
823
+ def get_request_data(self, endpoint: str, method: str) -> RequestData:
824
+ """Return an object with valid request data for body, headers and query params."""
825
+ method = method.lower()
826
+ dto_cls_name = self._get_dto_cls_name(endpoint=endpoint, method=method)
827
+ # The endpoint can contain already resolved Ids that have to be matched
828
+ # against the parametrized endpoints in the paths section.
829
+ spec_endpoint = self.get_parametrized_endpoint(endpoint)
830
+ dto_class = self.get_dto_class(endpoint=spec_endpoint, method=method)
831
+ try:
832
+ method_spec = self.openapi_spec["paths"][spec_endpoint][method]
833
+ except KeyError:
834
+ logger.info(
835
+ f"method '{method}' not supported on '{spec_endpoint}, using empty spec."
836
+ )
837
+ method_spec = {}
838
+
839
+ parameters, params, headers = self.get_request_parameters(
840
+ dto_class=dto_class, method_spec=method_spec
841
+ )
842
+ if (body_spec := method_spec.get("requestBody", None)) is None:
843
+ if dto_class == DefaultDto:
844
+ dto_instance: Dto = DefaultDto()
845
+ else:
846
+ dto_class = make_dataclass(
847
+ cls_name=method_spec.get("operationId", dto_cls_name),
848
+ fields=[],
849
+ bases=(dto_class,),
850
+ )
851
+ dto_instance = dto_class()
852
+ return RequestData(
853
+ dto=dto_instance,
854
+ parameters=parameters,
855
+ params=params,
856
+ headers=headers,
857
+ has_body=False,
858
+ )
859
+ content_schema = resolve_schema(self.get_content_schema(body_spec))
860
+ headers.update({"content-type": self.get_content_type(body_spec)})
861
+ dto_data = self.get_json_data_for_dto_class(
862
+ schema=content_schema,
863
+ dto_class=dto_class,
864
+ operation_id=method_spec.get("operationId", ""),
865
+ )
866
+ if dto_data is None:
867
+ dto_instance = DefaultDto()
868
+ else:
869
+ fields = self.get_fields_from_dto_data(content_schema, dto_data)
870
+ dto_class = make_dataclass(
871
+ cls_name=method_spec.get("operationId", dto_cls_name),
872
+ fields=fields,
873
+ bases=(dto_class,),
874
+ )
875
+ dto_data = {get_safe_key(key): value for key, value in dto_data.items()}
876
+ dto_instance = dto_class(**dto_data)
877
+ return RequestData(
878
+ dto=dto_instance,
879
+ dto_schema=content_schema,
880
+ parameters=parameters,
881
+ params=params,
882
+ headers=headers,
883
+ )
884
+
885
+ @staticmethod
886
+ def _get_dto_cls_name(endpoint: str, method: str) -> str:
887
+ method = method.capitalize()
888
+ path = endpoint.translate({ord(i): None for i in "{}"})
889
+ path_parts = path.split("/")
890
+ path_parts = [p.capitalize() for p in path_parts]
891
+ result = "".join([method, *path_parts])
892
+ return result
893
+
894
+ @staticmethod
895
+ def get_fields_from_dto_data(
896
+ content_schema: Dict[str, Any], dto_data: Dict[str, Any]
897
+ ):
898
+ # FIXME: annotation is not Pyhon 3.8-compatible
899
+ # ) -> List[Union[str, Tuple[str, Type[Any]], Tuple[str, Type[Any], Field[Any]]]]:
900
+ """Get a dataclasses fields list based on the content_schema and dto_data."""
901
+ fields: List[
902
+ Union[str, Tuple[str, Type[Any]], Tuple[str, Type[Any], Field[Any]]]
903
+ ] = []
904
+ for key, value in dto_data.items():
905
+ required_properties = content_schema.get("required", [])
906
+ safe_key = get_safe_key(key)
907
+ metadata = {"original_property_name": key}
908
+ if key in required_properties:
909
+ # The fields list is used to create a dataclass, so non-default fields
910
+ # must go before fields with a default
911
+ fields.insert(0, (safe_key, type(value), field(metadata=metadata)))
912
+ else:
913
+ fields.append((safe_key, type(value), field(default=None, metadata=metadata))) # type: ignore[arg-type]
914
+ return fields
915
+
916
+ def get_request_parameters(
917
+ self, dto_class: Union[Dto, Type[Dto]], method_spec: Dict[str, Any]
918
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any], Dict[str, str]]:
919
+ """Get the methods parameter spec and params and headers with valid data."""
920
+ parameters = method_spec.get("parameters", [])
921
+ parameter_relations = dto_class.get_parameter_relations()
922
+ query_params = [p for p in parameters if p.get("in") == "query"]
923
+ header_params = [p for p in parameters if p.get("in") == "header"]
924
+ params = self.get_parameter_data(query_params, parameter_relations)
925
+ headers = self.get_parameter_data(header_params, parameter_relations)
926
+ return parameters, params, headers
927
+
928
+ @classmethod
929
+ def get_content_schema(cls, body_spec: Dict[str, Any]) -> Dict[str, Any]:
930
+ """Get the content schema from the requestBody spec."""
931
+ content_type = cls.get_content_type(body_spec)
932
+ content_schema = body_spec["content"][content_type]["schema"]
933
+ return resolve_schema(content_schema)
934
+
935
+ @staticmethod
936
+ def get_content_type(body_spec: Dict[str, Any]) -> str:
937
+ """Get and validate the first supported content type from the requested body spec
938
+
939
+ Should be application/json like content type,
940
+ e.g "application/json;charset=utf-8" or "application/merge-patch+json"
941
+ """
942
+ content_types: List[str] = body_spec["content"].keys()
943
+ json_regex = r"application/([a-z\-]+\+)?json(;\s?charset=(.+))?"
944
+ for content_type in content_types:
945
+ if re.search(json_regex, content_type):
946
+ return content_type
947
+
948
+ # At present no supported for other types.
949
+ raise NotImplementedError(
950
+ f"Only content types like 'application/json' are supported. "
951
+ f"Content types definded in the spec are '{content_types}'."
952
+ )
953
+
954
+ def get_parametrized_endpoint(self, endpoint: str) -> str:
955
+ """
956
+ Get the parametrized endpoint as found in the `paths` section of the openapi
957
+ document from a (partially) resolved endpoint.
958
+ """
959
+
960
+ def match_parts(parts: List[str], spec_parts: List[str]) -> bool:
961
+ for part, spec_part in zip_longest(parts, spec_parts, fillvalue="Filler"):
962
+ if part == "Filler" or spec_part == "Filler":
963
+ return False
964
+ if part != spec_part and not spec_part.startswith("{"):
965
+ return False
966
+ return True
967
+
968
+ endpoint_parts = endpoint.split("/")
969
+ # if the last part is empty, the path has a trailing `/` that
970
+ # should be ignored during matching
971
+ if endpoint_parts[-1] == "":
972
+ _ = endpoint_parts.pop(-1)
973
+
974
+ spec_endpoints: List[str] = {**self.openapi_spec}["paths"].keys()
975
+
976
+ candidates: List[str] = []
977
+
978
+ for spec_endpoint in spec_endpoints:
979
+ spec_endpoint_parts = spec_endpoint.split("/")
980
+ # ignore trailing `/` the same way as for endpoint_parts
981
+ if spec_endpoint_parts[-1] == "":
982
+ _ = spec_endpoint_parts.pop(-1)
983
+ if match_parts(endpoint_parts, spec_endpoint_parts):
984
+ candidates.append(spec_endpoint)
985
+
986
+ if not candidates:
987
+ raise ValueError(
988
+ f"{endpoint} not found in paths section of the OpenAPI document."
989
+ )
990
+
991
+ if len(candidates) == 1:
992
+ return candidates[0]
993
+ # Multiple matches can happen in APIs with overloaded endpoints, e.g.
994
+ # /users/me
995
+ # /users/${user_id}
996
+ # In this case, find the closest (or exact) match
997
+ exact_match = [c for c in candidates if c == endpoint]
998
+ if exact_match:
999
+ return exact_match[0]
1000
+ # TODO: Implement a decision mechanism when real-world examples become available
1001
+ # In the face of ambiguity, refuse the temptation to guess.
1002
+ raise ValueError(f"{endpoint} matched to multiple paths: {candidates}")
1003
+
1004
+ @staticmethod
1005
+ def get_parameter_data(
1006
+ parameters: List[Dict[str, Any]],
1007
+ parameter_relations: List[Relation],
1008
+ ) -> Dict[str, str]:
1009
+ """Generate a valid list of key-value pairs for all parameters."""
1010
+ result: Dict[str, str] = {}
1011
+ value: Any = None
1012
+ for parameter in parameters:
1013
+ parameter_name = parameter["name"]
1014
+ parameter_schema = resolve_schema(parameter["schema"])
1015
+ relations = [
1016
+ r for r in parameter_relations if r.property_name == parameter_name
1017
+ ]
1018
+ if constrained_values := [
1019
+ r.values for r in relations if isinstance(r, PropertyValueConstraint)
1020
+ ]:
1021
+ value = choice(*constrained_values)
1022
+ if value is IGNORE:
1023
+ continue
1024
+ result[parameter_name] = value
1025
+ continue
1026
+ value = value_utils.get_valid_value(parameter_schema)
1027
+ result[parameter_name] = value
1028
+ return result
1029
+
1030
+ @keyword
1031
+ def get_json_data_for_dto_class(
1032
+ self,
1033
+ schema: Dict[str, Any],
1034
+ dto_class: Union[Dto, Type[Dto]],
1035
+ operation_id: str = "",
1036
+ ) -> Optional[Dict[str, Any]]:
1037
+ """
1038
+ Generate a valid (json-compatible) dict for all the `dto_class` properties.
1039
+ """
1040
+
1041
+ def get_constrained_values(property_name: str) -> List[Any]:
1042
+ relations = dto_class.get_relations()
1043
+ values_list = [
1044
+ c.values
1045
+ for c in relations
1046
+ if (
1047
+ isinstance(c, PropertyValueConstraint)
1048
+ and c.property_name == property_name
1049
+ )
1050
+ ]
1051
+ # values should be empty or contain 1 list of allowed values
1052
+ return values_list.pop() if values_list else []
1053
+
1054
+ def get_dependent_id(
1055
+ property_name: str, operation_id: str
1056
+ ) -> Optional[Union[str, int, float]]:
1057
+ relations = dto_class.get_relations()
1058
+ # multiple get paths are possible based on the operation being performed
1059
+ id_get_paths = [
1060
+ (d.get_path, d.operation_id)
1061
+ for d in relations
1062
+ if (isinstance(d, IdDependency) and d.property_name == property_name)
1063
+ ]
1064
+ if not id_get_paths:
1065
+ return None
1066
+ if len(id_get_paths) == 1:
1067
+ id_get_path, _ = id_get_paths.pop()
1068
+ else:
1069
+ try:
1070
+ [id_get_path] = [
1071
+ path
1072
+ for path, operation in id_get_paths
1073
+ if operation == operation_id
1074
+ ]
1075
+ # There could be multiple get_paths, but not one for the current operation
1076
+ except ValueError:
1077
+ return None
1078
+ valid_id = self.get_valid_id_for_endpoint(
1079
+ endpoint=id_get_path, method="get"
1080
+ )
1081
+ logger.debug(f"get_dependent_id for {id_get_path} returned {valid_id}")
1082
+ return valid_id
1083
+
1084
+ json_data: Dict[str, Any] = {}
1085
+
1086
+ for property_name in schema.get("properties", []):
1087
+ properties_schema = schema["properties"][property_name]
1088
+
1089
+ property_type = properties_schema.get("type")
1090
+ if property_type is None:
1091
+ property_types = properties_schema.get("types")
1092
+ if property_types is None:
1093
+ if properties_schema.get("properties") is not None:
1094
+ nested_data = self.get_json_data_for_dto_class(
1095
+ schema=properties_schema,
1096
+ dto_class=DefaultDto,
1097
+ )
1098
+ json_data[property_name] = nested_data
1099
+ continue
1100
+ selected_type_schema = choice(property_types)
1101
+ property_type = selected_type_schema["type"]
1102
+ if properties_schema.get("readOnly", False):
1103
+ continue
1104
+ if constrained_values := get_constrained_values(property_name):
1105
+ # do not add properties that are configured to be ignored
1106
+ if IGNORE in constrained_values:
1107
+ continue
1108
+ json_data[property_name] = choice(constrained_values)
1109
+ continue
1110
+ if (
1111
+ dependent_id := get_dependent_id(
1112
+ property_name=property_name, operation_id=operation_id
1113
+ )
1114
+ ) is not None:
1115
+ json_data[property_name] = dependent_id
1116
+ continue
1117
+ if property_type == "object":
1118
+ object_data = self.get_json_data_for_dto_class(
1119
+ schema=properties_schema,
1120
+ dto_class=DefaultDto,
1121
+ operation_id="",
1122
+ )
1123
+ json_data[property_name] = object_data
1124
+ continue
1125
+ if property_type == "array":
1126
+ array_data = self.get_json_data_for_dto_class(
1127
+ schema=properties_schema["items"],
1128
+ dto_class=DefaultDto,
1129
+ operation_id=operation_id,
1130
+ )
1131
+ json_data[property_name] = [array_data]
1132
+ continue
1133
+ json_data[property_name] = value_utils.get_valid_value(properties_schema)
1134
+ return json_data
1135
+
1136
+ @keyword
1137
+ def get_invalidated_url(self, valid_url: str) -> Optional[str]:
1138
+ """
1139
+ Return an url with all the path parameters in the `valid_url` replaced by a
1140
+ random UUID.
1141
+
1142
+ Raises ValueError if the valid_url cannot be invalidated.
1143
+ """
1144
+ parameterized_endpoint = self.get_parameterized_endpoint_from_url(valid_url)
1145
+ parameterized_url = self.base_url + parameterized_endpoint
1146
+ valid_url_parts = list(reversed(valid_url.split("/")))
1147
+ parameterized_parts = reversed(parameterized_url.split("/"))
1148
+ for index, (parameterized_part, _) in enumerate(
1149
+ zip(parameterized_parts, valid_url_parts)
1150
+ ):
1151
+ if parameterized_part.startswith("{") and parameterized_part.endswith("}"):
1152
+ valid_url_parts[index] = uuid4().hex
1153
+ valid_url_parts.reverse()
1154
+ invalid_url = "/".join(valid_url_parts)
1155
+ return invalid_url
1156
+ raise ValueError(f"{parameterized_endpoint} could not be invalidated.")
1157
+
1158
+ @keyword
1159
+ def get_parameterized_endpoint_from_url(self, url: str) -> str:
1160
+ """
1161
+ Return the endpoint as found in the `paths` section based on the given `url`.
1162
+ """
1163
+ endpoint = url.replace(self.base_url, "")
1164
+ endpoint_parts = endpoint.split("/")
1165
+ # first part will be '' since an endpoint starts with /
1166
+ endpoint_parts.pop(0)
1167
+ parameterized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
1168
+ return parameterized_endpoint
1169
+
1170
+ @keyword
1171
+ def get_invalid_json_data(
1172
+ self,
1173
+ url: str,
1174
+ method: str,
1175
+ status_code: int,
1176
+ request_data: RequestData,
1177
+ ) -> Dict[str, Any]:
1178
+ """
1179
+ Return `json_data` based on the `dto` on the `request_data` that will cause
1180
+ the provided `status_code` for the `method` operation on the `url`.
1181
+
1182
+ > Note: applicable UniquePropertyValueConstraint and IdReference Relations are
1183
+ considered before changes to `json_data` are made.
1184
+ """
1185
+ method = method.lower()
1186
+ data_relations = request_data.dto.get_relations_for_error_code(status_code)
1187
+ if not data_relations:
1188
+ if not request_data.dto_schema:
1189
+ raise ValueError(
1190
+ "Failed to invalidate: no data_relations and empty schema."
1191
+ )
1192
+ json_data = request_data.dto.get_invalidated_data(
1193
+ schema=request_data.dto_schema,
1194
+ status_code=status_code,
1195
+ invalid_property_default_code=self.invalid_property_default_response,
1196
+ )
1197
+ return json_data
1198
+ resource_relation = choice(data_relations)
1199
+ if isinstance(resource_relation, UniquePropertyValueConstraint):
1200
+ json_data = run_keyword(
1201
+ "get_json_data_with_conflict",
1202
+ url,
1203
+ method,
1204
+ request_data.dto,
1205
+ status_code,
1206
+ )
1207
+ elif isinstance(resource_relation, IdReference):
1208
+ run_keyword("ensure_in_use", url, resource_relation)
1209
+ json_data = request_data.dto.as_dict()
1210
+ else:
1211
+ json_data = request_data.dto.get_invalidated_data(
1212
+ schema=request_data.dto_schema,
1213
+ status_code=status_code,
1214
+ invalid_property_default_code=self.invalid_property_default_response,
1215
+ )
1216
+ return json_data
1217
+
1218
+ @keyword
1219
+ def get_invalidated_parameters(
1220
+ self,
1221
+ status_code: int,
1222
+ request_data: RequestData,
1223
+ ) -> Tuple[Dict[str, Any], Dict[str, str]]:
1224
+ """
1225
+ Returns a version of `params, headers` as present on `request_data` that has
1226
+ been modified to cause the provided `status_code`.
1227
+ """
1228
+ if not request_data.parameters:
1229
+ raise ValueError("No params or headers to invalidate.")
1230
+
1231
+ # ensure the status_code can be triggered
1232
+ relations = request_data.dto.get_parameter_relations_for_error_code(status_code)
1233
+ relations_for_status_code = [
1234
+ r
1235
+ for r in relations
1236
+ if isinstance(r, PropertyValueConstraint)
1237
+ and (
1238
+ r.error_code == status_code or r.invalid_value_error_code == status_code
1239
+ )
1240
+ ]
1241
+ parameters_to_ignore = {
1242
+ r.property_name
1243
+ for r in relations_for_status_code
1244
+ if r.invalid_value_error_code == status_code and r.invalid_value == IGNORE
1245
+ }
1246
+ relation_property_names = {r.property_name for r in relations_for_status_code}
1247
+ if not relation_property_names:
1248
+ if status_code != self.invalid_property_default_response:
1249
+ raise ValueError(
1250
+ f"No relations to cause status_code {status_code} found."
1251
+ )
1252
+
1253
+ # ensure we're not modifying mutable properties
1254
+ params = deepcopy(request_data.params)
1255
+ headers = deepcopy(request_data.headers)
1256
+
1257
+ if status_code == self.invalid_property_default_response:
1258
+ # take the params and headers that can be invalidated based on data type
1259
+ # and expand the set with properties that can be invalided by relations
1260
+ parameter_names = set(request_data.params_that_can_be_invalidated).union(
1261
+ request_data.headers_that_can_be_invalidated
1262
+ )
1263
+ parameter_names.update(relation_property_names)
1264
+ if not parameter_names:
1265
+ raise ValueError(
1266
+ "None of the query parameters and headers can be invalidated."
1267
+ )
1268
+ else:
1269
+ # non-default status_codes can only be the result of a Relation
1270
+ parameter_names = relation_property_names
1271
+
1272
+ # Dto mappings may contain generic mappings for properties that are not present
1273
+ # in this specific schema
1274
+ request_data_parameter_names = [p.get("name") for p in request_data.parameters]
1275
+ additional_relation_property_names = {
1276
+ n for n in relation_property_names if n not in request_data_parameter_names
1277
+ }
1278
+ if additional_relation_property_names:
1279
+ logger.warning(
1280
+ f"get_parameter_relations_for_error_code yielded properties that are "
1281
+ f"not defined in the schema: {additional_relation_property_names}\n"
1282
+ f"These properties will be ignored for parameter invalidation."
1283
+ )
1284
+ parameter_names = parameter_names - additional_relation_property_names
1285
+
1286
+ if not parameter_names:
1287
+ raise ValueError(
1288
+ f"No parameter can be changed to cause status_code {status_code}."
1289
+ )
1290
+
1291
+ parameter_names = parameter_names - parameters_to_ignore
1292
+ parameter_to_invalidate = choice(tuple(parameter_names))
1293
+
1294
+ # check for invalid parameters in the provided request_data
1295
+ try:
1296
+ [parameter_data] = [
1297
+ data
1298
+ for data in request_data.parameters
1299
+ if data["name"] == parameter_to_invalidate
1300
+ ]
1301
+ except Exception:
1302
+ raise ValueError(
1303
+ f"{parameter_to_invalidate} not found in provided parameters."
1304
+ ) from None
1305
+
1306
+ # get the invalid_value for the chosen parameter
1307
+ try:
1308
+ [invalid_value_for_error_code] = [
1309
+ r.invalid_value
1310
+ for r in relations_for_status_code
1311
+ if r.property_name == parameter_to_invalidate
1312
+ and r.invalid_value_error_code == status_code
1313
+ ]
1314
+ except ValueError:
1315
+ invalid_value_for_error_code = NOT_SET
1316
+
1317
+ # get the constraint values if available for the chosen parameter
1318
+ try:
1319
+ [values_from_constraint] = [
1320
+ r.values
1321
+ for r in relations_for_status_code
1322
+ if r.property_name == parameter_to_invalidate
1323
+ ]
1324
+ except ValueError:
1325
+ values_from_constraint = []
1326
+
1327
+ # if the parameter was not provided, add it to params / headers
1328
+ params, headers = self.ensure_parameter_in_parameters(
1329
+ parameter_to_invalidate=parameter_to_invalidate,
1330
+ params=params,
1331
+ headers=headers,
1332
+ parameter_data=parameter_data,
1333
+ values_from_constraint=values_from_constraint,
1334
+ )
1335
+
1336
+ # determine the invalid_value
1337
+ if invalid_value_for_error_code != NOT_SET:
1338
+ invalid_value = invalid_value_for_error_code
1339
+ else:
1340
+ if parameter_to_invalidate in params.keys():
1341
+ valid_value = params[parameter_to_invalidate]
1342
+ else:
1343
+ valid_value = headers[parameter_to_invalidate]
1344
+
1345
+ value_schema = resolve_schema(parameter_data["schema"])
1346
+ invalid_value = value_utils.get_invalid_value(
1347
+ value_schema=value_schema,
1348
+ current_value=valid_value,
1349
+ values_from_constraint=values_from_constraint,
1350
+ )
1351
+ logger.debug(f"{parameter_to_invalidate} changed to {invalid_value}")
1352
+
1353
+ # update the params / headers and return
1354
+ if parameter_to_invalidate in params.keys():
1355
+ params[parameter_to_invalidate] = invalid_value
1356
+ else:
1357
+ headers[parameter_to_invalidate] = invalid_value
1358
+ return params, headers
1359
+
1360
+ @staticmethod
1361
+ def ensure_parameter_in_parameters(
1362
+ parameter_to_invalidate: str,
1363
+ params: Dict[str, Any],
1364
+ headers: Dict[str, str],
1365
+ parameter_data: Dict[str, Any],
1366
+ values_from_constraint: List[Any],
1367
+ ) -> Tuple[Dict[str, Any], Dict[str, str]]:
1368
+ """
1369
+ Returns the params, headers tuple with parameter_to_invalidate with a valid
1370
+ value to params or headers if not originally present.
1371
+ """
1372
+ if (
1373
+ parameter_to_invalidate not in params.keys()
1374
+ and parameter_to_invalidate not in headers.keys()
1375
+ ):
1376
+ if values_from_constraint:
1377
+ valid_value = choice(values_from_constraint)
1378
+ else:
1379
+ parameter_schema = resolve_schema(parameter_data["schema"])
1380
+ valid_value = value_utils.get_valid_value(parameter_schema)
1381
+ if (
1382
+ parameter_data["in"] == "query"
1383
+ and parameter_to_invalidate not in params.keys()
1384
+ ):
1385
+ params[parameter_to_invalidate] = valid_value
1386
+ if (
1387
+ parameter_data["in"] == "header"
1388
+ and parameter_to_invalidate not in headers.keys()
1389
+ ):
1390
+ headers[parameter_to_invalidate] = valid_value
1391
+ return params, headers
1392
+
1393
+ @keyword
1394
+ def ensure_in_use(self, url: str, resource_relation: IdReference) -> None:
1395
+ """
1396
+ Ensure that the (right-most) `id` of the resource referenced by the `url`
1397
+ is used by the resource defined by the `resource_relation`.
1398
+ """
1399
+ resource_id = ""
1400
+
1401
+ endpoint = url.replace(self.base_url, "")
1402
+ endpoint_parts = endpoint.split("/")
1403
+ parameterized_endpoint = self.get_parametrized_endpoint(endpoint=endpoint)
1404
+ parameterized_endpoint_parts = parameterized_endpoint.split("/")
1405
+ for part, param_part in zip(
1406
+ reversed(endpoint_parts), reversed(parameterized_endpoint_parts)
1407
+ ):
1408
+ if param_part.endswith("}"):
1409
+ resource_id = part
1410
+ break
1411
+ if not resource_id:
1412
+ raise ValueError(f"The provided url ({url}) does not contain an id.")
1413
+ request_data = self.get_request_data(
1414
+ method="post", endpoint=resource_relation.post_path
1415
+ )
1416
+ json_data = request_data.dto.as_dict()
1417
+ json_data[resource_relation.property_name] = resource_id
1418
+ post_url: str = run_keyword(
1419
+ "get_valid_url",
1420
+ resource_relation.post_path,
1421
+ "post",
1422
+ )
1423
+ response: Response = run_keyword(
1424
+ "authorized_request",
1425
+ post_url,
1426
+ "post",
1427
+ request_data.params,
1428
+ request_data.headers,
1429
+ json_data,
1430
+ )
1431
+ if not response.ok:
1432
+ logger.debug(
1433
+ f"POST on {post_url} with json {json_data} failed: {response.json()}"
1434
+ )
1435
+ response.raise_for_status()
1436
+
1437
+ @keyword
1438
+ def get_json_data_with_conflict(
1439
+ self, url: str, method: str, dto: Dto, conflict_status_code: int
1440
+ ) -> Dict[str, Any]:
1441
+ """
1442
+ Return `json_data` based on the `UniquePropertyValueConstraint` that must be
1443
+ returned by the `get_relations` implementation on the `dto` for the given
1444
+ `conflict_status_code`.
1445
+ """
1446
+ method = method.lower()
1447
+ json_data = dto.as_dict()
1448
+ unique_property_value_constraints = [
1449
+ r
1450
+ for r in dto.get_relations()
1451
+ if isinstance(r, UniquePropertyValueConstraint)
1452
+ ]
1453
+ for relation in unique_property_value_constraints:
1454
+ json_data[relation.property_name] = relation.value
1455
+ # create a new resource that the original request will conflict with
1456
+ if method in ["patch", "put"]:
1457
+ post_url_parts = url.split("/")[:-1]
1458
+ post_url = "/".join(post_url_parts)
1459
+ # the PATCH or PUT may use a different dto than required for POST
1460
+ # so a valid POST dto must be constructed
1461
+ endpoint = post_url.replace(self.base_url, "")
1462
+ request_data = self.get_request_data(endpoint=endpoint, method="post")
1463
+ post_json = request_data.dto.as_dict()
1464
+ for key in post_json.keys():
1465
+ if key in json_data:
1466
+ post_json[key] = json_data.get(key)
1467
+ else:
1468
+ post_url = url
1469
+ post_json = json_data
1470
+ endpoint = post_url.replace(self.base_url, "")
1471
+ request_data = self.get_request_data(endpoint=endpoint, method="post")
1472
+ response: Response = run_keyword(
1473
+ "authorized_request",
1474
+ post_url,
1475
+ "post",
1476
+ request_data.params,
1477
+ request_data.headers,
1478
+ post_json,
1479
+ )
1480
+ # conflicting resource may already exist
1481
+ assert (
1482
+ response.ok or response.status_code == conflict_status_code
1483
+ ), f"get_json_data_with_conflict received {response.status_code}: {response.json()}"
1484
+ return json_data
1485
+ raise ValueError(
1486
+ f"No UniquePropertyValueConstraint in the get_relations list on dto {dto}."
1487
+ )
1488
+
1489
+ @keyword
1490
+ def authorized_request( # pylint: disable=too-many-arguments
1491
+ self,
1492
+ url: str,
1493
+ method: str,
1494
+ params: Optional[Dict[str, Any]] = None,
1495
+ headers: Optional[Dict[str, str]] = None,
1496
+ json_data: Optional[JSON] = None,
1497
+ ) -> Response:
1498
+ """
1499
+ Perform a request using the security token or authentication set in the library.
1500
+
1501
+ > Note: provided username / password or auth objects take precedence over token
1502
+ based security
1503
+ """
1504
+ headers = headers if headers else {}
1505
+ if self.extra_headers:
1506
+ headers.update(self.extra_headers)
1507
+ # if both an auth object and a token are available, auth takes precedence
1508
+ if self.security_token and not self.auth:
1509
+ security_header = {"Authorization": self.security_token}
1510
+ headers.update(security_header)
1511
+ headers = {k: str(v) for k, v in headers.items()}
1512
+ response = self.session.request(
1513
+ url=url,
1514
+ method=method,
1515
+ params=params,
1516
+ headers=headers,
1517
+ json=json_data,
1518
+ cookies=self.cookies,
1519
+ auth=self.auth,
1520
+ proxies=self.proxies,
1521
+ verify=self.verify,
1522
+ cert=self.cert,
1523
+ )
1524
+ logger.debug(f"Response text: {response.text}")
1525
+ return response