-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathtest_postgres.py
556 lines (430 loc) · 16.7 KB
/
test_postgres.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
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
import logging
import uuid
from contextlib import asynccontextmanager
from copy import deepcopy
from typing import Callable, Literal
import pytest
from fastapi import Request
from stac_pydantic import Collection, Item
from stac_fastapi.pgstac.db import close_db_connection, connect_to_db, get_connection
# from tests.conftest import MockStarletteRequest
logger = logging.getLogger(__name__)
async def test_create_collection(app_client, load_test_data: Callable):
in_json = load_test_data("test_collection.json")
in_coll = Collection.model_validate(in_json)
resp = await app_client.post(
"/collections",
json=in_json,
)
assert resp.status_code == 201
post_coll = Collection.model_validate(resp.json())
assert in_coll.model_dump(exclude={"links"}) == post_coll.model_dump(
exclude={"links"}
)
resp = await app_client.get(f"/collections/{post_coll.id}")
assert resp.status_code == 200
get_coll = Collection.model_validate(resp.json())
assert post_coll.model_dump(exclude={"links"}) == get_coll.model_dump(
exclude={"links"}
)
async def test_update_collection(app_client, load_test_collection, load_test_data):
in_coll = load_test_collection
in_coll["keywords"].append("newkeyword")
resp = await app_client.put(f"/collections/{in_coll['id']}", json=in_coll)
assert resp.status_code == 200
resp = await app_client.get(f"/collections/{in_coll['id']}")
assert resp.status_code == 200
get_coll = Collection.model_validate(resp.json())
in_coll = Collection(**in_coll)
assert in_coll.model_dump(exclude={"links"}) == get_coll.model_dump(exclude={"links"})
assert "newkeyword" in get_coll.keywords
async def test_delete_collection(app_client, load_test_collection):
in_coll = load_test_collection
resp = await app_client.delete(f"/collections/{in_coll['id']}")
assert resp.status_code == 200
resp = await app_client.get(f"/collections/{in_coll['id']}")
assert resp.status_code == 404
async def test_create_item(app_client, load_test_data: Callable, load_test_collection):
coll = load_test_collection
in_json = load_test_data("test_item.json")
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=in_json,
)
assert resp.status_code == 201
in_item = Item.model_validate(in_json)
post_item = Item.model_validate(resp.json())
assert in_item.model_dump(exclude={"links"}) == post_item.model_dump(
exclude={"links"}
)
resp = await app_client.get(f"/collections/{coll['id']}/items/{post_item.id}")
assert resp.status_code == 200
get_item = Item.model_validate(resp.json())
assert in_item.model_dump(exclude={"links"}) == get_item.model_dump(exclude={"links"})
async def test_create_item_no_collection_id(
app_client, load_test_data: Callable, load_test_collection
):
"""Items with no collection id should be set with the collection id from the path"""
coll = load_test_collection
item = load_test_data("test_item.json")
item["collection"] = None
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item,
)
assert resp.status_code == 201
resp = await app_client.get(f"/collections/{coll['id']}/items/{item['id']}")
assert resp.status_code == 200
get_item = Item.model_validate(resp.json())
assert get_item.collection == coll["id"]
async def test_create_item_invalid_ids(
app_client, load_test_data: Callable, load_test_collection
):
"""Items with invalid ids should return an error"""
coll = load_test_collection
item = load_test_data("test_item.json")
item["id"] = "invalid/id"
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item,
)
assert resp.status_code == 400
async def test_create_item_invalid_collection_id(
app_client, load_test_data: Callable, load_test_collection
):
"""Items with invalid collection ids should return an error"""
coll = load_test_collection
item = load_test_data("test_item.json")
item["collection"] = "wrong-collection-id"
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item,
)
assert resp.status_code == 400
async def test_create_item_bad_body(
app_client, load_test_data: Callable, load_test_collection
):
"""Items with invalid type should return an error"""
coll = load_test_collection
item = load_test_data("test_item.json")
item["type"] = "not-a-type"
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item,
)
assert resp.status_code == 400
async def test_update_item(app_client, load_test_collection, load_test_item):
coll = load_test_collection
item = load_test_item
item["properties"]["description"] = "Update Test"
resp = await app_client.put(
f"/collections/{coll['id']}/items/{item['id']}", json=item
)
assert resp.status_code == 200
resp = await app_client.get(f"/collections/{coll['id']}/items/{item['id']}")
assert resp.status_code == 200
get_item = Item.model_validate(resp.json())
item = Item(**item)
assert item.model_dump(exclude={"links"}) == get_item.model_dump(exclude={"links"})
assert get_item.properties.description == "Update Test"
async def test_delete_item(app_client, load_test_collection, load_test_item):
coll = load_test_collection
item = load_test_item
resp = await app_client.delete(f"/collections/{coll['id']}/items/{item['id']}")
assert resp.status_code == 200
resp = await app_client.get(f"/collections/{coll['id']}/items/{item['id']}")
assert resp.status_code == 404
async def test_get_collection_items(app_client, load_test_collection, load_test_item):
coll = load_test_collection
item = load_test_item
for _ in range(4):
item["id"] = str(uuid.uuid4())
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item,
)
assert resp.status_code == 201
resp = await app_client.get(
f"/collections/{coll['id']}/items",
)
assert resp.status_code == 200
fc = resp.json()
assert "features" in fc
assert len(fc["features"]) == 5
async def test_create_item_collection(
app_client, load_test_data: Callable, load_test_collection
):
"""POSTing a FeatureCollection to the items endpoint should create the items"""
coll = load_test_collection
base_item = load_test_data("test_item.json")
items = []
for _ in range(5):
item = deepcopy(base_item)
item["id"] = str(uuid.uuid4())
items.append(item)
item_collection = {"type": "FeatureCollection", "features": items, "links": []}
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item_collection,
)
assert resp.status_code == 201
resp = await app_client.get(
f"/collections/{coll['id']}/items",
)
for item in items:
resp = await app_client.get(f"/collections/{coll['id']}/items/{item['id']}")
assert resp.status_code == 200
async def test_create_item_collection_no_collection_ids(
app_client, load_test_data: Callable, load_test_collection
):
"""Items in ItemCollection with no collection ids should be set with the collection id from the path"""
coll = load_test_collection
base_item = load_test_data("test_item.json")
items = []
for _ in range(5):
item = deepcopy(base_item)
item["id"] = str(uuid.uuid4())
item["collection"] = None
items.append(item)
item_collection = {"type": "FeatureCollection", "features": items, "links": []}
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item_collection,
)
assert resp.status_code == 201
resp = await app_client.get(
f"/collections/{coll['id']}/items",
)
for item in items:
resp = await app_client.get(f"/collections/{coll['id']}/items/{item['id']}")
assert resp.status_code == 200
assert resp.json()["collection"] == coll["id"]
async def test_create_item_collection_invalid_collection_ids(
app_client, load_test_data: Callable, load_test_collection
):
"""Feature collection containing items with invalid collection ids should return an error"""
coll = load_test_collection
base_item = load_test_data("test_item.json")
items = []
for _ in range(5):
item = deepcopy(base_item)
item["id"] = str(uuid.uuid4())
item["collection"] = "wrong-collection-id"
items.append(item)
item_collection = {"type": "FeatureCollection", "features": items, "links": []}
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item_collection,
)
assert resp.status_code == 400
async def test_create_item_collection_invalid_item_ids(
app_client, load_test_data: Callable, load_test_collection
):
"""Feature collection containing items with invalid ids should return an error"""
coll = load_test_collection
base_item = load_test_data("test_item.json")
items = []
for _ in range(5):
item = deepcopy(base_item)
item["id"] = str(uuid.uuid4()) + "/bad/id"
items.append(item)
item_collection = {"type": "FeatureCollection", "features": items, "links": []}
resp = await app_client.post(
f"/collections/{coll['id']}/items",
json=item_collection,
)
assert resp.status_code == 400
async def test_create_bulk_items(
app_client, load_test_data: Callable, load_test_collection
):
coll = load_test_collection
item = load_test_data("test_item.json")
items = {}
for _ in range(2):
_item = deepcopy(item)
_item["id"] = str(uuid.uuid4())
items[_item["id"]] = _item
payload = {"items": items}
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 200
assert resp.text == '"Successfully added 2 items."'
for item_id in items.keys():
resp = await app_client.get(f"/collections/{coll['id']}/items/{item_id}")
assert resp.status_code == 200
async def test_create_bulk_items_already_exist_insert(
app_client, load_test_data: Callable, load_test_collection
):
coll = load_test_collection
item = load_test_data("test_item.json")
items = {}
for _ in range(2):
_item = deepcopy(item)
_item["id"] = str(uuid.uuid4())
items[_item["id"]] = _item
payload = {"items": items, "method": "insert"}
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 200
assert resp.text == '"Successfully added 2 items."'
for item_id in items.keys():
resp = await app_client.get(f"/collections/{coll['id']}/items/{item_id}")
assert resp.status_code == 200
# Try creating the same items again.
# This should fail with the default insert behavior.
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 409
async def test_create_bulk_items_already_exist_upsert(
app_client, load_test_data: Callable, load_test_collection
):
coll = load_test_collection
item = load_test_data("test_item.json")
items = {}
for _ in range(2):
_item = deepcopy(item)
_item["id"] = str(uuid.uuid4())
items[_item["id"]] = _item
payload = {"items": items, "method": "insert"}
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 200
assert resp.text == '"Successfully added 2 items."'
for item_id in items.keys():
resp = await app_client.get(f"/collections/{coll['id']}/items/{item_id}")
assert resp.status_code == 200
# Try creating the same items again, but using upsert.
# This should succeed.
payload["method"] = "upsert"
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 200
assert resp.text == '"Successfully upserted 2 items."'
async def test_create_bulk_items_omit_collection(
app_client, load_test_data: Callable, load_test_collection
):
coll = load_test_collection
item = load_test_data("test_item.json")
items = {}
for _ in range(2):
_item = deepcopy(item)
_item["id"] = str(uuid.uuid4())
# remove collection ID here
del _item["collection"]
items[_item["id"]] = _item
payload = {"items": items, "method": "insert"}
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 200
assert resp.text == '"Successfully added 2 items."'
for item_id in items.keys():
resp = await app_client.get(f"/collections/{coll['id']}/items/{item_id}")
assert resp.status_code == 200
# Try creating the same items again, but using upsert.
# This should succeed.
payload["method"] = "upsert"
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 200
assert resp.text == '"Successfully upserted 2 items."'
async def test_create_bulk_items_collection_mismatch(
app_client, load_test_data: Callable, load_test_collection
):
coll = load_test_collection
item = load_test_data("test_item.json")
items = {}
for _ in range(2):
_item = deepcopy(item)
_item["id"] = str(uuid.uuid4())
_item["collection"] = "wrong-collection"
items[_item["id"]] = _item
payload = {"items": items, "method": "insert"}
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 400
assert (
resp.json()["detail"]
== "Collection ID from path parameter (test-collection) does not match Collection ID from Item (wrong-collection)"
)
async def test_create_bulk_items_id_mismatch(
app_client, load_test_data: Callable, load_test_collection
):
coll = load_test_collection
item = load_test_data("test_item.json")
items = {}
for _ in range(2):
_item = deepcopy(item)
_item["id"] = str(uuid.uuid4())
_item["collection"] = "wrong-collection"
items[_item["id"] + "wrong"] = _item
payload = {"items": items, "method": "insert"}
resp = await app_client.post(
f"/collections/{coll['id']}/bulk_items",
json=payload,
)
assert resp.status_code == 400
assert (
resp.json()["detail"]
== "Collection ID from path parameter (test-collection) does not match Collection ID from Item (wrong-collection)"
)
# TODO since right now puts implement upsert
# test_create_collection_already_exists
# test create_item_already_exists
# def test_get_collection_items(
# postgres_core: CoreCrudClient,
# postgres_transactions: TransactionsClient,
# load_test_data: Callable,
# ):
# coll = Collection.model_validate(load_test_data("test_collection.json"))
# postgres_transactions.create_collection(coll, request=MockStarletteRequest)
# item = Item.model_validate(load_test_data("test_item.json"))
# for _ in range(5):
# item.id = str(uuid.uuid4())
# postgres_transactions.create_item(item, request=MockStarletteRequest)
# fc = postgres_core.item_collection(coll.id, request=MockStarletteRequest)
# assert len(fc.features) == 5
# for item in fc.features:
# assert item.collection == coll.id
@asynccontextmanager
async def custom_get_connection(
request: Request,
readwrite: Literal["r", "w"],
):
"""An example of customizing the connection getter"""
async with get_connection(request, readwrite) as conn:
await conn.execute("SELECT set_config('api.test', 'added-config', false)")
yield conn
class TestDbConnect:
@pytest.fixture
async def app(self, api_client):
"""
app fixture override to setup app with a customized db connection getter
"""
logger.debug("Customizing app setup")
await connect_to_db(api_client.app, custom_get_connection)
yield api_client.app
await close_db_connection(api_client.app)
async def test_db_setup(self, api_client, app_client):
@api_client.app.get(f"{api_client.router.prefix}/db-test")
async def example_view(request: Request):
async with request.app.state.get_connection(request, "r") as conn:
return await conn.fetchval("SELECT current_setting('api.test', true)")
response = await app_client.get("/db-test")
assert response.status_code == 200
assert response.json() == "added-config"