Repository navigation
Expand file tree
/
Copy pathtest_client.py
More file actions
502 lines (411 loc) · 26.3 KB
/
Copy pathtest_client.py
File metadata and controls
502 lines (411 loc) · 26.3 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
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
import asyncio
import json
import httpx
import pytest
from parseapi import AsyncParseAPI, ParseAPI, ParseAPIError
def make_client(handler, **kwargs):
calls = []
def record(request: httpx.Request) -> httpx.Response:
calls.append(request)
return handler(request)
client = ParseAPI("test_key_123", transport=httpx.MockTransport(record), retries=kwargs.pop("retries", 0), **kwargs)
return client, calls
def ok(body=None):
return lambda request: httpx.Response(200, json=body or {})
URL_TABLE = [
(lambda p: p.currency("JPY"), "https://api.parseapi.com/currency/JPY"),
(lambda p: p.currency("USD", deep=True, lang="fr"), "https://api.parseapi.com/currency/USD?deep=true&lang=fr"),
(lambda p: p.currency.rate("USD", "EUR", date="2026-10-30", amount=0), "https://api.parseapi.com/currency/USD/EUR?date=2026-10-30&amount=0"),
(lambda p: p.time("America/New_York", at="2026-11-01T01:30:00", to="UTC", disambiguation="compatible"), "https://api.parseapi.com/time/America%2FNew_York?at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=compatible"),
(lambda p: p.time.at(40.71, -74.01, at="2026-11-01T01:30:00", to="UTC", disambiguation="compatible"), "https://api.parseapi.com/time?lat=40.71&lon=-74.01&at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=compatible"),
(lambda p: p.time("America/New_York", at="2026-11-01T01:30:00", to="UTC", disambiguation="earlier"), "https://api.parseapi.com/time/America%2FNew_York?at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=earlier"),
(lambda p: p.time.at(40.71, -74.01, at="2026-11-01T01:30:00", to="UTC", disambiguation="earlier"), "https://api.parseapi.com/time?lat=40.71&lon=-74.01&at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=earlier"),
(lambda p: p.time("America/New_York", at="2026-11-01T01:30:00", to="UTC", disambiguation="later"), "https://api.parseapi.com/time/America%2FNew_York?at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=later"),
(lambda p: p.time.at(40.71, -74.01, at="2026-11-01T01:30:00", to="UTC", disambiguation="later"), "https://api.parseapi.com/time?lat=40.71&lon=-74.01&at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=later"),
(lambda p: p.time("America/New_York", at="2026-11-01T01:30:00", to="UTC", disambiguation="reject"), "https://api.parseapi.com/time/America%2FNew_York?at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=reject"),
(lambda p: p.time.at(40.71, -74.01, at="2026-11-01T01:30:00", to="UTC", disambiguation="reject"), "https://api.parseapi.com/time?lat=40.71&lon=-74.01&at=2026-11-01T01%3A30%3A00&to=UTC&disambiguation=reject"),
(lambda p: p.time.zones(), "https://api.parseapi.com/time/zones"),
(lambda p: p.time.zones('Europe'), "https://api.parseapi.com/time/zones?q=Europe"),
(lambda p: p.time('UTC', targets=['UTC', 'Asia/Tokyo', 'UTC']), "https://api.parseapi.com/time/UTC?targets=UTC%2CAsia%2FTokyo%2CUTC"),
(lambda p: p.time.at(0, 0, targets=['UTC', 'Asia/Tokyo', 'UTC']), "https://api.parseapi.com/time?lat=0&lon=0&targets=UTC%2CAsia%2FTokyo%2CUTC"),
(lambda p: p.card("001234"), "https://api.parseapi.com/card/001234"),
(lambda p: p.card("00 1234-56"), "https://api.parseapi.com/card/00%201234-56"),
(lambda p: p.time(), "https://api.parseapi.com/time"),
(lambda p: p.time("America/New_York", at="2026-09-05T15:00:00", to="Asia/Tokyo"), "https://api.parseapi.com/time/America%2FNew_York?at=2026-09-05T15%3A00%3A00&to=Asia%2FTokyo"),
(lambda p: p.time.at(0, 0, at="1970-01-01T00:00:00Z", to="UTC"), "https://api.parseapi.com/time?lat=0&lon=0&at=1970-01-01T00%3A00%3A00Z&to=UTC"),
(lambda p: p.dns("example.com"), "https://api.parseapi.com/dns/example.com"),
(lambda p: p.dns("_dmarc.bücher.example.", type="txt"), "https://api.parseapi.com/dns/_dmarc.b%C3%BCcher.example.?type=txt"),
(lambda p: p.industry("31-33"), "https://api.parseapi.com/industry/31-33"),
(lambda p: p.industry("54/11"), "https://api.parseapi.com/industry/54%2F11"),
(lambda p: p.industry.search("coffee & tea", limit=5), "https://api.parseapi.com/industry?q=coffee+%26+tea&limit=5"),
(lambda p: p.industry.search("plumbing"), "https://api.parseapi.com/industry?q=plumbing"),
(lambda p: p.name("Andrea / Smith", country="IT"), "https://api.parseapi.com/name/Andrea%20%2F%20Smith?country=IT"),
(lambda p: p.address("10 rue / Paris", country="FR"),
"https://api.parseapi.com/address/10%20rue%20%2F%20Paris?country=FR"),
(lambda p: p.address.search("10 rue", country="FR", postal="75001"),
"https://api.parseapi.com/address?q=10+rue&country=FR&postal=75001"),
(lambda p: p.company("51 824 753 556"), "https://api.parseapi.com/company/51%20824%20753%20556"),
(lambda p: p.date("03/04/2026", format="dmy", to="2026-04-05"),
"https://api.parseapi.com/date/03%2F04%2F2026?format=dmy&to=2026-04-05"),
(lambda p: p.date.today(to="2026-12-25"), "https://api.parseapi.com/date?to=2026-12-25"),
(lambda p: p.timezone.at(0, -0.5, at="2026-09-05T00:00:00Z"),
"https://api.parseapi.com/timezone?lat=0&lon=-0.5&at=2026-09-05T00%3A00%3A00Z"),
(lambda p: p.timezone("America/New_York", at="2026-09-05T15:00:00", to="Europe/London"),
"https://api.parseapi.com/timezone/America%2FNew_York?at=2026-09-05T15%3A00%3A00&to=Europe%2FLondon"),
(lambda p: p.weather(0, 0, deep=True, date="2026-08-28"),
"https://api.parseapi.com/weather?lat=0&lon=0&deep=true&date=2026-08-28"),
(lambda p: p.ip("8.8.8.8"), "https://api.parseapi.com/ip/8.8.8.8"),
(lambda p: p.ip.self(), "https://api.parseapi.com/ip"),
(lambda p: p.ip("8.8.8.8", deep=True), "https://api.parseapi.com/ip/8.8.8.8?deep=true"),
(lambda p: p.continent("NA"), "https://api.parseapi.com/continent/NA"),
(lambda p: p.continent.countries("NA"), "https://api.parseapi.com/continent/NA/countries"),
(lambda p: p.country("US"), "https://api.parseapi.com/country/US"),
(lambda p: p.country.states("US"), "https://api.parseapi.com/country/US/states"),
(lambda p: p.state("NC", country="US"), "https://api.parseapi.com/state/NC?country=US"),
(lambda p: p.state("colorado"), "https://api.parseapi.com/state/colorado"),
(lambda p: p.state.districts("NC", country="US"), "https://api.parseapi.com/state/NC/counties?country=US"),
(lambda p: p.district("37081"), "https://api.parseapi.com/county/37081"),
(lambda p: p.city("charlotte", state="NC"), "https://api.parseapi.com/city/charlotte?state=NC"),
(lambda p: p.city.id("city_mb8mbqrkz8zb"), "https://api.parseapi.com/city/id/city_mb8mbqrkz8zb"),
(lambda p: p.city.search("char", country="US", limit=10), "https://api.parseapi.com/city?q=char&country=US&limit=10"),
(lambda p: p.city.nearest(35.2271, -80.8431), "https://api.parseapi.com/city?lat=35.2271&lon=-80.8431"),
(
lambda p: p.city.nearby("denver", radius=8, unit="mi", limit=3),
"https://api.parseapi.com/city/denver/nearby?radius=8&unit=mi&limit=3",
),
(lambda p: p.postal("28202", country="US"), "https://api.parseapi.com/postal/28202?country=US"),
(lambda p: p.postal("SW1A 1AA"), "https://api.parseapi.com/postal/SW1A%201AA"),
(
lambda p: p.postal.nearby("28202", country="US", radius=40, unit="km"),
"https://api.parseapi.com/postal/28202/nearby?country=US&radius=40&unit=km",
),
(
lambda p: p.postal.distance("28202", "10001", country="US"),
"https://api.parseapi.com/postal/28202/distance/10001?country=US",
),
(lambda p: p.email("a@b.com"), "https://api.parseapi.com/email/a%40b.com"),
(lambda p: p.phone("+14155552671", deep=True), "https://api.parseapi.com/phone/%2B14155552671?deep=true"),
(lambda p: p.carrier("+14155552671"), "https://api.parseapi.com/carrier/%2B14155552671"),
(lambda p: p.caller("4155552671", country="US"), "https://api.parseapi.com/caller/4155552671?country=US"),
(lambda p: p.hlr("+447712345678"), "https://api.parseapi.com/hlr/%2B447712345678"),
(lambda p: p.domain("example.com"), "https://api.parseapi.com/domain/example.com"),
(lambda p: p.asn("AS13335"), "https://api.parseapi.com/asn/AS13335"),
(lambda p: p.asn("13335"), "https://api.parseapi.com/asn/13335"),
(lambda p: p.mx("example.com"), "https://api.parseapi.com/mx/example.com"),
(lambda p: p.useragent("TestUA/1.0"), "https://api.parseapi.com/useragent"),
(lambda p: p.language("en"), "https://api.parseapi.com/language/en"),
(lambda p: p.name("Smith, John"), "https://api.parseapi.com/name/Smith%2C%20John"),
(lambda p: p.timezone("America/New_York"), "https://api.parseapi.com/timezone/America%2FNew_York"),
(lambda p: p.holiday("US", year=1955), "https://api.parseapi.com/holiday/US?year=1955"),
(lambda p: p.holiday.date("US", "2026-12-25"), "https://api.parseapi.com/holiday/US/2026-12-25"),
(lambda p: p.elevation(35.2, -80.8), "https://api.parseapi.com/elevation?lat=35.2&lon=-80.8"),
(lambda p: p.point(36.0726, -79.792, deep=True), "https://api.parseapi.com/point?lat=36.0726&lon=-79.792&deep=true"),
(
lambda p: p.weather(40.7128, -74.006, deep=True),
"https://api.parseapi.com/weather?lat=40.7128&lon=-74.006&deep=true",
),
(lambda p: p.emoji("rocket"), "https://api.parseapi.com/emoji/rocket"),
(lambda p: p.emoji.search("fire", limit=20), "https://api.parseapi.com/emoji?q=fire&limit=20"),
]
@pytest.mark.parametrize("invoke,expected", URL_TABLE)
def test_url_mapping(invoke, expected):
client, calls = make_client(ok())
invoke(client)
assert str(calls[0].url) == expected
def test_name_preserves_nullable_evidence_and_future_fields():
body = {"name": "王", "valid": True, "deep": {"gender": None, "salutation": None}, "future": True}
client, calls = make_client(ok(body))
assert client.name("王", country="CN", deep=True) == body
assert str(calls[0].url).endswith("?country=CN&deep=true")
def test_headers():
client, calls = make_client(ok())
client.country("US")
assert calls[0].headers["X-API-Key"] == "test_key_123"
assert calls[0].headers["User-Agent"].startswith("parseapi-python/")
def test_useragent_header_override():
client, calls = make_client(ok())
client.useragent("Mozilla/5.0 (Test)")
assert calls[0].headers["User-Agent"] == "Mozilla/5.0 (Test)"
def test_missing_key(monkeypatch):
monkeypatch.delenv("PARSEAPI_KEY", raising=False)
with pytest.raises(ValueError, match="PARSEAPI_KEY"):
ParseAPI()
def test_env_key(monkeypatch):
monkeypatch.setenv("PARSEAPI_KEY", "env_key_456")
calls = []
def record(request):
calls.append(request)
return httpx.Response(200, json={})
client = ParseAPI(transport=httpx.MockTransport(record))
client.country("US")
assert calls[0].headers["X-API-Key"] == "env_key_456"
def test_base_url_override():
calls = []
def record(request):
calls.append(request)
return httpx.Response(200, json={})
client = ParseAPI("k", base_url="http://localhost:3000/", transport=httpx.MockTransport(record))
client.country("US")
assert str(calls[0].url) == "http://localhost:3000/country/US"
def test_error_shape():
body = {
"code": "not_found",
"message": "City not found",
"docs": "https://parseapi.com/docs#not_found",
"request_id": "req_abc",
}
client, _ = make_client(lambda request: httpx.Response(404, json=body))
with pytest.raises(ParseAPIError) as excinfo:
client.city("notarealcityxyz")
err = excinfo.value
assert err.status == 404
assert err.code == "not_found"
assert str(err) == "City not found"
assert err.docs == "https://parseapi.com/docs#not_found"
assert err.request_id == "req_abc"
def test_non_json_error_body():
client, _ = make_client(lambda request: httpx.Response(400, text="gateway timeout"))
with pytest.raises(ParseAPIError) as excinfo:
client.country("US")
assert excinfo.value.code == "unknown_error"
def test_retry_then_success():
responses = [httpx.Response(500, json={"code": "server_error", "message": "boom"}), httpx.Response(200, json={"country": "us"})]
calls = []
def record(request):
calls.append(request)
return responses[len(calls) - 1]
client = ParseAPI("k", transport=httpx.MockTransport(record), retries=2)
assert client.country("US")["country"] == "us"
assert len(calls) == 2
def test_no_retry_on_404():
calls = []
def record(request):
calls.append(request)
return httpx.Response(404, json={"code": "not_found", "message": "nope"})
client = ParseAPI("k", transport=httpx.MockTransport(record), retries=2)
with pytest.raises(ParseAPIError):
client.country("XX")
assert len(calls) == 1
def test_gives_up_after_retries():
calls = []
def record(request):
calls.append(request)
return httpx.Response(429, json={"code": "rate_limited", "message": "slow down"})
client = ParseAPI("k", transport=httpx.MockTransport(record), retries=2)
with pytest.raises(ParseAPIError) as excinfo:
client.country("US")
assert excinfo.value.code == "rate_limited"
assert len(calls) == 3
def test_async_client():
async def run():
calls = []
def record(request):
calls.append(request)
return httpx.Response(200, json={"iso3": "USA"})
client = AsyncParseAPI("k", transport=httpx.MockTransport(record))
result = await client.country("US")
assert result["iso3"] == "USA"
ip_result = await client.ip.self(deep=True)
assert str(calls[1].url) == "https://api.parseapi.com/ip?deep=true"
await client.close()
asyncio.run(run())
@pytest.mark.parametrize("invoke,expected", URL_TABLE)
def test_async_url_mapping_matches_sync(invoke, expected):
async def run():
calls = []
def record(request):
calls.append(request)
return httpx.Response(200, json={"future_field": {"value": None}})
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(record), retries=0) as client:
result = await invoke(client)
assert len(calls) == 1
assert str(calls[0].url) == expected
assert result == {"future_field": {"value": None}}
asyncio.run(run())
@pytest.mark.parametrize("client_type", [ParseAPI, AsyncParseAPI])
@pytest.mark.parametrize("options", [
{"retries": -1}, {"retries": 1.5}, {"retries": float("inf")},
{"timeout": 0}, {"timeout": -1}, {"timeout": True}, {"timeout": float("nan")}, {"timeout": float("inf")},
])
def test_invalid_config_fails_at_construction(client_type, options):
with pytest.raises(ValueError):
client_type("test_key", **options)
def test_retry_after_http_date(monkeypatch):
from parseapi import _client
monkeypatch.setattr(_client.time, "time", lambda: 1788566400.0)
assert _client._retry_delay(0, "Sat, 05 Sep 2026 00:00:02 GMT") == 2.0
assert _client._retry_delay(0, "Sat, 05 Sep 2026 00:01:00 GMT") is None
assert _client._retry_delay(0, "Fri, 04 Sep 2026 00:00:00 GMT") == 0.0
def test_redirect_is_an_error_not_a_second_request():
client, calls = make_client(lambda request: httpx.Response(302, headers={"Location": "https://example.com/other"}))
with client:
with pytest.raises(ParseAPIError) as error:
client.country("US")
assert error.value.status == 302
assert len(calls) == 1
def test_async_redirect_is_an_error_not_a_second_request():
async def run():
calls = []
def redirect(request):
calls.append(request)
return httpx.Response(302, headers={"Location": "https://example.com/other"})
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(redirect)) as client:
with pytest.raises(ParseAPIError) as error:
await client.country("US")
assert error.value.status == 302
assert len(calls) == 1
asyncio.run(run())
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize("invoke", [
lambda p: p.carrier("555-0100"), lambda p: p.caller("555-0100"), lambda p: p.hlr("555-0100"),
lambda p: p.email("a@example.com", deep=True),
])
def test_paid_checks_default_to_one_attempt(async_mode, invoke):
calls = []
def fail(request):
calls.append(request)
return httpx.Response(503, json={"code": "unavailable"}, headers={"Retry-After": "0"})
if async_mode:
async def run():
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(fail)) as client:
with pytest.raises(ParseAPIError):
await invoke(client)
asyncio.run(run())
else:
with ParseAPI("test_key", transport=httpx.MockTransport(fail)) as client:
with pytest.raises(ParseAPIError):
invoke(client)
assert len(calls) == 1
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize("explicit,deep,expected", [(None, False, 3), (None, True, 1), (1, True, 2), (0, False, 1)])
def test_retry_policy_overrides(async_mode, explicit, deep, expected):
calls = []
def fail(request):
calls.append(request)
return httpx.Response(503, json={"code": "unavailable"}, headers={"Retry-After": "0"})
if async_mode:
async def run():
async with AsyncParseAPI("test_key", retries=explicit, transport=httpx.MockTransport(fail)) as client:
with pytest.raises(ParseAPIError):
await client.email("a@example.com", deep=deep)
asyncio.run(run())
else:
with ParseAPI("test_key", retries=explicit, transport=httpx.MockTransport(fail)) as client:
with pytest.raises(ParseAPIError):
client.email("a@example.com", deep=deep)
assert len(calls) == expected
def test_async_cancellation_does_not_retry():
async def run():
calls = []
started = asyncio.Event()
async def transport(request):
calls.append(request)
started.set()
await asyncio.Event().wait()
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(transport)) as client:
task = asyncio.create_task(client.country("US"))
await started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert len(calls) == 1
asyncio.run(run())
def test_dns_preserves_presentation_and_empty_records_sync_and_async():
async def run(body):
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(ok(body))) as client:
assert await client.dns("example.com", type="TXT") == body
for records in [[], [{"name": "example.com.", "type": "TXT", "ttl": 0, "value": '\"one\" \"two\"', "future": None}]]:
body = {"domain": "example.com", "records": records, "future": True}
client, _ = make_client(ok(body))
assert client.dns("example.com", type="TXT") == body
asyncio.run(run(body))
@pytest.mark.parametrize("record", json.loads(r'''[{"naics":"541511","name":"Custom Computer Programming Services","description":null,"level":6,"parent":"54151","parent_name":"Computer Systems Design and Related Services","children":[],"year":2022,"country":"US"},{"naics":"541511","name":"Custom Computer Programming Services","description":null,"level":6,"parent":"54151","parent_name":"Computer Systems Design and Related Services","children":[],"year":2022,"country":"US","exclusions":null,"match":null},{"naics":"541511","name":"Custom Computer Programming Services","description":null,"level":6,"parent":"54151","parent_name":"Computer Systems Design and Related Services","children":[],"year":2022,"country":"US","exclusions":[],"match":{"field":"future-field","text":"Future matching evidence","corrections":[],"future":true}},{"naics":"541511","name":"Custom Computer Programming Services","description":null,"level":6,"parent":"54151","parent_name":"Computer Systems Design and Related Services","children":[],"year":2022,"country":"US","exclusions":[{"description":"Designing integrated computer systems","codes":[{"naics":"541512","name":"Computer Systems Design Services"}]},{"description":"Activities classified elsewhere","codes":[]}],"match":{"field":"term","text":"Computer software programming services","corrections":[{"from":"sofware","to":"software"}]},"future":true}]'''))
def test_naics_exclusions_and_match_pass_through(record):
body = {"q": "sofware", "year": 2022, "country": "US", "results": [record]}
client, calls = make_client(ok(body))
assert client.industry.search("sofware") == body
assert calls[0].url.params["q"] == "sofware"
def test_async_naics_exclusions_and_match_pass_through():
async def run():
record = json.loads(r'{"naics":"541511","name":"Custom Computer Programming Services","description":null,"level":6,"parent":"54151","parent_name":"Computer Systems Design and Related Services","children":[],"year":2022,"country":"US","exclusions":[{"description":"Designing integrated computer systems","codes":[{"naics":"541512","name":"Computer Systems Design Services"}]},{"description":"Activities classified elsewhere","codes":[]}],"match":{"field":"term","text":"Computer software programming services","corrections":[{"from":"sofware","to":"software"}]},"future":true}''')
body = {"q": "sofware", "year": 2022, "country": "US", "results": [record]}
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(ok(body))) as client:
assert await client.industry.search("sofware") == body
asyncio.run(run())
def test_card_reference_null_false_and_error():
body = {"bin": "00123456", "prefix": "001234", "country": None, "issuer": "Fixture Bank", "brand": "future-brand", "type": None, "prepaid": False, "deep": {}, "future": True}
client, calls = make_client(ok(body))
assert client.card("00 1234-56") == body
assert str(calls[0].url) == "https://api.parseapi.com/card/00%201234-56"
async def check_async():
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(ok(body))) as client:
assert await client.card("00123456") == body
asyncio.run(check_async())
client, calls = make_client(lambda request: httpx.Response(400, json={"code": "invalid_input", "message": "Expected 6-11 digits"}))
with pytest.raises(ValueError):
client.card("bad/input")
assert len(calls) == 0
ADP_CASES = [('country', ['US'], {}), ('state', ['NC'], {'country': 'US'}), ('state.districts', ['NC'], {'country': 'US'}), ('district', ['37081'], {'country': 'US', 'state': 'NC'}), ('city', ['Charlotte'], {'country': 'US', 'state': 'NC'}), ('city.id', ['city_test'], {}), ('city.search', ['Charlotte'], {'country': 'US', 'state': 'NC', 'limit': 2}), ('city.nearest', [0, 0], {}), ('city.nearby', ['Charlotte'], {'radius': 0, 'unit': 'km', 'country': 'US', 'state': 'NC', 'limit': 2}), ('postal', ['28202'], {'country': 'US'}), ('postal.nearby', ['28202'], {'country': 'US', 'radius': 0, 'unit': 'km'}), ('postal.distance', ['28202', '10001'], {'country': 'US'}), ('carrier', ['+14155552671'], {'country': 'US'}), ('hlr', ['+447712345678'], {'country': 'GB'}), ('naics', ['31-33'], {}), ('naics.search', ['coffee'], {'limit': 2}), ('language', ['ar'], {}), ('name', ['Andrea'], {'country': 'IT'}), ('time', [], {'at': '2026-09-08', 'to': 'UTC'}), ('time.at', [0, 0], {'at': '2026-09-08', 'to': 'UTC'}), ('timezone', ['UTC'], {'at': '2026-09-08', 'to': 'UTC'}), ('timezone.at', [0, 0], {'at': '2026-09-08'}), ('date', ['03/04/2026'], {'format': 'dmy', 'to': '2026-09-08'}), ('date.today', [], {'to': '2026-09-08'}), ('emoji', ['fire'], {}), ('emoji.search', ['fire'], {'limit': 2})]
@pytest.mark.parametrize("method,args,options", ADP_CASES)
@pytest.mark.parametrize("async_mode", [False, True])
def test_adp_optional_depth_same_operation(method, args, options, async_mode):
calls = []
data = {"deep": {"zero": 0, "missing": None, "empty": [], "future": True}}
def reply(request):
calls.append(request)
return httpx.Response(200, json=data)
async def run():
client = (AsyncParseAPI if async_mode else ParseAPI)("k", transport=httpx.MockTransport(reply))
fn = client
for part in method.split("."):
fn = getattr(fn, part)
try:
for extra in ({}, {"deep": True}):
result = fn(*args, **options, **extra)
assert (await result if async_mode else result) == data
finally:
if async_mode: await client.close()
else: client.close()
asyncio.run(run())
assert calls[0].url.path == calls[1].url.path
if method == "bank":
assert json.loads(calls[1].content) == {**json.loads(calls[0].content), "deep": True}
assert not calls[1].url.query
else:
assert dict(calls[1].url.params) == {**dict(calls[0].url.params), "deep": "true"}
@pytest.mark.parametrize("name_local", ["München", None])
def test_name_local_preserved_sync_and_async(name_local):
record = {"name": "Munich", "name_local": name_local}
cases = [
(lambda p: p.country("DE"), record),
(lambda p: p.state("BY"), record),
(lambda p: p.city("Munich"), record),
(lambda p: p.language("de"), record),
(lambda p: p.holiday("DE"), {"holidays": [record]}),
(lambda p: p.point(48, 11, deep=True), {"deep": {"city": record}}),
]
for invoke, body in cases:
client, _ = make_client(ok(body))
with client:
assert invoke(client) == body
async def check():
async with AsyncParseAPI("test_key", transport=httpx.MockTransport(ok(body))) as client:
assert await invoke(client) == body
asyncio.run(check())
def test_async_currency_helpers_are_available_through_the_public_client():
async def run():
calls = []
def transport(request):
calls.append(request)
return httpx.Response(200, json={"currency": "JPY", "digits": 0})
async with AsyncParseAPI("fixture", transport=httpx.MockTransport(transport)) as client:
assert (await client.currency("JPY"))["digits"] == 0
await client.currency.rate("USD", "EUR", date="2026-10-30", amount=0)
assert calls[0].url.path == "/currency/JPY"
assert calls[0].headers["x-api-version"] == "2.2.0"
assert str(calls[1].url) == "https://api.parseapi.com/currency/USD/EUR?date=2026-10-30&amount=0"
asyncio.run(run())
def test_legacy_bin_is_not_a_public_lookup():
for client_type in (ParseAPI, AsyncParseAPI):
assert not hasattr(client_type, "bin")
assert callable(getattr(client_type, "card"))