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.
- OpenApiDriver/openapi_executors.py +748 -743
- OpenApiDriver/openapi_reader.py +2 -1
- OpenApiDriver/openapidriver.libspec +2 -2
- OpenApiDriver/openapidriver.py +2 -2
- OpenApiLibCore/openapi_libcore.libspec +16 -16
- OpenApiLibCore/openapi_libcore.py +1525 -1492
- {robotframework_openapitools-0.1.1.dist-info → robotframework_openapitools-0.1.3.dist-info}/METADATA +2 -2
- {robotframework_openapitools-0.1.1.dist-info → robotframework_openapitools-0.1.3.dist-info}/RECORD +10 -10
- {robotframework_openapitools-0.1.1.dist-info → robotframework_openapitools-0.1.3.dist-info}/LICENSE +0 -0
- {robotframework_openapitools-0.1.1.dist-info → robotframework_openapitools-0.1.3.dist-info}/WHEEL +0 -0
@@ -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
|
123
|
-
|
124
|
-
from
|
125
|
-
from
|
126
|
-
from
|
127
|
-
from
|
128
|
-
from
|
129
|
-
from
|
130
|
-
from
|
131
|
-
from
|
132
|
-
|
133
|
-
|
134
|
-
from openapi_core
|
135
|
-
|
136
|
-
|
137
|
-
|
138
|
-
|
139
|
-
from prance
|
140
|
-
from
|
141
|
-
from requests
|
142
|
-
from requests.
|
143
|
-
from
|
144
|
-
from robot.
|
145
|
-
|
146
|
-
|
147
|
-
from OpenApiLibCore
|
148
|
-
|
149
|
-
|
150
|
-
|
151
|
-
|
152
|
-
|
153
|
-
|
154
|
-
|
155
|
-
|
156
|
-
|
157
|
-
|
158
|
-
|
159
|
-
|
160
|
-
|
161
|
-
|
162
|
-
|
163
|
-
|
164
|
-
|
165
|
-
from OpenApiLibCore.
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
key = key.replace("
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
|
189
|
-
|
190
|
-
|
191
|
-
|
192
|
-
|
193
|
-
|
194
|
-
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
|
199
|
-
|
200
|
-
|
201
|
-
|
202
|
-
|
203
|
-
|
204
|
-
|
205
|
-
|
206
|
-
|
207
|
-
|
208
|
-
|
209
|
-
self.
|
210
|
-
self.
|
211
|
-
|
212
|
-
|
213
|
-
|
214
|
-
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
|
222
|
-
|
223
|
-
|
224
|
-
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
|
229
|
-
|
230
|
-
|
231
|
-
|
232
|
-
|
233
|
-
|
234
|
-
|
235
|
-
|
236
|
-
|
237
|
-
|
238
|
-
|
239
|
-
|
240
|
-
|
241
|
-
|
242
|
-
|
243
|
-
|
244
|
-
|
245
|
-
|
246
|
-
|
247
|
-
|
248
|
-
|
249
|
-
|
250
|
-
|
251
|
-
|
252
|
-
|
253
|
-
|
254
|
-
param_types = schema
|
255
|
-
|
256
|
-
|
257
|
-
|
258
|
-
|
259
|
-
|
260
|
-
|
261
|
-
|
262
|
-
|
263
|
-
|
264
|
-
|
265
|
-
|
266
|
-
"
|
267
|
-
"
|
268
|
-
"
|
269
|
-
|
270
|
-
|
271
|
-
|
272
|
-
|
273
|
-
|
274
|
-
|
275
|
-
|
276
|
-
|
277
|
-
]
|
278
|
-
"
|
279
|
-
|
280
|
-
"
|
281
|
-
"
|
282
|
-
|
283
|
-
|
284
|
-
|
285
|
-
|
286
|
-
|
287
|
-
|
288
|
-
|
289
|
-
|
290
|
-
|
291
|
-
|
292
|
-
|
293
|
-
|
294
|
-
|
295
|
-
|
296
|
-
|
297
|
-
|
298
|
-
|
299
|
-
|
300
|
-
|
301
|
-
|
302
|
-
|
303
|
-
|
304
|
-
|
305
|
-
|
306
|
-
|
307
|
-
|
308
|
-
|
309
|
-
|
310
|
-
|
311
|
-
|
312
|
-
|
313
|
-
|
314
|
-
|
315
|
-
|
316
|
-
|
317
|
-
|
318
|
-
header_types = schema
|
319
|
-
|
320
|
-
|
321
|
-
|
322
|
-
|
323
|
-
|
324
|
-
|
325
|
-
|
326
|
-
|
327
|
-
|
328
|
-
|
329
|
-
|
330
|
-
"
|
331
|
-
"
|
332
|
-
"
|
333
|
-
|
334
|
-
|
335
|
-
|
336
|
-
|
337
|
-
|
338
|
-
|
339
|
-
|
340
|
-
|
341
|
-
]
|
342
|
-
"
|
343
|
-
|
344
|
-
"
|
345
|
-
"
|
346
|
-
|
347
|
-
|
348
|
-
|
349
|
-
|
350
|
-
|
351
|
-
|
352
|
-
|
353
|
-
|
354
|
-
|
355
|
-
|
356
|
-
|
357
|
-
|
358
|
-
|
359
|
-
|
360
|
-
|
361
|
-
|
362
|
-
|
363
|
-
|
364
|
-
|
365
|
-
|
366
|
-
|
367
|
-
|
368
|
-
|
369
|
-
|
370
|
-
|
371
|
-
|
372
|
-
|
373
|
-
|
374
|
-
|
375
|
-
|
376
|
-
|
377
|
-
|
378
|
-
|
379
|
-
|
380
|
-
|
381
|
-
|
382
|
-
|
383
|
-
|
384
|
-
|
385
|
-
|
386
|
-
|
387
|
-
|
388
|
-
|
389
|
-
|
390
|
-
|
391
|
-
|
392
|
-
|
393
|
-
|
394
|
-
|
395
|
-
|
396
|
-
|
397
|
-
|
398
|
-
|
399
|
-
|
400
|
-
|
401
|
-
|
402
|
-
|
403
|
-
|
404
|
-
|
405
|
-
|
406
|
-
|
407
|
-
|
408
|
-
|
409
|
-
|
410
|
-
|
411
|
-
|
412
|
-
|
413
|
-
|
414
|
-
|
415
|
-
|
416
|
-
|
417
|
-
|
418
|
-
|
419
|
-
|
420
|
-
|
421
|
-
|
422
|
-
|
423
|
-
|
424
|
-
|
425
|
-
|
426
|
-
|
427
|
-
|
428
|
-
|
429
|
-
|
430
|
-
|
431
|
-
|
432
|
-
|
433
|
-
The default
|
434
|
-
|
435
|
-
|
436
|
-
|
437
|
-
|
438
|
-
|
439
|
-
|
440
|
-
|
441
|
-
|
442
|
-
|
443
|
-
|
444
|
-
|
445
|
-
|
446
|
-
|
447
|
-
|
448
|
-
|
449
|
-
|
450
|
-
|
451
|
-
|
452
|
-
|
453
|
-
The
|
454
|
-
|
455
|
-
|
456
|
-
|
457
|
-
|
458
|
-
|
459
|
-
|
460
|
-
|
461
|
-
|
462
|
-
|
463
|
-
|
464
|
-
|
465
|
-
|
466
|
-
|
467
|
-
|
468
|
-
|
469
|
-
|
470
|
-
|
471
|
-
|
472
|
-
|
473
|
-
|
474
|
-
|
475
|
-
|
476
|
-
|
477
|
-
|
478
|
-
|
479
|
-
|
480
|
-
|
481
|
-
|
482
|
-
|
483
|
-
|
484
|
-
|
485
|
-
|
486
|
-
|
487
|
-
|
488
|
-
|
489
|
-
|
490
|
-
|
491
|
-
|
492
|
-
|
493
|
-
|
494
|
-
|
495
|
-
|
496
|
-
|
497
|
-
|
498
|
-
|
499
|
-
self.
|
500
|
-
self.
|
501
|
-
self.
|
502
|
-
self.
|
503
|
-
|
504
|
-
|
505
|
-
|
506
|
-
|
507
|
-
|
508
|
-
|
509
|
-
|
510
|
-
|
511
|
-
|
512
|
-
|
513
|
-
|
514
|
-
|
515
|
-
self.
|
516
|
-
self.
|
517
|
-
self.
|
518
|
-
self.
|
519
|
-
|
520
|
-
|
521
|
-
|
522
|
-
|
523
|
-
|
524
|
-
|
525
|
-
|
526
|
-
|
527
|
-
|
528
|
-
|
529
|
-
|
530
|
-
|
531
|
-
|
532
|
-
|
533
|
-
|
534
|
-
|
535
|
-
|
536
|
-
|
537
|
-
|
538
|
-
|
539
|
-
|
540
|
-
|
541
|
-
|
542
|
-
|
543
|
-
|
544
|
-
|
545
|
-
|
546
|
-
|
547
|
-
|
548
|
-
|
549
|
-
|
550
|
-
|
551
|
-
|
552
|
-
|
553
|
-
|
554
|
-
|
555
|
-
|
556
|
-
|
557
|
-
|
558
|
-
|
559
|
-
|
560
|
-
|
561
|
-
|
562
|
-
|
563
|
-
|
564
|
-
|
565
|
-
|
566
|
-
|
567
|
-
|
568
|
-
|
569
|
-
|
570
|
-
|
571
|
-
|
572
|
-
|
573
|
-
|
574
|
-
|
575
|
-
|
576
|
-
|
577
|
-
|
578
|
-
|
579
|
-
|
580
|
-
|
581
|
-
|
582
|
-
|
583
|
-
|
584
|
-
|
585
|
-
|
586
|
-
|
587
|
-
|
588
|
-
|
589
|
-
|
590
|
-
|
591
|
-
|
592
|
-
|
593
|
-
|
594
|
-
|
595
|
-
|
596
|
-
|
597
|
-
|
598
|
-
|
599
|
-
|
600
|
-
|
601
|
-
|
602
|
-
|
603
|
-
|
604
|
-
|
605
|
-
|
606
|
-
|
607
|
-
|
608
|
-
|
609
|
-
|
610
|
-
|
611
|
-
|
612
|
-
|
613
|
-
|
614
|
-
|
615
|
-
|
616
|
-
|
617
|
-
|
618
|
-
|
619
|
-
|
620
|
-
|
621
|
-
|
622
|
-
|
623
|
-
|
624
|
-
|
625
|
-
|
626
|
-
|
627
|
-
|
628
|
-
|
629
|
-
|
630
|
-
|
631
|
-
|
632
|
-
|
633
|
-
|
634
|
-
|
635
|
-
|
636
|
-
|
637
|
-
|
638
|
-
|
639
|
-
|
640
|
-
|
641
|
-
|
642
|
-
|
643
|
-
|
644
|
-
|
645
|
-
|
646
|
-
|
647
|
-
|
648
|
-
"""
|
649
|
-
|
650
|
-
|
651
|
-
|
652
|
-
|
653
|
-
|
654
|
-
|
655
|
-
|
656
|
-
|
657
|
-
|
658
|
-
|
659
|
-
|
660
|
-
|
661
|
-
|
662
|
-
|
663
|
-
|
664
|
-
|
665
|
-
|
666
|
-
|
667
|
-
|
668
|
-
|
669
|
-
|
670
|
-
|
671
|
-
|
672
|
-
|
673
|
-
|
674
|
-
|
675
|
-
|
676
|
-
|
677
|
-
|
678
|
-
|
679
|
-
|
680
|
-
|
681
|
-
|
682
|
-
|
683
|
-
|
684
|
-
|
685
|
-
|
686
|
-
|
687
|
-
|
688
|
-
|
689
|
-
|
690
|
-
|
691
|
-
|
692
|
-
|
693
|
-
|
694
|
-
|
695
|
-
|
696
|
-
|
697
|
-
|
698
|
-
|
699
|
-
|
700
|
-
|
701
|
-
|
702
|
-
|
703
|
-
|
704
|
-
|
705
|
-
|
706
|
-
)
|
707
|
-
|
708
|
-
|
709
|
-
|
710
|
-
|
711
|
-
|
712
|
-
|
713
|
-
|
714
|
-
|
715
|
-
|
716
|
-
|
717
|
-
|
718
|
-
|
719
|
-
|
720
|
-
|
721
|
-
|
722
|
-
|
723
|
-
|
724
|
-
|
725
|
-
|
726
|
-
|
727
|
-
|
728
|
-
|
729
|
-
|
730
|
-
|
731
|
-
|
732
|
-
|
733
|
-
|
734
|
-
|
735
|
-
|
736
|
-
|
737
|
-
|
738
|
-
|
739
|
-
if
|
740
|
-
|
741
|
-
|
742
|
-
|
743
|
-
|
744
|
-
|
745
|
-
|
746
|
-
|
747
|
-
#
|
748
|
-
|
749
|
-
|
750
|
-
|
751
|
-
|
752
|
-
|
753
|
-
|
754
|
-
|
755
|
-
|
756
|
-
|
757
|
-
|
758
|
-
|
759
|
-
|
760
|
-
|
761
|
-
|
762
|
-
|
763
|
-
) from
|
764
|
-
|
765
|
-
|
766
|
-
|
767
|
-
|
768
|
-
|
769
|
-
|
770
|
-
|
771
|
-
|
772
|
-
|
773
|
-
|
774
|
-
|
775
|
-
|
776
|
-
|
777
|
-
|
778
|
-
|
779
|
-
|
780
|
-
|
781
|
-
|
782
|
-
|
783
|
-
|
784
|
-
|
785
|
-
|
786
|
-
|
787
|
-
|
788
|
-
|
789
|
-
|
790
|
-
|
791
|
-
|
792
|
-
|
793
|
-
|
794
|
-
|
795
|
-
|
796
|
-
|
797
|
-
|
798
|
-
|
799
|
-
|
800
|
-
|
801
|
-
|
802
|
-
if
|
803
|
-
|
804
|
-
|
805
|
-
|
806
|
-
|
807
|
-
|
808
|
-
|
809
|
-
return
|
810
|
-
|
811
|
-
|
812
|
-
|
813
|
-
|
814
|
-
|
815
|
-
|
816
|
-
|
817
|
-
|
818
|
-
|
819
|
-
|
820
|
-
|
821
|
-
|
822
|
-
|
823
|
-
|
824
|
-
|
825
|
-
|
826
|
-
|
827
|
-
|
828
|
-
|
829
|
-
|
830
|
-
|
831
|
-
|
832
|
-
|
833
|
-
|
834
|
-
|
835
|
-
|
836
|
-
|
837
|
-
|
838
|
-
|
839
|
-
|
840
|
-
|
841
|
-
|
842
|
-
|
843
|
-
|
844
|
-
|
845
|
-
|
846
|
-
|
847
|
-
|
848
|
-
|
849
|
-
|
850
|
-
|
851
|
-
|
852
|
-
|
853
|
-
|
854
|
-
|
855
|
-
|
856
|
-
|
857
|
-
|
858
|
-
|
859
|
-
|
860
|
-
|
861
|
-
|
862
|
-
|
863
|
-
|
864
|
-
|
865
|
-
|
866
|
-
|
867
|
-
|
868
|
-
|
869
|
-
|
870
|
-
|
871
|
-
|
872
|
-
|
873
|
-
|
874
|
-
|
875
|
-
|
876
|
-
|
877
|
-
|
878
|
-
|
879
|
-
|
880
|
-
|
881
|
-
|
882
|
-
|
883
|
-
|
884
|
-
|
885
|
-
|
886
|
-
):
|
887
|
-
|
888
|
-
|
889
|
-
|
890
|
-
|
891
|
-
|
892
|
-
|
893
|
-
|
894
|
-
|
895
|
-
|
896
|
-
|
897
|
-
|
898
|
-
|
899
|
-
|
900
|
-
|
901
|
-
|
902
|
-
|
903
|
-
|
904
|
-
|
905
|
-
|
906
|
-
|
907
|
-
|
908
|
-
|
909
|
-
|
910
|
-
|
911
|
-
|
912
|
-
|
913
|
-
|
914
|
-
|
915
|
-
|
916
|
-
|
917
|
-
|
918
|
-
|
919
|
-
"""Get the
|
920
|
-
|
921
|
-
|
922
|
-
|
923
|
-
|
924
|
-
|
925
|
-
|
926
|
-
|
927
|
-
|
928
|
-
|
929
|
-
|
930
|
-
|
931
|
-
|
932
|
-
|
933
|
-
|
934
|
-
|
935
|
-
|
936
|
-
|
937
|
-
|
938
|
-
|
939
|
-
|
940
|
-
|
941
|
-
|
942
|
-
|
943
|
-
|
944
|
-
|
945
|
-
|
946
|
-
|
947
|
-
|
948
|
-
|
949
|
-
|
950
|
-
|
951
|
-
|
952
|
-
|
953
|
-
|
954
|
-
|
955
|
-
|
956
|
-
|
957
|
-
|
958
|
-
|
959
|
-
|
960
|
-
|
961
|
-
|
962
|
-
|
963
|
-
|
964
|
-
|
965
|
-
|
966
|
-
|
967
|
-
|
968
|
-
|
969
|
-
#
|
970
|
-
#
|
971
|
-
|
972
|
-
|
973
|
-
|
974
|
-
|
975
|
-
|
976
|
-
|
977
|
-
|
978
|
-
|
979
|
-
|
980
|
-
|
981
|
-
|
982
|
-
|
983
|
-
|
984
|
-
|
985
|
-
|
986
|
-
|
987
|
-
|
988
|
-
|
989
|
-
|
990
|
-
|
991
|
-
|
992
|
-
|
993
|
-
|
994
|
-
|
995
|
-
|
996
|
-
|
997
|
-
|
998
|
-
|
999
|
-
|
1000
|
-
|
1001
|
-
|
1002
|
-
|
1003
|
-
|
1004
|
-
|
1005
|
-
|
1006
|
-
|
1007
|
-
|
1008
|
-
|
1009
|
-
|
1010
|
-
|
1011
|
-
|
1012
|
-
|
1013
|
-
|
1014
|
-
|
1015
|
-
|
1016
|
-
|
1017
|
-
|
1018
|
-
|
1019
|
-
|
1020
|
-
|
1021
|
-
|
1022
|
-
if
|
1023
|
-
|
1024
|
-
|
1025
|
-
|
1026
|
-
|
1027
|
-
|
1028
|
-
|
1029
|
-
|
1030
|
-
|
1031
|
-
|
1032
|
-
|
1033
|
-
|
1034
|
-
|
1035
|
-
|
1036
|
-
|
1037
|
-
|
1038
|
-
|
1039
|
-
|
1040
|
-
|
1041
|
-
|
1042
|
-
|
1043
|
-
|
1044
|
-
|
1045
|
-
|
1046
|
-
|
1047
|
-
|
1048
|
-
|
1049
|
-
|
1050
|
-
|
1051
|
-
|
1052
|
-
|
1053
|
-
|
1054
|
-
|
1055
|
-
|
1056
|
-
|
1057
|
-
|
1058
|
-
|
1059
|
-
|
1060
|
-
|
1061
|
-
|
1062
|
-
|
1063
|
-
|
1064
|
-
|
1065
|
-
|
1066
|
-
if
|
1067
|
-
|
1068
|
-
|
1069
|
-
|
1070
|
-
|
1071
|
-
|
1072
|
-
|
1073
|
-
|
1074
|
-
|
1075
|
-
|
1076
|
-
|
1077
|
-
|
1078
|
-
|
1079
|
-
|
1080
|
-
|
1081
|
-
|
1082
|
-
|
1083
|
-
|
1084
|
-
|
1085
|
-
|
1086
|
-
|
1087
|
-
|
1088
|
-
|
1089
|
-
|
1090
|
-
|
1091
|
-
|
1092
|
-
|
1093
|
-
|
1094
|
-
|
1095
|
-
|
1096
|
-
|
1097
|
-
|
1098
|
-
|
1099
|
-
|
1100
|
-
|
1101
|
-
|
1102
|
-
|
1103
|
-
|
1104
|
-
|
1105
|
-
|
1106
|
-
|
1107
|
-
|
1108
|
-
|
1109
|
-
|
1110
|
-
|
1111
|
-
|
1112
|
-
|
1113
|
-
|
1114
|
-
|
1115
|
-
|
1116
|
-
|
1117
|
-
|
1118
|
-
|
1119
|
-
|
1120
|
-
|
1121
|
-
|
1122
|
-
|
1123
|
-
|
1124
|
-
|
1125
|
-
|
1126
|
-
|
1127
|
-
|
1128
|
-
|
1129
|
-
|
1130
|
-
|
1131
|
-
|
1132
|
-
|
1133
|
-
|
1134
|
-
|
1135
|
-
|
1136
|
-
|
1137
|
-
|
1138
|
-
|
1139
|
-
|
1140
|
-
|
1141
|
-
|
1142
|
-
|
1143
|
-
|
1144
|
-
|
1145
|
-
|
1146
|
-
|
1147
|
-
|
1148
|
-
|
1149
|
-
|
1150
|
-
|
1151
|
-
|
1152
|
-
|
1153
|
-
|
1154
|
-
|
1155
|
-
|
1156
|
-
|
1157
|
-
|
1158
|
-
|
1159
|
-
|
1160
|
-
|
1161
|
-
|
1162
|
-
|
1163
|
-
|
1164
|
-
|
1165
|
-
|
1166
|
-
|
1167
|
-
|
1168
|
-
|
1169
|
-
|
1170
|
-
|
1171
|
-
|
1172
|
-
|
1173
|
-
|
1174
|
-
|
1175
|
-
|
1176
|
-
|
1177
|
-
|
1178
|
-
|
1179
|
-
|
1180
|
-
|
1181
|
-
|
1182
|
-
|
1183
|
-
|
1184
|
-
|
1185
|
-
|
1186
|
-
|
1187
|
-
|
1188
|
-
|
1189
|
-
|
1190
|
-
|
1191
|
-
|
1192
|
-
|
1193
|
-
|
1194
|
-
|
1195
|
-
|
1196
|
-
|
1197
|
-
|
1198
|
-
|
1199
|
-
|
1200
|
-
|
1201
|
-
|
1202
|
-
|
1203
|
-
|
1204
|
-
|
1205
|
-
|
1206
|
-
)
|
1207
|
-
|
1208
|
-
|
1209
|
-
|
1210
|
-
|
1211
|
-
|
1212
|
-
|
1213
|
-
|
1214
|
-
|
1215
|
-
|
1216
|
-
|
1217
|
-
|
1218
|
-
|
1219
|
-
|
1220
|
-
|
1221
|
-
|
1222
|
-
|
1223
|
-
|
1224
|
-
|
1225
|
-
|
1226
|
-
|
1227
|
-
|
1228
|
-
|
1229
|
-
)
|
1230
|
-
|
1231
|
-
|
1232
|
-
|
1233
|
-
|
1234
|
-
|
1235
|
-
|
1236
|
-
|
1237
|
-
|
1238
|
-
|
1239
|
-
|
1240
|
-
|
1241
|
-
|
1242
|
-
|
1243
|
-
|
1244
|
-
|
1245
|
-
|
1246
|
-
|
1247
|
-
|
1248
|
-
|
1249
|
-
|
1250
|
-
|
1251
|
-
|
1252
|
-
|
1253
|
-
|
1254
|
-
|
1255
|
-
|
1256
|
-
|
1257
|
-
|
1258
|
-
|
1259
|
-
|
1260
|
-
|
1261
|
-
|
1262
|
-
|
1263
|
-
|
1264
|
-
|
1265
|
-
|
1266
|
-
|
1267
|
-
|
1268
|
-
|
1269
|
-
|
1270
|
-
|
1271
|
-
|
1272
|
-
|
1273
|
-
#
|
1274
|
-
|
1275
|
-
|
1276
|
-
|
1277
|
-
|
1278
|
-
|
1279
|
-
|
1280
|
-
|
1281
|
-
|
1282
|
-
|
1283
|
-
|
1284
|
-
|
1285
|
-
|
1286
|
-
|
1287
|
-
|
1288
|
-
|
1289
|
-
|
1290
|
-
|
1291
|
-
|
1292
|
-
|
1293
|
-
|
1294
|
-
#
|
1295
|
-
|
1296
|
-
|
1297
|
-
|
1298
|
-
|
1299
|
-
|
1300
|
-
|
1301
|
-
|
1302
|
-
|
1303
|
-
|
1304
|
-
|
1305
|
-
|
1306
|
-
|
1307
|
-
|
1308
|
-
|
1309
|
-
|
1310
|
-
|
1311
|
-
|
1312
|
-
|
1313
|
-
|
1314
|
-
|
1315
|
-
|
1316
|
-
|
1317
|
-
|
1318
|
-
|
1319
|
-
|
1320
|
-
|
1321
|
-
|
1322
|
-
|
1323
|
-
|
1324
|
-
|
1325
|
-
|
1326
|
-
|
1327
|
-
|
1328
|
-
|
1329
|
-
|
1330
|
-
|
1331
|
-
|
1332
|
-
|
1333
|
-
|
1334
|
-
|
1335
|
-
|
1336
|
-
|
1337
|
-
|
1338
|
-
|
1339
|
-
|
1340
|
-
parameter_to_invalidate
|
1341
|
-
|
1342
|
-
|
1343
|
-
|
1344
|
-
|
1345
|
-
|
1346
|
-
|
1347
|
-
|
1348
|
-
|
1349
|
-
|
1350
|
-
|
1351
|
-
|
1352
|
-
|
1353
|
-
|
1354
|
-
|
1355
|
-
|
1356
|
-
|
1357
|
-
|
1358
|
-
return params, headers
|
1359
|
-
|
1360
|
-
@
|
1361
|
-
def
|
1362
|
-
|
1363
|
-
|
1364
|
-
|
1365
|
-
|
1366
|
-
|
1367
|
-
|
1368
|
-
|
1369
|
-
|
1370
|
-
|
1371
|
-
|
1372
|
-
|
1373
|
-
|
1374
|
-
|
1375
|
-
|
1376
|
-
|
1377
|
-
|
1378
|
-
|
1379
|
-
|
1380
|
-
|
1381
|
-
|
1382
|
-
|
1383
|
-
|
1384
|
-
|
1385
|
-
|
1386
|
-
|
1387
|
-
|
1388
|
-
|
1389
|
-
|
1390
|
-
|
1391
|
-
|
1392
|
-
|
1393
|
-
|
1394
|
-
|
1395
|
-
|
1396
|
-
|
1397
|
-
|
1398
|
-
|
1399
|
-
|
1400
|
-
|
1401
|
-
|
1402
|
-
|
1403
|
-
|
1404
|
-
|
1405
|
-
|
1406
|
-
|
1407
|
-
|
1408
|
-
|
1409
|
-
|
1410
|
-
|
1411
|
-
|
1412
|
-
|
1413
|
-
|
1414
|
-
|
1415
|
-
|
1416
|
-
|
1417
|
-
|
1418
|
-
|
1419
|
-
|
1420
|
-
|
1421
|
-
|
1422
|
-
|
1423
|
-
|
1424
|
-
|
1425
|
-
|
1426
|
-
|
1427
|
-
|
1428
|
-
|
1429
|
-
|
1430
|
-
|
1431
|
-
|
1432
|
-
|
1433
|
-
|
1434
|
-
|
1435
|
-
|
1436
|
-
|
1437
|
-
|
1438
|
-
|
1439
|
-
|
1440
|
-
|
1441
|
-
|
1442
|
-
|
1443
|
-
|
1444
|
-
|
1445
|
-
|
1446
|
-
|
1447
|
-
|
1448
|
-
|
1449
|
-
|
1450
|
-
|
1451
|
-
|
1452
|
-
|
1453
|
-
|
1454
|
-
|
1455
|
-
|
1456
|
-
|
1457
|
-
|
1458
|
-
|
1459
|
-
|
1460
|
-
|
1461
|
-
|
1462
|
-
|
1463
|
-
|
1464
|
-
|
1465
|
-
|
1466
|
-
|
1467
|
-
|
1468
|
-
|
1469
|
-
|
1470
|
-
|
1471
|
-
|
1472
|
-
|
1473
|
-
|
1474
|
-
|
1475
|
-
|
1476
|
-
|
1477
|
-
|
1478
|
-
|
1479
|
-
|
1480
|
-
|
1481
|
-
|
1482
|
-
|
1483
|
-
|
1484
|
-
|
1485
|
-
|
1486
|
-
|
1487
|
-
|
1488
|
-
|
1489
|
-
|
1490
|
-
|
1491
|
-
|
1492
|
-
|
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
|