summaryrefslogtreecommitdiff
path: root/python-apiritif.spec
blob: 664018db62fbe077272578603c5a4af550f01b29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
210
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
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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
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
803
804
805
806
807
808
809
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
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
%global _empty_manifest_terminate_build 0
Name:		python-apiritif
Version:	1.1.3
Release:	1
Summary:	Python framework for API testing
License:	Apache 2.0
URL:		https://github.com/Blazemeter/apiritif
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/3f/49/1b639130c415badb18aa4cceb9f6ae0af80c7c528b247cc2542b9b746838/apiritif-1.1.3.tar.gz
BuildArch:	noarch

Requires:	python3-nose2
Requires:	python3-pytest
Requires:	python3-requests
Requires:	python3-jsonpath-ng
Requires:	python3-lxml
Requires:	python3-unicodecsv
Requires:	python3-cssselect
Requires:	python3-chardet
Requires:	python3-pyopenssl
Requires:	python3-codecov

%description
# Apiritif

Apiritif is a number of utilities aimed to simplify the process of maintaining API tests. 
Apiritif tests fully based on python nose tests. This library can help you to develop and run your existing tests.
In order to create any valid tests for Apiritif you can read [nose test documentation](https://nose.readthedocs.io/en/latest/testing.html).

Check Apiritif version with the following command:
```
python -m apiritif -- version
```

Here described some features of Apiritif which can help you to create tests more easily.  

## Overview

## HTTP Requests

Apiritif allows to use simple `requests`-like API for making HTTP requests.

```python
from apiritif import http

response = http.get("http://example.com")
response.assert_ok()  # will raise AssertionError if request wasn't successful
```

`http` object provides the following methods:
```python
from apiritif import http

http.get("http://api.example.com/posts")
http.post("http://api.example.com/posts")
http.put("http://api.example.com/posts/1")
http.patch("http://api.example.com/posts/1")
http.delete("http://api.example.com/posts/1")
http.head("http://api.example.com/posts")
```

All methods (`get`, `post`, `put`, `patch`, `delete`, `head`) support the following arguments:
```python
def get(address,               # URL for the request
        params=None,           # URL params dict
        headers=None,          # HTTP headers
        cookies=None,          # request cookies
        data=None,             # raw request data
        json=None,             # attach JSON object as request body
        encrypted_cert=None,   # certificate to use with request 
        allow_redirects=True,  # automatically follow HTTP redirects
        timeout=30)            # request timeout, by default it's 30 seconds
```

##### Certificate usage
Currently `http` supports `pem` and `pkcs12` certificates. 
Here is an example of certificate usage:
```python
http.get("http://api.example.com/posts", encrypted_cert=('./cert.pem', 'passphrase'))
```
First parameter is path to certificate, second is the passphrase certificate encrypted with.

## HTTP Targets

Target is an object that captures resource name of the URL (protocol, domain, port)
and allows to set some settings applied to all requests made for a target.


```python
from apiritif import http

qa_env = http.target("http://192.160.0.2")
qa_env.get("/api/v4/user")
qa_env.get("/api/v4/user")
```

Target constructor supports the following options:
```python
target = apiritif.http.target(
    address,               # target base address
    base_path=None,        # base path prepended to all paths (e.g. '/api/v2')
    use_cookies=True,      # use cookies
    additional_headers=None,  # additional headers for all requests
    keep_alive=True,       # reuse opened HTTP connection
    auto_assert_ok=True,   # automatically invoke 'assert_ok' after each request
)
```


## Assertions

Apiritif responses provide a lot of useful assertions that can be used on responses.

Here's the list of assertions that can be used:
```python
response = http.get("http://example.com/")

# assert that request succeeded (status code is 2xx or 3xx)
response.assert_ok()
# assert that request has failed
response.assert_failed()

# status code based assertions
response.assert_2xx()
response.assert_3xx()
response.assert_4xx()
response.assert_5xx()
response.assert_status_code(code)
response.assert_not_status_code(code)
response.assert_status_code_in(codes)

# content-based assertions

# assert that response body contains a string
response.assert_in_body(member)

# assert that response body doesn't contain a string
response.assert_not_in_body(member)

# search (or match) response body with a regex
response.assert_regex_in_body(regex, match=False)
response.assert_regex_not_in_body(regex, match=False)

# assert that response has header
response.assert_has_header(header)

# assert that response has header with given value
response.assert_header_value(header, value)

# assert that response's headers contains a string
response.assert_in_headers(member)
response.assert_not_in_headers(member)

# search (or match) response body with a regex
response.assert_regex_in_headers(member)
response.assert_regex_not_in_headers(member)

# assert that response body matches JSONPath query
response.assert_jsonpath(jsonpath_query, expected_value=None)
response.assert_not_jsonpath(jsonpath_query)

# assert that response body matches XPath query
response.assert_xpath(xpath_query, parser_type='html', validate=False)
response.assert_not_xpath(xpath_query, parser_type='html', validate=False)

# assert that HTML response body contains CSS selector item
response.assert_cssselect(selector, expected_value=None, attribute=None)
response.assert_not_cssselect(selector, expected_value=None, attribute=None)

```

Note that assertions can be chained, so the following construction is entirely valid:
```python

response = http.get("http://example.com/")
response.assert_ok().assert_in_body("Example")
```

## Transactions

Apiritif allows to group multiple requests or actions into a transaction using a `transaction` context manager.
For example when we have test action like bellow we want to execute requests according to concrete user as a separate piece.
Also we want to process test for `users/all` page even if something wrong with previous actions.

```python
def test_with_login():
    user_credentials = data_mock.get_my_user()
    http.get("https://blazedemo.com/user/login?id="+user_credentials.id).assert_ok()
    http.get("https://blazedemo.com/user/id/personalPage").assert_ok()
    http.get("https://blazedemo.com/user/id/getPersonalData").assert_ok()

    http.get("https://blazedemo.com/users/all").assert_ok()
```

Here where we can use transaction in order to wrap login process in one block.

```python
def test_with_login():
    with apiritif.transaction('Login'):
        user_credentials = data_mock.get_my_user()
        http.get("https://blazedemo.com/user/login?id="+user_credentials.id).assert_ok()
        http.get("https://blazedemo.com/user/id/personalPage").assert_ok()
        http.get("https://blazedemo.com/user/id/getPersonalData").assert_ok()

    http.get("https://blazedemo.com/users/all").assert_ok()
```
At the same time requests to `users/all` page will be executed outside of transaction even if something inside transaction fails.

Transaction defines the name for the block of code. This name with execution results of this particular block will be displayed in the output report.

#### Smart transactions

`smart_transaction` is advanced option for test flow control (stop or continue after failed test method).
Let see another test method example:

```python
class Tests(TestCase):
    def test_available_pages():
        http.get("https://blazedemo.com/").assert_ok()
        http.get("https://blazedemo.com/users").assert_ok()
    
        http.get("https://blazedemo.com/users/search").assert_ok()
        http.get("https://blazedemo.com/users/count").assert_ok()
        http.get("https://blazedemo.com/users/login").assert_ok()

        http.get("https://blazedemo.com/contactUs").assert_ok()
        http.get("https://blazedemo.com/copyright").assert_ok()
```
In this case we have multiple requests divided into blocks. I do not want to test pages under `users` space if it is not available.
For this purpose we can use `smart_transaction`.

```python
class Tests(TestCase):
    def setUp(self):
        apiritif.put_into_thread_store(func_mode=True)
    
    def test_available_pages():
        http.get("https://blazedemo.com/").assert_ok()

        with apiritif.smart_transaction('Availability check'):
            http.get("https://blazedemo.com/users").assert_ok()
    
        with apiritif.smart_transaction('Test users pages'):
            http.get("https://blazedemo.com/users/search").assert_ok()
            http.get("https://blazedemo.com/users/count").assert_ok()
            http.get("https://blazedemo.com/users/login").assert_ok()

        http.get("https://blazedemo.com/contactUs").assert_ok()
        http.get("https://blazedemo.com/copyright").assert_ok()
```
Now this two blocks are wrapped into `smart_transaction` which would help with error test flow handling and logging.

Also each transaction defines the name for the block of code and will be displayed in the output report.
 
Now about `apiritif.put_into_thread_store(func_mode=True)`, this is test execution mode for apiritif.
We can execute all of the transactions in test no matter what or stop after first failed transaction.
This flag tells to apiritif "Stop execution if some transaction failed". `False` says "Run till the end in any case".

##### Nose Flow Control
It's one more feature based on smart transactions. It changes `func_mode` if necessary to execute whole teardown block,
intended to finalize all necessary things.

```python
def test_flow-control(self):
        try:
            self._method_with_exception()
            self._skipped_method()
        finally:
            apiritif.set_stage("teardown")
            self._teardown1()
            self._teardown2()
```
If this test will be interrupted in `_method_with_exception`, both of teardown methods will be executed even if them raise exception.
Please note two differences with usage of `tearDown` method of nose:
1. all parts of teardown stage will be executed as mentioned above (will be interrupted in regular nose execution)
2. results of teardown steps will be written by apiritif SampleWriter into output file (nose lost them as tearDown isn't recognised as test).

##### Graceful shutdown
Somethimes waiting of end of test isn't necessary and we prefer to break it but save all current results and handle all teardown steps. (see above)
It's possible with GRACEFUL flag. To use it you can run apiritif with GRACEFUL environment variable pointed to any file name.
Apiritif will be interrupted as soon as the file is created.

## CSV Reader
In order to use data from csv file as test parameters Apiritif provides two different csv readers.
Simple `CSVReader` helps you to read data from file line by line and use this data wherever you need:

```python
data_reader = apiritif.CSVReader('---path to required file---')
class Tests(TestCase):
    def test_user_page():
        data_reader.read_vars()
        vars = data_reader.get_vars()
        http.get("https://blazedemo.com/users/" + vars.user_id).assert_ok()
```

In case of multithreading testing you may need to deviate data between threads and ysu uniq lines for each thread.
`CSVReaderPerThread` helps to solve this problem: 

```python
data_per_thread_reader = apiritif.CSVReaderPerThread('---path to required file---')
class Tests(TestCase):
    def setUp(self):
        data_per_thread_reader.read_vars()
        self.vars = data_per_thread_reader.get_vars()
    
    def test_user_page():
        http.get("https://blazedemo.com/users/" + self.vars.user_id).assert_ok()
```

## Execution results

Apiritif writes output data from tests in `apiritif.#.csv` files by default. Here `#` is number of executing process.
The output file is similar to this:
```csv
timeStamp,elapsed,Latency,label,responseCode,responseMessage,success,allThreads,bytes
1602759519185,0,0,Correct test,,,true,0,2
1602759519186,0,0,Correct transaction,,,true,0,2
1602759519187,0,0,Test with exception,,Exception: Horrible error,false,0,2
```  
It contains test and transaction results for executed tests by one process.

### Environment Variables

There are environment variables to control length of response/request body to be written into traces and logs:
  * `APIRITIF_TRACE_BODY_EXCLIMIT` - limit of body part to include into exception messages, default is 1024
  * `APIRITIF_TRACE_BODY_HARDLIMIT` - limit of body length to include into JSON trace records, default is unlimited




%package -n python3-apiritif
Summary:	Python framework for API testing
Provides:	python-apiritif
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-apiritif
# Apiritif

Apiritif is a number of utilities aimed to simplify the process of maintaining API tests. 
Apiritif tests fully based on python nose tests. This library can help you to develop and run your existing tests.
In order to create any valid tests for Apiritif you can read [nose test documentation](https://nose.readthedocs.io/en/latest/testing.html).

Check Apiritif version with the following command:
```
python -m apiritif -- version
```

Here described some features of Apiritif which can help you to create tests more easily.  

## Overview

## HTTP Requests

Apiritif allows to use simple `requests`-like API for making HTTP requests.

```python
from apiritif import http

response = http.get("http://example.com")
response.assert_ok()  # will raise AssertionError if request wasn't successful
```

`http` object provides the following methods:
```python
from apiritif import http

http.get("http://api.example.com/posts")
http.post("http://api.example.com/posts")
http.put("http://api.example.com/posts/1")
http.patch("http://api.example.com/posts/1")
http.delete("http://api.example.com/posts/1")
http.head("http://api.example.com/posts")
```

All methods (`get`, `post`, `put`, `patch`, `delete`, `head`) support the following arguments:
```python
def get(address,               # URL for the request
        params=None,           # URL params dict
        headers=None,          # HTTP headers
        cookies=None,          # request cookies
        data=None,             # raw request data
        json=None,             # attach JSON object as request body
        encrypted_cert=None,   # certificate to use with request 
        allow_redirects=True,  # automatically follow HTTP redirects
        timeout=30)            # request timeout, by default it's 30 seconds
```

##### Certificate usage
Currently `http` supports `pem` and `pkcs12` certificates. 
Here is an example of certificate usage:
```python
http.get("http://api.example.com/posts", encrypted_cert=('./cert.pem', 'passphrase'))
```
First parameter is path to certificate, second is the passphrase certificate encrypted with.

## HTTP Targets

Target is an object that captures resource name of the URL (protocol, domain, port)
and allows to set some settings applied to all requests made for a target.


```python
from apiritif import http

qa_env = http.target("http://192.160.0.2")
qa_env.get("/api/v4/user")
qa_env.get("/api/v4/user")
```

Target constructor supports the following options:
```python
target = apiritif.http.target(
    address,               # target base address
    base_path=None,        # base path prepended to all paths (e.g. '/api/v2')
    use_cookies=True,      # use cookies
    additional_headers=None,  # additional headers for all requests
    keep_alive=True,       # reuse opened HTTP connection
    auto_assert_ok=True,   # automatically invoke 'assert_ok' after each request
)
```


## Assertions

Apiritif responses provide a lot of useful assertions that can be used on responses.

Here's the list of assertions that can be used:
```python
response = http.get("http://example.com/")

# assert that request succeeded (status code is 2xx or 3xx)
response.assert_ok()
# assert that request has failed
response.assert_failed()

# status code based assertions
response.assert_2xx()
response.assert_3xx()
response.assert_4xx()
response.assert_5xx()
response.assert_status_code(code)
response.assert_not_status_code(code)
response.assert_status_code_in(codes)

# content-based assertions

# assert that response body contains a string
response.assert_in_body(member)

# assert that response body doesn't contain a string
response.assert_not_in_body(member)

# search (or match) response body with a regex
response.assert_regex_in_body(regex, match=False)
response.assert_regex_not_in_body(regex, match=False)

# assert that response has header
response.assert_has_header(header)

# assert that response has header with given value
response.assert_header_value(header, value)

# assert that response's headers contains a string
response.assert_in_headers(member)
response.assert_not_in_headers(member)

# search (or match) response body with a regex
response.assert_regex_in_headers(member)
response.assert_regex_not_in_headers(member)

# assert that response body matches JSONPath query
response.assert_jsonpath(jsonpath_query, expected_value=None)
response.assert_not_jsonpath(jsonpath_query)

# assert that response body matches XPath query
response.assert_xpath(xpath_query, parser_type='html', validate=False)
response.assert_not_xpath(xpath_query, parser_type='html', validate=False)

# assert that HTML response body contains CSS selector item
response.assert_cssselect(selector, expected_value=None, attribute=None)
response.assert_not_cssselect(selector, expected_value=None, attribute=None)

```

Note that assertions can be chained, so the following construction is entirely valid:
```python

response = http.get("http://example.com/")
response.assert_ok().assert_in_body("Example")
```

## Transactions

Apiritif allows to group multiple requests or actions into a transaction using a `transaction` context manager.
For example when we have test action like bellow we want to execute requests according to concrete user as a separate piece.
Also we want to process test for `users/all` page even if something wrong with previous actions.

```python
def test_with_login():
    user_credentials = data_mock.get_my_user()
    http.get("https://blazedemo.com/user/login?id="+user_credentials.id).assert_ok()
    http.get("https://blazedemo.com/user/id/personalPage").assert_ok()
    http.get("https://blazedemo.com/user/id/getPersonalData").assert_ok()

    http.get("https://blazedemo.com/users/all").assert_ok()
```

Here where we can use transaction in order to wrap login process in one block.

```python
def test_with_login():
    with apiritif.transaction('Login'):
        user_credentials = data_mock.get_my_user()
        http.get("https://blazedemo.com/user/login?id="+user_credentials.id).assert_ok()
        http.get("https://blazedemo.com/user/id/personalPage").assert_ok()
        http.get("https://blazedemo.com/user/id/getPersonalData").assert_ok()

    http.get("https://blazedemo.com/users/all").assert_ok()
```
At the same time requests to `users/all` page will be executed outside of transaction even if something inside transaction fails.

Transaction defines the name for the block of code. This name with execution results of this particular block will be displayed in the output report.

#### Smart transactions

`smart_transaction` is advanced option for test flow control (stop or continue after failed test method).
Let see another test method example:

```python
class Tests(TestCase):
    def test_available_pages():
        http.get("https://blazedemo.com/").assert_ok()
        http.get("https://blazedemo.com/users").assert_ok()
    
        http.get("https://blazedemo.com/users/search").assert_ok()
        http.get("https://blazedemo.com/users/count").assert_ok()
        http.get("https://blazedemo.com/users/login").assert_ok()

        http.get("https://blazedemo.com/contactUs").assert_ok()
        http.get("https://blazedemo.com/copyright").assert_ok()
```
In this case we have multiple requests divided into blocks. I do not want to test pages under `users` space if it is not available.
For this purpose we can use `smart_transaction`.

```python
class Tests(TestCase):
    def setUp(self):
        apiritif.put_into_thread_store(func_mode=True)
    
    def test_available_pages():
        http.get("https://blazedemo.com/").assert_ok()

        with apiritif.smart_transaction('Availability check'):
            http.get("https://blazedemo.com/users").assert_ok()
    
        with apiritif.smart_transaction('Test users pages'):
            http.get("https://blazedemo.com/users/search").assert_ok()
            http.get("https://blazedemo.com/users/count").assert_ok()
            http.get("https://blazedemo.com/users/login").assert_ok()

        http.get("https://blazedemo.com/contactUs").assert_ok()
        http.get("https://blazedemo.com/copyright").assert_ok()
```
Now this two blocks are wrapped into `smart_transaction` which would help with error test flow handling and logging.

Also each transaction defines the name for the block of code and will be displayed in the output report.
 
Now about `apiritif.put_into_thread_store(func_mode=True)`, this is test execution mode for apiritif.
We can execute all of the transactions in test no matter what or stop after first failed transaction.
This flag tells to apiritif "Stop execution if some transaction failed". `False` says "Run till the end in any case".

##### Nose Flow Control
It's one more feature based on smart transactions. It changes `func_mode` if necessary to execute whole teardown block,
intended to finalize all necessary things.

```python
def test_flow-control(self):
        try:
            self._method_with_exception()
            self._skipped_method()
        finally:
            apiritif.set_stage("teardown")
            self._teardown1()
            self._teardown2()
```
If this test will be interrupted in `_method_with_exception`, both of teardown methods will be executed even if them raise exception.
Please note two differences with usage of `tearDown` method of nose:
1. all parts of teardown stage will be executed as mentioned above (will be interrupted in regular nose execution)
2. results of teardown steps will be written by apiritif SampleWriter into output file (nose lost them as tearDown isn't recognised as test).

##### Graceful shutdown
Somethimes waiting of end of test isn't necessary and we prefer to break it but save all current results and handle all teardown steps. (see above)
It's possible with GRACEFUL flag. To use it you can run apiritif with GRACEFUL environment variable pointed to any file name.
Apiritif will be interrupted as soon as the file is created.

## CSV Reader
In order to use data from csv file as test parameters Apiritif provides two different csv readers.
Simple `CSVReader` helps you to read data from file line by line and use this data wherever you need:

```python
data_reader = apiritif.CSVReader('---path to required file---')
class Tests(TestCase):
    def test_user_page():
        data_reader.read_vars()
        vars = data_reader.get_vars()
        http.get("https://blazedemo.com/users/" + vars.user_id).assert_ok()
```

In case of multithreading testing you may need to deviate data between threads and ysu uniq lines for each thread.
`CSVReaderPerThread` helps to solve this problem: 

```python
data_per_thread_reader = apiritif.CSVReaderPerThread('---path to required file---')
class Tests(TestCase):
    def setUp(self):
        data_per_thread_reader.read_vars()
        self.vars = data_per_thread_reader.get_vars()
    
    def test_user_page():
        http.get("https://blazedemo.com/users/" + self.vars.user_id).assert_ok()
```

## Execution results

Apiritif writes output data from tests in `apiritif.#.csv` files by default. Here `#` is number of executing process.
The output file is similar to this:
```csv
timeStamp,elapsed,Latency,label,responseCode,responseMessage,success,allThreads,bytes
1602759519185,0,0,Correct test,,,true,0,2
1602759519186,0,0,Correct transaction,,,true,0,2
1602759519187,0,0,Test with exception,,Exception: Horrible error,false,0,2
```  
It contains test and transaction results for executed tests by one process.

### Environment Variables

There are environment variables to control length of response/request body to be written into traces and logs:
  * `APIRITIF_TRACE_BODY_EXCLIMIT` - limit of body part to include into exception messages, default is 1024
  * `APIRITIF_TRACE_BODY_HARDLIMIT` - limit of body length to include into JSON trace records, default is unlimited




%package help
Summary:	Development documents and examples for apiritif
Provides:	python3-apiritif-doc
%description help
# Apiritif

Apiritif is a number of utilities aimed to simplify the process of maintaining API tests. 
Apiritif tests fully based on python nose tests. This library can help you to develop and run your existing tests.
In order to create any valid tests for Apiritif you can read [nose test documentation](https://nose.readthedocs.io/en/latest/testing.html).

Check Apiritif version with the following command:
```
python -m apiritif -- version
```

Here described some features of Apiritif which can help you to create tests more easily.  

## Overview

## HTTP Requests

Apiritif allows to use simple `requests`-like API for making HTTP requests.

```python
from apiritif import http

response = http.get("http://example.com")
response.assert_ok()  # will raise AssertionError if request wasn't successful
```

`http` object provides the following methods:
```python
from apiritif import http

http.get("http://api.example.com/posts")
http.post("http://api.example.com/posts")
http.put("http://api.example.com/posts/1")
http.patch("http://api.example.com/posts/1")
http.delete("http://api.example.com/posts/1")
http.head("http://api.example.com/posts")
```

All methods (`get`, `post`, `put`, `patch`, `delete`, `head`) support the following arguments:
```python
def get(address,               # URL for the request
        params=None,           # URL params dict
        headers=None,          # HTTP headers
        cookies=None,          # request cookies
        data=None,             # raw request data
        json=None,             # attach JSON object as request body
        encrypted_cert=None,   # certificate to use with request 
        allow_redirects=True,  # automatically follow HTTP redirects
        timeout=30)            # request timeout, by default it's 30 seconds
```

##### Certificate usage
Currently `http` supports `pem` and `pkcs12` certificates. 
Here is an example of certificate usage:
```python
http.get("http://api.example.com/posts", encrypted_cert=('./cert.pem', 'passphrase'))
```
First parameter is path to certificate, second is the passphrase certificate encrypted with.

## HTTP Targets

Target is an object that captures resource name of the URL (protocol, domain, port)
and allows to set some settings applied to all requests made for a target.


```python
from apiritif import http

qa_env = http.target("http://192.160.0.2")
qa_env.get("/api/v4/user")
qa_env.get("/api/v4/user")
```

Target constructor supports the following options:
```python
target = apiritif.http.target(
    address,               # target base address
    base_path=None,        # base path prepended to all paths (e.g. '/api/v2')
    use_cookies=True,      # use cookies
    additional_headers=None,  # additional headers for all requests
    keep_alive=True,       # reuse opened HTTP connection
    auto_assert_ok=True,   # automatically invoke 'assert_ok' after each request
)
```


## Assertions

Apiritif responses provide a lot of useful assertions that can be used on responses.

Here's the list of assertions that can be used:
```python
response = http.get("http://example.com/")

# assert that request succeeded (status code is 2xx or 3xx)
response.assert_ok()
# assert that request has failed
response.assert_failed()

# status code based assertions
response.assert_2xx()
response.assert_3xx()
response.assert_4xx()
response.assert_5xx()
response.assert_status_code(code)
response.assert_not_status_code(code)
response.assert_status_code_in(codes)

# content-based assertions

# assert that response body contains a string
response.assert_in_body(member)

# assert that response body doesn't contain a string
response.assert_not_in_body(member)

# search (or match) response body with a regex
response.assert_regex_in_body(regex, match=False)
response.assert_regex_not_in_body(regex, match=False)

# assert that response has header
response.assert_has_header(header)

# assert that response has header with given value
response.assert_header_value(header, value)

# assert that response's headers contains a string
response.assert_in_headers(member)
response.assert_not_in_headers(member)

# search (or match) response body with a regex
response.assert_regex_in_headers(member)
response.assert_regex_not_in_headers(member)

# assert that response body matches JSONPath query
response.assert_jsonpath(jsonpath_query, expected_value=None)
response.assert_not_jsonpath(jsonpath_query)

# assert that response body matches XPath query
response.assert_xpath(xpath_query, parser_type='html', validate=False)
response.assert_not_xpath(xpath_query, parser_type='html', validate=False)

# assert that HTML response body contains CSS selector item
response.assert_cssselect(selector, expected_value=None, attribute=None)
response.assert_not_cssselect(selector, expected_value=None, attribute=None)

```

Note that assertions can be chained, so the following construction is entirely valid:
```python

response = http.get("http://example.com/")
response.assert_ok().assert_in_body("Example")
```

## Transactions

Apiritif allows to group multiple requests or actions into a transaction using a `transaction` context manager.
For example when we have test action like bellow we want to execute requests according to concrete user as a separate piece.
Also we want to process test for `users/all` page even if something wrong with previous actions.

```python
def test_with_login():
    user_credentials = data_mock.get_my_user()
    http.get("https://blazedemo.com/user/login?id="+user_credentials.id).assert_ok()
    http.get("https://blazedemo.com/user/id/personalPage").assert_ok()
    http.get("https://blazedemo.com/user/id/getPersonalData").assert_ok()

    http.get("https://blazedemo.com/users/all").assert_ok()
```

Here where we can use transaction in order to wrap login process in one block.

```python
def test_with_login():
    with apiritif.transaction('Login'):
        user_credentials = data_mock.get_my_user()
        http.get("https://blazedemo.com/user/login?id="+user_credentials.id).assert_ok()
        http.get("https://blazedemo.com/user/id/personalPage").assert_ok()
        http.get("https://blazedemo.com/user/id/getPersonalData").assert_ok()

    http.get("https://blazedemo.com/users/all").assert_ok()
```
At the same time requests to `users/all` page will be executed outside of transaction even if something inside transaction fails.

Transaction defines the name for the block of code. This name with execution results of this particular block will be displayed in the output report.

#### Smart transactions

`smart_transaction` is advanced option for test flow control (stop or continue after failed test method).
Let see another test method example:

```python
class Tests(TestCase):
    def test_available_pages():
        http.get("https://blazedemo.com/").assert_ok()
        http.get("https://blazedemo.com/users").assert_ok()
    
        http.get("https://blazedemo.com/users/search").assert_ok()
        http.get("https://blazedemo.com/users/count").assert_ok()
        http.get("https://blazedemo.com/users/login").assert_ok()

        http.get("https://blazedemo.com/contactUs").assert_ok()
        http.get("https://blazedemo.com/copyright").assert_ok()
```
In this case we have multiple requests divided into blocks. I do not want to test pages under `users` space if it is not available.
For this purpose we can use `smart_transaction`.

```python
class Tests(TestCase):
    def setUp(self):
        apiritif.put_into_thread_store(func_mode=True)
    
    def test_available_pages():
        http.get("https://blazedemo.com/").assert_ok()

        with apiritif.smart_transaction('Availability check'):
            http.get("https://blazedemo.com/users").assert_ok()
    
        with apiritif.smart_transaction('Test users pages'):
            http.get("https://blazedemo.com/users/search").assert_ok()
            http.get("https://blazedemo.com/users/count").assert_ok()
            http.get("https://blazedemo.com/users/login").assert_ok()

        http.get("https://blazedemo.com/contactUs").assert_ok()
        http.get("https://blazedemo.com/copyright").assert_ok()
```
Now this two blocks are wrapped into `smart_transaction` which would help with error test flow handling and logging.

Also each transaction defines the name for the block of code and will be displayed in the output report.
 
Now about `apiritif.put_into_thread_store(func_mode=True)`, this is test execution mode for apiritif.
We can execute all of the transactions in test no matter what or stop after first failed transaction.
This flag tells to apiritif "Stop execution if some transaction failed". `False` says "Run till the end in any case".

##### Nose Flow Control
It's one more feature based on smart transactions. It changes `func_mode` if necessary to execute whole teardown block,
intended to finalize all necessary things.

```python
def test_flow-control(self):
        try:
            self._method_with_exception()
            self._skipped_method()
        finally:
            apiritif.set_stage("teardown")
            self._teardown1()
            self._teardown2()
```
If this test will be interrupted in `_method_with_exception`, both of teardown methods will be executed even if them raise exception.
Please note two differences with usage of `tearDown` method of nose:
1. all parts of teardown stage will be executed as mentioned above (will be interrupted in regular nose execution)
2. results of teardown steps will be written by apiritif SampleWriter into output file (nose lost them as tearDown isn't recognised as test).

##### Graceful shutdown
Somethimes waiting of end of test isn't necessary and we prefer to break it but save all current results and handle all teardown steps. (see above)
It's possible with GRACEFUL flag. To use it you can run apiritif with GRACEFUL environment variable pointed to any file name.
Apiritif will be interrupted as soon as the file is created.

## CSV Reader
In order to use data from csv file as test parameters Apiritif provides two different csv readers.
Simple `CSVReader` helps you to read data from file line by line and use this data wherever you need:

```python
data_reader = apiritif.CSVReader('---path to required file---')
class Tests(TestCase):
    def test_user_page():
        data_reader.read_vars()
        vars = data_reader.get_vars()
        http.get("https://blazedemo.com/users/" + vars.user_id).assert_ok()
```

In case of multithreading testing you may need to deviate data between threads and ysu uniq lines for each thread.
`CSVReaderPerThread` helps to solve this problem: 

```python
data_per_thread_reader = apiritif.CSVReaderPerThread('---path to required file---')
class Tests(TestCase):
    def setUp(self):
        data_per_thread_reader.read_vars()
        self.vars = data_per_thread_reader.get_vars()
    
    def test_user_page():
        http.get("https://blazedemo.com/users/" + self.vars.user_id).assert_ok()
```

## Execution results

Apiritif writes output data from tests in `apiritif.#.csv` files by default. Here `#` is number of executing process.
The output file is similar to this:
```csv
timeStamp,elapsed,Latency,label,responseCode,responseMessage,success,allThreads,bytes
1602759519185,0,0,Correct test,,,true,0,2
1602759519186,0,0,Correct transaction,,,true,0,2
1602759519187,0,0,Test with exception,,Exception: Horrible error,false,0,2
```  
It contains test and transaction results for executed tests by one process.

### Environment Variables

There are environment variables to control length of response/request body to be written into traces and logs:
  * `APIRITIF_TRACE_BODY_EXCLIMIT` - limit of body part to include into exception messages, default is 1024
  * `APIRITIF_TRACE_BODY_HARDLIMIT` - limit of body length to include into JSON trace records, default is unlimited




%prep
%autosetup -n apiritif-1.1.3

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-apiritif -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Tue Apr 25 2023 Python_Bot <Python_Bot@openeuler.org> - 1.1.3-1
- Package Spec generated