-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_hooks.py
More file actions
369 lines (307 loc) · 10.8 KB
/
test_hooks.py
File metadata and controls
369 lines (307 loc) · 10.8 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
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
from unittest import TestCase
from fastapi import Request
from piccolo.columns import Integer, Varchar
from piccolo.columns.readable import Readable
from piccolo.table import Table
from starlette.testclient import TestClient
from piccolo_api.crud.endpoints import PiccoloCRUD
from piccolo_api.crud.hooks import Hook, HookType
class Movie(Table):
name = Varchar(length=100, required=True)
rating = Integer()
@classmethod
def get_readable(cls):
return Readable(template="%s", columns=[cls.name])
async def set_movie_rating_10(row: Movie):
row["rating"] = 10
return row
async def set_movie_rating_20(row: Movie):
row["rating"] = 20
return row
async def remove_spaces(row_id: int, values: dict):
values["name"] = values["name"].replace(" ", "")
return values
async def look_up_existing(row_id: int, values: dict):
row = await Movie.objects().get(Movie._meta.primary_key == row_id).run()
values["name"] = row.name
return values
async def add_additional_name_details(
row_id: int, values: dict, request: Request
):
director = request.query_params.get("director_name", "")
values["name"] = values["name"] + f" ({director})"
return values
async def additional_name_details(row: Movie, request: Request):
director = request.query_params.get("director_name", "")
row["name"] = f"{row.name} ({director})"
return row
async def raises_exception(row_id: int, request: Request):
if request.query_params.get("director_name", False):
raise Exception("Test Passed")
async def failing_hook(row_id: int):
raise Exception("hook failed")
# TODO - add test for a non-async hook.
class TestPostHooks(TestCase):
def setUp(self):
Movie.create_table(if_not_exists=True).run_sync()
def tearDown(self):
Movie.alter().drop_table().run_sync()
def test_request_context_passed_to_post_hook(self):
"""
Make sure request context can be passed to post hook
callable
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.pre_save,
callable=additional_name_details,
)
],
)
)
json_req = {
"name": "Star Wars",
"rating": 93,
}
_ = client.post("/", json=json_req, params={"director_name": "George"})
movie = Movie.objects().first().run_sync()
self.assertEqual(movie.name, "Star Wars (George)")
def test_single_pre_post_hook(self):
"""
Make sure single hook executes
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.pre_save,
callable=set_movie_rating_10,
)
],
)
)
json_req = {"name": "Star Wars", "rating": 93}
_ = client.post("/", json=json_req)
movie = Movie.objects().first().run_sync()
self.assertEqual(movie.rating, 10)
def test_multi_pre_post_hooks(self):
"""
Make sure multiple hooks execute in correct order
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.pre_save,
callable=set_movie_rating_10,
),
Hook(
hook_type=HookType.pre_save,
callable=set_movie_rating_20,
),
],
)
)
json_req = {"name": "Star Wars", "rating": 93}
_ = client.post("/", json=json_req)
movie = Movie.objects().first().run_sync()
self.assertEqual(movie.rating, 20)
def test_post_save_hook_failed(self):
"""
Make sure failing post_save hook bubbles up
(this implicitly also tests that post_save hooks execute)
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.post_save,
callable=failing_hook,
)
],
)
)
json_req = {"name": "Star Wars", "rating": 93}
with self.assertRaises(Exception, msg="Test Passed"):
_ = client.post("/", json=json_req)
movie = Movie.objects().first().run_sync()
self.assertEqual(movie.rating, 20)
def test_request_context_passed_to_patch_hook(self):
"""
Make sure request context can be passed to patch hook
callable
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.pre_patch,
callable=add_additional_name_details,
)
],
)
)
movie = Movie(name="Star Wars", rating=93)
movie.save().run_sync()
new_name = "Star Wars: A New Hope"
new_name_modified = new_name + " (George)"
json_req = {
"name": new_name,
}
response = client.patch(
f"/{movie.id}/", json=json_req, params={"director_name": "George"}
)
self.assertEqual(response.status_code, 200)
# Make sure the row is returned:
response_json = response.json()
self.assertEqual(response_json["name"], new_name_modified)
# Make sure the underlying database row was changed:
movies = Movie.select().run_sync()
self.assertEqual(movies[0]["name"], new_name_modified)
def test_pre_patch_hook(self):
"""
Make sure pre_patch hook executes successfully
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(hook_type=HookType.pre_patch, callable=remove_spaces)
],
)
)
movie = Movie(name="Star Wars", rating=93)
movie.save().run_sync()
new_name = "Star Wars: A New Hope"
new_name_modified = new_name.replace(" ", "")
response = client.patch(f"/{movie.id}/", json={"name": new_name})
self.assertEqual(response.status_code, 200)
# Make sure the row is returned:
response_json = response.json()
self.assertEqual(response_json["name"], new_name_modified)
# Make sure the underlying database row was changed:
movies = Movie.select().run_sync()
self.assertEqual(movies[0]["name"], new_name_modified)
def test_pre_patch_hook_db_lookup(self):
"""
Make sure pre_patch hook can perform db lookups
(function will always reset "name" to the original name)
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.pre_patch, callable=look_up_existing
)
],
)
)
original_name = "Star Wars"
movie = Movie(name="Star Wars", rating=93)
movie.save().run_sync()
new_name = "Star Wars: A New Hope"
response = client.patch(f"/{movie.id}/", json={"name": new_name})
self.assertEqual(response.status_code, 200)
response_json = response.json()
self.assertEqual(response_json["name"], original_name)
movies = Movie.select().run_sync()
self.assertEqual(movies[0]["name"], original_name)
def test_post_patch_hook_failed(self):
"""
Make sure failing post_patch hook bubbles up
(this implicitly also tests that post_patch hooks execute)
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.post_patch,
callable=failing_hook,
)
],
)
)
original_name = "Star Wars"
movie = Movie(name="Star Wars", rating=93)
movie.save().run_sync()
new_name = "Star Wars: A New Hope"
with self.assertRaises(Exception, msg="Test Passed"):
_ = client.patch(f"/{movie.id}/", json={"name": new_name})
movies = Movie.select().run_sync()
self.assertEqual(movies[0]["name"], original_name)
def test_request_context_passed_to_delete_hook(self):
"""
Make sure request context can be passed to delete hook
callable
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(
hook_type=HookType.pre_delete,
callable=raises_exception,
)
],
)
)
movie = Movie(name="Star Wars", rating=10)
movie.save().run_sync()
with self.assertRaises(Exception, msg="Test Passed"):
_ = client.delete(
f"/{movie.id}/", params={"director_name": "George"}
)
def test_delete_hook_fails(self):
"""
Make sure failing pre_delete hook bubbles up
(this implicitly also tests that pre_delete hooks execute)
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(hook_type=HookType.pre_delete, callable=failing_hook)
],
)
)
movie = Movie(name="Star Wars", rating=10)
movie.save().run_sync()
with self.assertRaises(Exception, msg="Test Passed"):
_ = client.delete(f"/{movie.id}/")
def test_post_delete_hook_fails(self):
"""
Make sure failing post_delete hook bubbles up
(this implicitly also tests that pre_delete hooks execute)
"""
client = TestClient(
PiccoloCRUD(
table=Movie,
read_only=False,
hooks=[
Hook(hook_type=HookType.post_delete, callable=failing_hook)
],
)
)
movie = Movie(name="Star Wars", rating=10)
movie.save().run_sync()
with self.assertRaises(Exception, msg="Test Passed"):
_ = client.delete(f"/{movie.id}/")