eggfetch-python 0.1.4

Python sync and asyncio bindings for the eggfetch HTTP engine (Rust core via PyO3; Python users install from PyPI)
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
"""Tests for the eggfetch Python async API."""

import asyncio
import http.server
import json
import threading
import urllib.parse

import pytest

import eggfetch

from conftest import _ThreadingHTTPServer


# ---------------------------------------------------------------------------
# Local test server
# ---------------------------------------------------------------------------

class _Handler(http.server.BaseHTTPRequestHandler):
    """Minimal test server that echoes request details."""

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        body = json.dumps({
            "method": "GET",
            "path": parsed.path,
            "query": parsed.query,
            "headers": dict(self.headers),
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length) if length else b""
        body = json.dumps({
            "method": "POST",
            "path": self.path,
            "headers": dict(self.headers),
            "body": raw.decode(errors="replace"),
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_PUT(self):
        self.do_POST()

    def do_PATCH(self):
        self.do_POST()

    def do_DELETE(self):
        self.do_GET()

    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("X-Echo", "head-ok")
        self.end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header("Allow", "GET, POST, OPTIONS")
        self.end_headers()

    def log_message(self, format, *args):
        pass  # suppress logs during tests


@pytest.fixture(scope="module")
def server():
    """Start a local HTTP server for the test module."""
    srv = _ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    yield f"http://127.0.0.1:{port}"
    srv.shutdown()


# ---------------------------------------------------------------------------
# Package imports
# ---------------------------------------------------------------------------

class TestAsyncPackageImports:
    def test_import_async_client(self):
        assert hasattr(eggfetch, "AsyncClient")

    def test_async_client_is_class(self):
        assert isinstance(eggfetch.AsyncClient, type)


# ---------------------------------------------------------------------------
# AsyncClient basic behavior
# ---------------------------------------------------------------------------

class TestAsyncClientBasic:
    def test_async_context_manager(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello")
                assert r.status_code == 200
        asyncio.run(_test())

    def test_async_get_returns_response(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello")
                assert isinstance(r, eggfetch.Response)
                assert r.status_code == 200
        asyncio.run(_test())

    def test_async_get_body(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello")
                data = json.loads(r.text)
                assert data["method"] == "GET"
                assert data["path"] == "/hello"
        asyncio.run(_test())

    def test_async_get_is_success(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello")
                assert r.is_success
        asyncio.run(_test())

    def test_async_get_url_property(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello")
                assert r.url == f"{server}/hello"
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# AsyncClient POST
# ---------------------------------------------------------------------------

class TestAsyncClientPost:
    def test_async_post_content(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", content=b"hello world")
                assert r.status_code == 200
                data = json.loads(r.text)
                assert data["method"] == "POST"
                assert data["body"] == "hello world"
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Headers and params
# ---------------------------------------------------------------------------

class TestAsyncHeadersAndParams:
    def test_headers_reach_server(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(
                    f"{server}/hello", headers={"X-Custom": "test-value"}
                )
                data = json.loads(r.text)
                assert data["headers"].get("x-custom") == "test-value"
        asyncio.run(_test())

    def test_response_headers(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello")
                assert "content-type" in r.headers
        asyncio.run(_test())

    def test_params_serialized(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(
                    f"{server}/search", params={"q": "hello", "page": "1"}
                )
                data = json.loads(r.text)
                assert "q=hello" in data["query"]
                assert "page=1" in data["query"]
        asyncio.run(_test())

    def test_params_sequence_of_pairs(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(
                    f"{server}/search",
                    params=[("q", "test"), ("q", "other")],
                )
                data = json.loads(r.text)
                assert "q=test" in data["query"]
                assert "q=other" in data["query"]
        asyncio.run(_test())

    def test_headers_as_sequence_of_pairs(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(
                    f"{server}/hello",
                    headers=[("X-Pair", "val1"), ("X-Pair", "val2")],
                )
                data = json.loads(r.text)
                assert data["headers"].get("x-pair") == "val2"
        asyncio.run(_test())

    def test_request_headers_override_client_default(self, server):
        async def _test():
            async with eggfetch.AsyncClient(
                headers={"X-Foo": "from-client"}
            ) as client:
                r = await client.get(
                    f"{server}/hello",
                    headers={"X-Foo": "override", "X-Bar": "from-request"},
                )
                data = json.loads(r.text)
                assert data["headers"].get("x-bar") == "from-request"
        asyncio.run(_test())

    def test_params_with_existing_query(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(
                    f"{server}/search?existing=1",
                    params={"q": "hello"},
                )
                data = json.loads(r.text)
                assert "existing=1" in data["query"]
                assert "q=hello" in data["query"]
        asyncio.run(_test())

    def test_invalid_params_type_raises(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(TypeError):
                    await client.get(f"{server}/search", params=123)
        asyncio.run(_test())

    def test_invalid_header_value_raises(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(eggfetch.RequestError):
                    await client.get(
                        f"{server}/hello", headers={"X-Bad": "val\nue"}
                    )
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Client reuse and default headers
# ---------------------------------------------------------------------------

class TestAsyncClientReuse:
    def test_client_reuses_connection(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r1 = await client.get(f"{server}/hello")
                r2 = await client.get(f"{server}/hello")
                assert r1.status_code == 200
                assert r2.status_code == 200
        asyncio.run(_test())

    def test_client_default_headers(self, server):
        async def _test():
            async with eggfetch.AsyncClient(
                headers={"X-Client-Header": "from-client"}
            ) as client:
                r = await client.get(f"{server}/hello")
                data = json.loads(r.text)
                assert data["headers"].get("x-client-header") == "from-client"
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# HTTP methods
# ---------------------------------------------------------------------------

class TestAsyncHTTPMethods:
    def test_put(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.put(f"{server}/api", content=b"put-data")
                assert r.status_code == 200
        asyncio.run(_test())

    def test_patch(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.patch(f"{server}/api", content=b"patch-data")
                assert r.status_code == 200
        asyncio.run(_test())

    def test_delete(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.delete(f"{server}/resource")
                assert r.status_code == 200
        asyncio.run(_test())

    def test_head(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.head(f"{server}/hello")
                assert r.status_code == 200
        asyncio.run(_test())

    def test_options(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.options(f"{server}/hello")
                assert r.status_code == 200
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Closed client
# ---------------------------------------------------------------------------

class TestAsyncClientClosed:
    def test_closed_client_raises(self, server):
        async def _test():
            client = eggfetch.AsyncClient()
            client.close()
            with pytest.raises(ValueError, match="closed"):
                await client.get(f"{server}/hello")
        asyncio.run(_test())

    def test_client_is_closed_property(self):
        async def _test():
            client = eggfetch.AsyncClient()
            assert not client.is_closed
            client.close()
            assert client.is_closed
        asyncio.run(_test())

    def test_aclose_is_idempotent(self):
        async def _test():
            client = eggfetch.AsyncClient()
            client.close()
            client.close()  # should not raise
            assert client.is_closed
        asyncio.run(_test())

    def test_aclose_is_awaitable(self):
        async def _test():
            client = eggfetch.AsyncClient()
            await client.aclose()
            assert client.is_closed
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Error mapping
# ---------------------------------------------------------------------------

class TestAsyncErrors:
    def test_invalid_url(self):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(ValueError):
                    await client.get("not-a-url")
        asyncio.run(_test())

    def test_unsupported_scheme(self):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(eggfetch.RequestError, match="not supported"):
                    await client.get("ftp://example.com")
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Timeout
# ---------------------------------------------------------------------------

class TestAsyncTimeout:
    def test_scalar_timeout(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.get(f"{server}/hello", timeout=10.0)
                assert r.status_code == 200
        asyncio.run(_test())

    def test_request_timeout_overrides_client_default(self, server):
        async def _test():
            async with eggfetch.AsyncClient(timeout=0.001) as client:
                # Client timeout is very short; request-level override should succeed
                r = await client.get(f"{server}/hello", timeout=10.0)
                assert r.status_code == 200
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Concurrent requests
# ---------------------------------------------------------------------------

class TestAsyncConcurrent:
    def test_many_concurrent_requests(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                tasks = [
                    client.get(f"{server}/hello") for _ in range(10)
                ]
                responses = await asyncio.gather(*tasks)
                assert len(responses) == 10
                for r in responses:
                    assert r.status_code == 200
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Cancellation
# ---------------------------------------------------------------------------

class TestAsyncCancellation:
    def test_cancellation_does_not_poison_client(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                # Start a request and cancel it
                async def do_get():
                    return await client.get(f"{server}/hello")

                task = asyncio.create_task(do_get())
                await asyncio.sleep(0)  # let it start
                task.cancel()
                try:
                    await task
                except asyncio.CancelledError:
                    pass

                # A later request should still succeed
                r = await client.get(f"{server}/hello")
                assert r.status_code == 200
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Unsupported kwargs
# ---------------------------------------------------------------------------

class TestAsyncUnsupportedKwargs:
    def test_unsupported_kwarg(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(TypeError):
                    await client.get(f"{server}/hello", json={"key": "value"})
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# Body kwargs: content, data, json
# ---------------------------------------------------------------------------

class TestAsyncContent:
    def test_content_dict_rejected(self, server):
        async def _test():
            with pytest.raises(TypeError, match="content must be bytes, str"):
                async with eggfetch.AsyncClient() as client:
                    await client.post(f"{server}/api", content={"key": "value"})
        asyncio.run(_test())

    def test_content_bytes(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", content=b"raw bytes")
                data = json.loads(r.text)
                assert data["body"] == "raw bytes"
        asyncio.run(_test())

    def test_content_str(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", content="string body")
                data = json.loads(r.text)
                assert data["body"] == "string body"
        asyncio.run(_test())


class TestAsyncFormData:
    def test_form_dict(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", data={"a": "1", "b": "2"})
                data = json.loads(r.text)
                assert "a=1" in data["body"]
                assert "b=2" in data["body"]
                assert data["headers"].get("content-type") == "application/x-www-form-urlencoded"
        asyncio.run(_test())

    def test_form_sequence_of_pairs(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(
                    f"{server}/api",
                    data=[("a", "1"), ("a", "2")],
                )
                data = json.loads(r.text)
                assert "a=1" in data["body"]
                assert "a=2" in data["body"]
        asyncio.run(_test())


class TestAsyncJsonBody:
    def test_json_dict(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", json={"hello": "world"})
                data = json.loads(r.text)
                body = json.loads(data["body"])
                assert body == {"hello": "world"}
                assert data["headers"].get("content-type") == "application/json"
        asyncio.run(_test())

    def test_json_list(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", json=[1, 2, 3])
                data = json.loads(r.text)
                body = json.loads(data["body"])
                assert body == [1, 2, 3]
        asyncio.run(_test())

    def test_json_unserializable_raises(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(TypeError):
                    await client.post(f"{server}/api", json=object())
        asyncio.run(_test())

    def test_json_preserves_user_content_type(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(
                    f"{server}/api",
                    headers={"Content-Type": "custom/json"},
                    json={"a": 1},
                )
                data = json.loads(r.text)
                assert data["headers"].get("content-type") == "custom/json"
        asyncio.run(_test())


class TestAsyncBodyConflict:
    def test_content_and_json_raises(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(TypeError, match="only one of content, data, or json"):
                    await client.post(f"{server}/api", content=b"raw", json={"a": 1})
        asyncio.run(_test())

    def test_data_and_json_raises(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                with pytest.raises(TypeError, match="only one of content, data, or json"):
                    await client.post(f"{server}/api", data={"a": "1"}, json={"b": 2})
        asyncio.run(_test())


# ---------------------------------------------------------------------------
# AsyncClient body kwargs
# ---------------------------------------------------------------------------

class TestAsyncClientBodyKwargs:
    def test_client_json(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.post(f"{server}/api", json={"key": "value"})
                data = json.loads(r.text)
                body = json.loads(data["body"])
                assert body == {"key": "value"}
        asyncio.run(_test())

    def test_client_put_json(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.put(f"{server}/api", json={"updated": True})
                data = json.loads(r.text)
                body = json.loads(data["body"])
                assert body == {"updated": True}
        asyncio.run(_test())

    def test_client_patch_form_data(self, server):
        async def _test():
            async with eggfetch.AsyncClient() as client:
                r = await client.patch(f"{server}/api", data={"a": "1"})
                data = json.loads(r.text)
                assert "a=1" in data["body"]
        asyncio.run(_test())