This repository was archived by the owner on Apr 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_opportunity_async.py
More file actions
355 lines (298 loc) · 12.5 KB
/
test_opportunity_async.py
File metadata and controls
355 lines (298 loc) · 12.5 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
from datetime import UTC, datetime, timedelta, timezone
from typing import Any, Callable
from uuid import uuid4
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from stapi_fastapi.models.opportunity import (
OpportunityCollection,
OpportunitySearchRecord,
OpportunitySearchStatus,
OpportunitySearchStatusCode,
)
from stapi_fastapi.models.shared import Link
from .shared import (
create_mock_opportunity,
find_link,
pagination_tester,
product_test_spotlight,
product_test_spotlight_async_opportunity,
product_test_spotlight_sync_async_opportunity,
product_test_spotlight_sync_opportunity,
)
from .test_datetime_interval import rfc3339_strftime
@pytest.mark.mock_products([product_test_spotlight])
def test_no_opportunity_search_advertised(stapi_client: TestClient) -> None:
product_id = "test-spotlight"
# the `/products/{productId}/opportunities link should not be advertised on the product
product_response = stapi_client.get(f"/products/{product_id}")
product_body = product_response.json()
assert find_link(product_body["links"], "opportunities") is None
# the `searches/opportunities` link should not be advertised on the root
root_response = stapi_client.get("/")
root_body = root_response.json()
assert find_link(root_body["links"], "opportunity-search-records") is None
@pytest.mark.mock_products([product_test_spotlight_sync_opportunity])
def test_only_sync_search_advertised(stapi_client: TestClient) -> None:
product_id = "test-spotlight"
# the `/products/{productId}/opportunities link should be advertised on the product
product_response = stapi_client.get(f"/products/{product_id}")
product_body = product_response.json()
assert find_link(product_body["links"], "opportunities")
# the `searches/opportunities` link should not be advertised on the root
root_response = stapi_client.get("/")
root_body = root_response.json()
assert find_link(root_body["links"], "opportunity-search-records") is None
# test async search offered
@pytest.mark.parametrize(
"mock_products",
[
[product_test_spotlight_async_opportunity],
[product_test_spotlight_sync_async_opportunity],
],
)
def test_async_search_advertised(stapi_client_async_opportunity: TestClient) -> None:
product_id = "test-spotlight"
# the `/products/{productId}/opportunities link should be advertised on the product
product_response = stapi_client_async_opportunity.get(f"/products/{product_id}")
product_body = product_response.json()
assert find_link(product_body["links"], "opportunities")
# the `searches/opportunities` link should be advertised on the root
root_response = stapi_client_async_opportunity.get("/")
root_body = root_response.json()
assert find_link(root_body["links"], "opportunity-search-records")
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_async_search_response(
stapi_client_async_opportunity: TestClient,
opportunity_search: dict[str, Any],
) -> None:
product_id = "test-spotlight"
url = f"/products/{product_id}/opportunities"
response = stapi_client_async_opportunity.post(url, json=opportunity_search)
assert response.status_code == 201
body = response.json()
try:
_ = OpportunitySearchRecord(**body)
except Exception as _:
pytest.fail("response is not an opportunity search record")
assert find_link(body["links"], "self")
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_async_search_is_default(
stapi_client_async_opportunity: TestClient,
opportunity_search: dict[str, Any],
) -> None:
product_id = "test-spotlight"
url = f"/products/{product_id}/opportunities"
response = stapi_client_async_opportunity.post(url, json=opportunity_search)
assert response.status_code == 201
body = response.json()
try:
_ = OpportunitySearchRecord(**body)
except Exception as _:
pytest.fail("response is not an opportunity search record")
@pytest.mark.mock_products([product_test_spotlight_sync_async_opportunity])
def test_prefer_header(
stapi_client_async_opportunity: TestClient,
opportunity_search: dict[str, Any],
) -> None:
product_id = "test-spotlight"
url = f"/products/{product_id}/opportunities"
# prefer = "wait"
response = stapi_client_async_opportunity.post(
url, json=opportunity_search, headers={"Prefer": "wait"}
)
assert response.status_code == 200
assert response.headers["Preference-Applied"] == "wait"
body = response.json()
try:
OpportunityCollection(**body)
except Exception as _:
pytest.fail("response is not an opportunity collection")
# prefer = "respond-async"
response = stapi_client_async_opportunity.post(
url, json=opportunity_search, headers={"Prefer": "respond-async"}
)
assert response.status_code == 201
assert response.headers["Preference-Applied"] == "respond-async"
body = response.json()
try:
OpportunitySearchRecord(**body)
except Exception as _:
pytest.fail("response is not an opportunity search record")
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_async_search_record_retrieval(
stapi_client_async_opportunity: TestClient,
opportunity_search: dict[str, Any],
) -> None:
# post an async search
product_id = "test-spotlight"
url = f"/products/{product_id}/opportunities"
search_response = stapi_client_async_opportunity.post(url, json=opportunity_search)
assert search_response.status_code == 201
search_response_body = search_response.json()
# get the search record by id and verify it matches the original response
search_record_id = search_response_body["id"]
record_response = stapi_client_async_opportunity.get(
f"/searches/opportunities/{search_record_id}"
)
assert record_response.status_code == 200
record_response_body = record_response.json()
assert record_response_body == search_response_body
# verify the search record is in the list of all search records
records_response = stapi_client_async_opportunity.get("/searches/opportunities")
assert records_response.status_code == 200
records_response_body = records_response.json()
assert search_record_id in [
x["id"] for x in records_response_body["search_records"]
]
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_async_opportunity_search_to_completion(
stapi_client_async_opportunity: TestClient,
opportunity_search: dict[str, Any],
url_for: Callable[[str], str],
) -> None:
# Post a request for an async search
product_id = "test-spotlight"
url = f"/products/{product_id}/opportunities"
search_response = stapi_client_async_opportunity.post(url, json=opportunity_search)
assert search_response.status_code == 201
search_record = OpportunitySearchRecord(**search_response.json())
# Simulate the search being completed by some external process:
# - an OpportunityCollection is created and stored in the database
collection = OpportunityCollection(
id=str(uuid4()),
features=[create_mock_opportunity()],
)
collection.links.append(
Link(
rel="create-order",
href=url_for(f"/products/{product_id}/orders"),
body=search_record.opportunity_request.model_dump(),
method="POST",
)
)
collection.links.append(
Link(
rel="search-record",
href=url_for(f"/searches/opportunities/{search_record.id}"),
)
)
stapi_client_async_opportunity.app_state[
"_opportunities_db"
].put_opportunity_collection(collection)
# - the OpportunitySearchRecord links and status are updated in the database
search_record.links.append(
Link(
rel="opportunities",
href=url_for(f"/products/{product_id}/opportunities/{collection.id}"),
)
)
search_record.status = OpportunitySearchStatus(
timestamp=datetime.now(timezone.utc),
status_code=OpportunitySearchStatusCode.completed,
)
stapi_client_async_opportunity.app_state["_opportunities_db"].put_search_record(
search_record
)
# Verify we can retrieve the OpportunitySearchRecord by its id and its status is
# `completed`
url = f"/searches/opportunities/{search_record.id}"
retrieved_search_response = stapi_client_async_opportunity.get(url)
assert retrieved_search_response.status_code == 200
retrieved_search_record = OpportunitySearchRecord(
**retrieved_search_response.json()
)
assert (
retrieved_search_record.status.status_code
== OpportunitySearchStatusCode.completed
)
# Verify we can retrieve the OpportunityCollection from the
# OpportunitySearchRecord's `opportunities` link; verify the retrieved
# OpportunityCollection contains an order link and a link pointing back to the
# OpportunitySearchRecord
opportunities_link = next(
x for x in retrieved_search_record.links if x.rel == "opportunities"
)
url = str(opportunities_link.href)
retrieved_collection_response = stapi_client_async_opportunity.get(url)
assert retrieved_collection_response.status_code == 200
retrieved_collection = OpportunityCollection(**retrieved_collection_response.json())
assert any(x for x in retrieved_collection.links if x.rel == "create-order")
assert any(x for x in retrieved_collection.links if x.rel == "search-record")
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_new_search_location_header_matches_self_link(
stapi_client_async_opportunity: TestClient,
opportunity_search: dict[str, Any],
) -> None:
product_id = "test-spotlight"
url = f"/products/{product_id}/opportunities"
search_response = stapi_client_async_opportunity.post(url, json=opportunity_search)
assert search_response.status_code == 201
search_record = search_response.json()
link = find_link(search_record["links"], "self")
assert link
assert search_response.headers["Location"] == str(link["href"])
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_bad_ids(stapi_client_async_opportunity: TestClient) -> None:
search_record_id = "bad_id"
res = stapi_client_async_opportunity.get(
f"/searches/opportunities/{search_record_id}"
)
assert res.status_code == status.HTTP_404_NOT_FOUND
product_id = "test-spotlight"
opportunity_collection_id = "bad_id"
res = stapi_client_async_opportunity.get(
f"/products/{product_id}/opportunities/{opportunity_collection_id}"
)
assert res.status_code == status.HTTP_404_NOT_FOUND
@pytest.fixture
def setup_search_record_pagination(
stapi_client_async_opportunity: TestClient,
) -> list[dict[str, Any]]:
product_id = "test-spotlight"
search_records = []
for _ in range(3):
now = datetime.now(UTC)
end = now + timedelta(days=5)
format = "%Y-%m-%dT%H:%M:%S.%f%z"
start_string = rfc3339_strftime(now, format)
end_string = rfc3339_strftime(end, format)
opportunity_request = {
"geometry": {
"type": "Point",
"coordinates": [0, 0],
},
"datetime": f"{start_string}/{end_string}",
"filter": {
"op": "and",
"args": [
{"op": ">", "args": [{"property": "off_nadir"}, 0]},
{"op": "<", "args": [{"property": "off_nadir"}, 45]},
],
},
}
response = stapi_client_async_opportunity.post(
f"/products/{product_id}/opportunities", json=opportunity_request
)
assert response.status_code == 201
body = response.json()
search_records.append(body)
return search_records
@pytest.mark.parametrize("limit", [0, 1, 2, 4])
@pytest.mark.mock_products([product_test_spotlight_async_opportunity])
def test_get_search_records_pagination(
stapi_client_async_opportunity: TestClient,
setup_search_record_pagination: list[dict[str, Any]],
limit: int,
) -> None:
expected_returns = []
if limit > 0:
expected_returns = setup_search_record_pagination
pagination_tester(
stapi_client=stapi_client_async_opportunity,
url="/searches/opportunities",
method="GET",
limit=limit,
target="search_records",
expected_returns=expected_returns,
)