/
test_crud.py
321 lines (258 loc) · 9.67 KB
/
test_crud.py
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
from flask import url_for
from kqueen.conftest import AuthHeader, TestUserWithNamespace, TestUser, etcd_setup
from kqueen.config import current_config
import faker
import json
import pytest
config = current_config()
@pytest.mark.usefixtures('client_class', 'etcd_setup')
class BaseTestCRUD:
def get_object(self):
raise NotImplementedError
def get_edit_data(self):
raise NotImplementedError
def get_resource_type(self):
return self.obj.__class__.__name__.lower()
def get_create_data(self):
data = self.obj.get_dict(expand=True)
data['id'] = None
return data
def get_urls(self, pk=None):
if not pk:
pk = self.obj.id
return {
'list': url_for(
'api.{}_list'.format(self.get_resource_type())
),
'create': url_for(
'api.{}_create'.format(self.get_resource_type())
),
'get': url_for(
'api.{}_get'.format(self.get_resource_type()),
pk=pk
),
'update': url_for(
'api.{}_update'.format(self.get_resource_type()),
pk=pk
),
'delete': url_for(
'api.{}_delete'.format(self.get_resource_type()),
pk=pk
),
}
def setup(self):
etcd_setup()
self.test_object = self.get_object()
self.obj = self.test_object.obj
self.obj.save()
self.test_user = TestUser()
self.test_auth_header = AuthHeader(self.test_user)
self.auth_header = self.test_auth_header.get(self.client)
self.namespace = self.auth_header['X-Test-Namespace']
# self.user = self.test_user.obj
# self.test_provisioner = TestProvisioner(self.test_user)
# self.provisioner = self.test_provisioner.obj
self.urls = self.get_urls()
def teardown(self):
self.test_auth_header.destroy()
print('!!!!!!!!!!!deleting ' + self.test_object.obj.id)
self.test_object.destroy()
# self.test_provisioner.destroy()
def test_crud_create(self):
data = self.get_create_data()
response = self.client.post(
self.urls['create'],
data=json.dumps(data),
headers=self.auth_header,
content_type='application/json',
)
assert response.status_code == 200
assert response.json['id'] != self.obj.id
def test_crud_create_not_json(self):
response = self.client.post(
self.urls['create'],
headers=self.auth_header,
content_type='text/plain',
)
assert response.status_code == 400
def test_crud_create_failed_save(self, monkeypatch):
def fake_save(self, *args, **kwargs):
raise Exception('Test')
monkeypatch.setattr(self.obj.__class__, 'save', fake_save)
data = self.get_create_data()
response = self.client.post(
self.urls['create'],
data=json.dumps(data),
headers=self.auth_header,
content_type='application/json',
)
assert response.status_code == 500
def test_crud_get(self):
response = self.client.get(
self.urls['get'],
headers=self.auth_header,
)
# object might have been updated during GET
obj = self.obj.__class__.load(
self.namespace,
self.obj.id
)
assert response.status_code == 200
assert response.json == obj.get_dict(expand=True)
def test_crud_list(self):
response = self.client.get(
self.urls['list'],
headers=self.auth_header
)
data = response.json
# object might have been updated during LIST
obj = self.obj.__class__.load(
self.namespace,
self.obj.id
)
assert isinstance(data, list)
assert len(data) == len(self.obj.__class__.list(
self.namespace,
return_objects=False)
)
assert obj.get_dict(expand=True) in data
def test_crud_update(self):
data = self.get_edit_data()
response = self.client.patch(
self.urls['update'],
data=json.dumps(data),
headers=self.auth_header,
content_type='application/json',
)
assert response.status_code == 200
patched = self.obj.__class__.load(
self.namespace,
self.obj.id,
)
for key, value in data.items():
assert getattr(patched, key) == value
@pytest.mark.parametrize('data,content_type,code', [
('hello', 'text/plain', 400),
('[1, 2, 3]', 'application/json', 400),
])
def test_crud_update_return_error(self, data, content_type, code):
response = self.client.patch(
self.urls['update'],
data=data,
headers=self.auth_header,
content_type=content_type,
)
assert response.status_code == code
def test_crud_update_failed_save(self, monkeypatch):
def fake_save(self, *args, **kwargs):
raise Exception('Testing')
monkeypatch.setattr(self.obj.__class__, 'save', fake_save)
data = self.get_edit_data()
response = self.client.patch(
self.urls['update'],
data=json.dumps(data),
headers=self.auth_header,
content_type='application/json',
)
assert response.status_code == 500
def test_crud_delete(self):
response = self.client.delete(
self.urls['delete'],
headers=self.auth_header
)
assert response.status_code == 200
with pytest.raises(NameError, message='Object not found'):
self.obj.__class__.load(
self.namespace,
self.obj.id,
)
def test_crud_delete_failed(self, monkeypatch):
original_delete = getattr(self.obj.__class__, 'delete')
def fake_delete(self, *args, **kwargs):
raise Exception('Testing')
monkeypatch.setattr(self.obj.__class__, 'delete', fake_delete)
response = self.client.delete(self.urls['delete'], headers=self.auth_header)
assert response.status_code == 500
monkeypatch.setattr(self.obj.__class__, 'delete', original_delete)
#
# namespacing tests
#
def test_namespacing(self):
user1 = TestUserWithNamespace()
user1.auth_header = AuthHeader(user1).get(self.client)
user2 = TestUserWithNamespace()
user2.auth_header = AuthHeader(user2).get(self.client)
# skip if object class isn't namespaced
if not self.obj.__class__.is_namespaced():
pytest.skip('Class {} isn\'t namespaced'.format(self.obj.__class__.__name__))
objs = {}
# create objects for both users
for u in [user1, user2]:
data = self.get_create_data()
# TODO: fix this
# Dirty hack to make testing data namespaced.
organization_data = {
'name': 'Test organization',
'namespace': 'testorg',
}
response = self.client.post(
url_for('api.organization_create'),
data=json.dumps(organization_data),
headers=u.auth_header,
content_type='application/json',
)
organization_ref = 'Organization:{}'.format(response.json['id'])
profile = faker.Faker().simple_profile()
owner_data = {
'username': profile['username'],
'email': profile['mail'],
'password': 'pytest',
'organization': organization_ref,
'role': 'admin',
'active': True
}
response = self.client.post(
url_for('api.user_create'),
data=json.dumps(owner_data),
headers=u.auth_header,
content_type='application/json',
)
if 'owner' in data:
data['owner'] = 'User:{}'.format(response.json['id'])
if 'provisioner' in data:
provisioner_data = {
'name': 'Test provisioner',
'engine': 'kqueen.engines.ManualEngine',
'owner': 'User:{}'.format(response.json['id'])
}
response = self.client.post(
url_for('api.provisioner_create'),
data=json.dumps(provisioner_data),
headers=u.auth_header,
content_type='application/json',
)
data['provisioner'] = 'Provisioner:{}'.format(response.json['id'])
response = self.client.post(
self.urls['create'],
data=json.dumps(data),
headers=u.auth_header,
content_type='application/json',
)
print(response.data.decode(response.charset))
objs[u.obj.namespace] = response.json['id']
print(response.json)
# test use can't read other's object
for u in [user1, user2]:
for ns, pk in objs.items():
url = self.get_urls(pk)['get']
if ns == u.obj.namespace:
req_code = 200
else:
req_code = 404
response = self.client.get(
url,
headers=u.auth_header,
content_type='application/json',
)
print(response.data.decode(response.charset))
assert response.status_code == req_code