1
|
|
|
from base64 import b64encode |
|
|
|
|
2
|
|
|
from werkzeug.exceptions import HTTPException |
3
|
|
|
import json |
|
|
|
|
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class TestClient(): |
|
|
|
|
7
|
|
|
def __init__(self, app, username, password): |
8
|
|
|
self.app = app |
9
|
|
|
if username is None: |
10
|
|
|
self.auth = None |
11
|
|
|
else: |
12
|
|
|
self.auth = 'Basic ' + b64encode( |
13
|
|
|
(username + ':' + password).encode('utf-8')).decode('utf-8') |
14
|
|
|
|
15
|
|
|
def send(self, url, method='GET', data=None, headers=None): |
|
|
|
|
16
|
|
|
if headers is None: |
17
|
|
|
headers = {} |
18
|
|
|
headers = headers.copy() |
19
|
|
|
if self.auth is not None: |
20
|
|
|
headers['Authorization'] = self.auth |
21
|
|
|
headers['Content-Type'] = 'application/json' |
22
|
|
|
headers['Accept'] = 'application/json' |
23
|
|
|
if data: |
24
|
|
|
data = json.dumps(data) |
25
|
|
|
|
26
|
|
|
with self.app.test_request_context( |
27
|
|
|
url, method=method, data=data, headers=headers): |
28
|
|
|
try: |
29
|
|
|
rv = self.app.preprocess_request() |
|
|
|
|
30
|
|
|
if rv is None: |
31
|
|
|
rv = self.app.dispatch_request() |
|
|
|
|
32
|
|
|
rv = self.app.make_response(rv) |
|
|
|
|
33
|
|
|
rv = self.app.process_response(rv) |
|
|
|
|
34
|
|
|
except HTTPException as e: |
|
|
|
|
35
|
|
|
rv = self.app.handle_user_exception(e) |
|
|
|
|
36
|
|
|
|
37
|
|
|
try: |
38
|
|
|
json_data = json.loads(rv.data.decode('utf-8')) |
39
|
|
|
except AttributeError: |
40
|
|
|
json_data = None |
41
|
|
|
except json.decoder.JSONDecodeError: |
42
|
|
|
json_data = None |
43
|
|
|
return rv, json_data |
44
|
|
|
|
45
|
|
|
def get(self, url, headers=None): |
|
|
|
|
46
|
|
|
if headers is None: |
47
|
|
|
headers = {} |
48
|
|
|
return self.send(url, 'GET', headers=headers) |
49
|
|
|
|
50
|
|
|
def post(self, url, data, headers=None): |
|
|
|
|
51
|
|
|
if headers is None: |
52
|
|
|
headers = {} |
53
|
|
|
return self.send(url, 'POST', data, headers=headers) |
54
|
|
|
|
55
|
|
|
def put(self, url, data, headers=None): |
|
|
|
|
56
|
|
|
if headers is None: |
57
|
|
|
headers = {} |
58
|
|
|
return self.send(url, 'PUT', data, headers=headers) |
59
|
|
|
|
60
|
|
|
def delete(self, url, headers=None): |
|
|
|
|
61
|
|
|
if headers is None: |
62
|
|
|
headers = {} |
63
|
|
|
return self.send(url, 'DELETE', headers=headers) |
64
|
|
|
|
65
|
|
|
def head(self, url, headers=None): |
|
|
|
|
66
|
|
|
if headers is None: |
67
|
|
|
headers = {} |
68
|
|
|
return self.send(url, 'HEAD', headers=headers) |
69
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.