Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
283 lines (232 loc) · 7.75 KB
/
Copy pathutils.py
File metadata and controls
283 lines (232 loc) · 7.75 KB
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
# Patchwork - automated patch tracking system
# Copyright (C) 2018 Stephen Finucane <stephen@that.guru>
#
# SPDX-License-Identifier: GPL-2.0-or-later
import functools
import json
import os
from django.test import testcases
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient as BaseAPIClient
from rest_framework.test import APIRequestFactory
from patchwork.tests.unit.api import validator
from patchwork.tests.utils import create_user
# docs/api/samples
OUT_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.pardir,
os.pardir,
os.pardir,
os.pardir,
'docs',
'api',
'samples',
)
_WRITTEN_FILES = {}
def _duplicate_sample(filename, func):
global _WRITTEN_FILES
# sanity check to make sure we're not writing to the same file
# twice
if filename in _WRITTEN_FILES:
# though if tests do this, we simply ignore subsequent
# writes
if _WRITTEN_FILES[filename] == func:
return True
raise Exception(
"Tests '{}' and '{}' write to the same file".format(
_WRITTEN_FILES[filename], func
)
)
_WRITTEN_FILES[filename] = func
return False
def store_samples(filename):
"""Wrapper to store responses and requests generated in tests.
These can be used in documentation. Only the first response or request body
is saved per test.
"""
if not os.path.exists(OUT_DIR):
os.mkdir(OUT_DIR)
def inner(func):
def wrapper(self, *args, **kwargs):
def client_wrapper(
orig_func, path, data=None, *orig_args, **orig_kwargs
):
req_filename = filename + '-req.json'
resp_filename = filename + '-resp.json'
# we don't have a request body for GET requests
if orig_func != _get and not _duplicate_sample(
req_filename, func
):
with open(os.path.join(OUT_DIR, req_filename), 'w') as fh:
json.dump(data, fh, indent=4, separators=(',', ': '))
resp = orig_func(path, data, *orig_args, **orig_kwargs)
if not _duplicate_sample(resp_filename, func):
with open(os.path.join(OUT_DIR, resp_filename), 'w') as fh:
json.dump(
resp.data, fh, indent=4, separators=(',', ': ')
)
return resp
# replace client.* with our own implementations
_get = self.client.get
self.client.get = functools.partial(client_wrapper, _get)
_post = self.client.post
self.client.post = functools.partial(client_wrapper, _post)
_put = self.client.put
self.client.put = functools.partial(client_wrapper, _put)
_patch = self.client.patch
self.client.patch = functools.partial(client_wrapper, _patch)
func(self, *args, **kwargs)
# ...then reverse
self.client.patch = _patch
self.client.put = _put
self.client.post = _post
self.client.get = _get
return wrapper
return inner
class APIClient(BaseAPIClient):
def __init__(self, *args, **kwargs):
super(APIClient, self).__init__(*args, **kwargs)
self.factory = APIRequestFactory()
self.token = None
def authenticate(self, user):
if user is None: # if none, we want an "anonymous" user
user = create_user()
self.token, _ = Token.objects.get_or_create(user=user)
self.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
def get(self, path, data=None, follow=False, **extra):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
# NOTE(stephenfin): For some reason, the authentication information
# does not appear in the headers. We need to manually set it (but this
# isn't good enough to *actually* authenticate
headers = {}
if self.token:
headers['AUTHORIZATION'] = f'Token {self.token.key}'
request = self.factory.get(
path,
data=data,
headers=headers,
SERVER_NAME='example.com',
**extra,
)
response = super(APIClient, self).get(
path,
data=data,
follow=follow,
SERVER_NAME='example.com',
**extra,
)
validator.validate_data(
path, request, response, validate_request, validate_response
)
return response
def post(
self,
path,
data=None,
format=None,
content_type=None,
follow=False,
**extra,
):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
headers = {}
if self.token:
headers['AUTHORIZATION'] = f'Token {self.token.key}'
request = self.factory.post(
path,
data=data,
format='json',
content_type=content_type,
headers=headers,
SERVER_NAME='example.com',
**extra,
)
response = super(APIClient, self).post(
path,
data=data,
format='json',
content_type=content_type,
follow=follow,
SERVER_NAME='example.com',
**extra,
)
validator.validate_data(
path, request, response, validate_request, validate_response
)
return response
def put(
self,
path,
data=None,
format=None,
content_type=None,
follow=False,
**extra,
):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
headers = {}
if self.token:
headers['AUTHORIZATION'] = f'Token {self.token.key}'
request = self.factory.put(
path,
data=data,
format='json',
content_type=content_type,
headers=headers,
SERVER_NAME='example.com',
**extra,
)
response = super(APIClient, self).put(
path,
data=data,
format='json',
content_type=content_type,
follow=follow,
SERVER_NAME='example.com',
**extra,
)
validator.validate_data(
path, request, response, validate_request, validate_response
)
return response
def patch(
self,
path,
data=None,
format=None,
content_type=None,
follow=False,
**extra,
):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
headers = {}
if self.token:
headers['AUTHORIZATION'] = f'Token {self.token.key}'
request = self.factory.patch(
path,
data=data,
format='json',
content_type=content_type,
headers=headers,
SERVER_NAME='example.com',
**extra,
)
response = super(APIClient, self).patch(
path,
data=data,
format='json',
content_type=content_type,
follow=follow,
SERVER_NAME='example.com',
**extra,
)
validator.validate_data(
path, request, response, validate_request, validate_response
)
return response
class APITestCase(testcases.TestCase):
client_class = APIClient