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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
"""Tests for URL-pattern mount routing."""

from __future__ import annotations

import pytest

from eggfetch.compat.httpx import (
    Client,
    AsyncClient,
    MockTransport,
    Request,
    Response,
)
from eggfetch.compat.httpx._client import (
    _match_mount,
    _parse_mount_pattern,
    _MOUNT_NO_MATCH,
    _validate_mount_pattern,
)


def _make_handler(response_text: str):
    def handler(request):
        return Response(200, content=response_text.encode())

    return handler


class TestParseMountPattern:
    def test_all_catchall(self):
        assert _parse_mount_pattern("all://") == ("", None, None, "", False)

    def test_http_scheme_only(self):
        assert _parse_mount_pattern("http://") == ("http", None, None, "", False)

    def test_https_scheme_only(self):
        assert _parse_mount_pattern("https://") == ("https", None, None, "", False)

    def test_scheme_and_host(self):
        assert _parse_mount_pattern("http://example.com") == (
            "http", "example.com", None, "", False,
        )

    def test_scheme_host_port(self):
        assert _parse_mount_pattern("http://example.com:8080") == (
            "http", "example.com", 8080, "", False,
        )

    def test_scheme_host_path(self):
        assert _parse_mount_pattern("http://example.com/api") == (
            "http", "example.com", None, "/api", False,
        )

    def test_full_pattern(self):
        assert _parse_mount_pattern("https://example.com:443/api/v1") == (
            "https", "example.com", 443, "/api/v1", False,
        )

    def test_wildcard_domain(self):
        assert _parse_mount_pattern("all://*.example.com") == (
            "", "example.com", None, "", True,
        )

    def test_wildcard_domain_with_scheme(self):
        assert _parse_mount_pattern("https://*.example.com") == (
            "https", "example.com", None, "", True,
        )


class TestMountRouting:
    def test_exact_scheme_match(self):
        http_handler = _make_handler("http")
        https_handler = _make_handler("https")

        with Client(
            mounts={
                "http://": MockTransport(http_handler),
                "https://": MockTransport(https_handler),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"http"

    def test_longer_prefix_wins(self):
        general = _make_handler("general")
        specific = _make_handler("specific")

        with Client(
            mounts={
                "http://": MockTransport(general),
                "http://specific.example.com": MockTransport(specific),
            }
        ) as client:
            resp = client.get("http://specific.example.com/path")
            assert resp.content == b"specific"

    def test_no_match_falls_through(self):
        mock_resp = Response(200, content=b"default")

        def handler(request):
            return mock_resp

        with Client(transport=MockTransport(handler)) as client:
            resp = client.get("http://example.com/")
            assert resp.status_code == 200

    def test_mount_close_on_client_close(self):
        closed = []

        class TrackingTransport:
            def handle_request(self, request):
                return Response(200)

            def close(self):
                closed.append(True)

        client = Client(mounts={"http://": TrackingTransport()})
        client.close()
        assert len(closed) == 1


class TestComponentBasedMountRouting:
    """Tests for the component-based mount matching."""

    def test_all_catchall_matches_everything(self):
        with Client(
            mounts={"all://": MockTransport(_make_handler("catchall"))}
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"catchall"

    def test_host_specific_does_not_match_different_host(self):
        specific = _make_handler("specific")
        default = _make_handler("default")

        with Client(
            mounts={
                "http://specific.com": MockTransport(specific),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("http://other.com/")
            assert resp.content == b"default"

    def test_port_specific_match(self):
        port8080 = _make_handler("port8080")
        port9090 = _make_handler("port9090")

        with Client(
            mounts={
                "http://example.com:8080": MockTransport(port8080),
                "http://example.com:9090": MockTransport(port9090),
            }
        ) as client:
            resp = client.get("http://example.com:8080/")
            assert resp.content == b"port8080"

    def test_port_specific_no_match(self):
        port8080 = _make_handler("port8080")
        default = _make_handler("default")

        with Client(
            mounts={
                "http://example.com:8080": MockTransport(port8080),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("http://example.com:9090/")
            assert resp.content == b"default"

    def test_path_prefix_match(self):
        api = _make_handler("api")
        default = _make_handler("default")

        with Client(
            mounts={
                "http://example.com/api": MockTransport(api),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("http://example.com/api/users")
            assert resp.content == b"api"

    def test_path_prefix_no_match_without_prefix(self):
        api = _make_handler("api")
        default = _make_handler("default")

        with Client(
            mounts={
                "http://example.com/api": MockTransport(api),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("http://example.com/other")
            assert resp.content == b"default"

    def test_host_beats_scheme_only(self):
        host_handler = _make_handler("host")
        scheme_handler = _make_handler("scheme")

        with Client(
            mounts={
                "http://": MockTransport(scheme_handler),
                "http://example.com": MockTransport(host_handler),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"host"

    def test_host_with_path_beats_host_only(self):
        host_handler = _make_handler("host")
        path_handler = _make_handler("path")

        with Client(
            mounts={
                "http://example.com": MockTransport(host_handler),
                "http://example.com/api": MockTransport(path_handler),
            }
        ) as client:
            resp = client.get("http://example.com/api/endpoint")
            assert resp.content == b"path"

    def test_no_mount_returns_no_match(self):
        result = _match_mount("http://example.com/", {})
        assert result is _MOUNT_NO_MATCH

    def test_scheme_mismatch_skips(self):
        https_handler = _make_handler("https")
        default = _make_handler("default")

        with Client(
            mounts={
                "https://": MockTransport(https_handler),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"default"

    def test_host_port_beats_host_path(self):
        """host+port beats host+path."""
        port_handler = _make_handler("port")
        path_handler = _make_handler("path")

        with Client(
            mounts={
                "http://example.com:8080": MockTransport(port_handler),
                "http://example.com/api": MockTransport(path_handler),
            }
        ) as client:
            resp = client.get("http://example.com:8080/api/endpoint")
            assert resp.content == b"port"

    def test_full_url_beats_all(self):
        """Full URL pattern beats catch-all."""
        full_handler = _make_handler("full")
        catchall_handler = _make_handler("catchall")

        with Client(
            mounts={
                "http://example.com:8080/api": MockTransport(full_handler),
                "all://": MockTransport(catchall_handler),
            }
        ) as client:
            resp = client.get("http://example.com:8080/api/v1")
            assert resp.content == b"full"

    def test_no_explicit_port_matches_default(self):
        """URL without explicit port matches mount without port."""
        port_handler = _make_handler("port")
        default_handler = _make_handler("default")

        with Client(
            mounts={
                "http://example.com:8080": MockTransport(port_handler),
                "all://": MockTransport(default_handler),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"default"

    def test_base_url_plus_mount(self):
        """Mount matching uses the resolved URL (after base_url merge)."""
        api_handler = _make_handler("api")
        default_handler = _make_handler("default")

        with Client(
            base_url="http://example.com",
            mounts={
                "http://example.com/api": MockTransport(api_handler),
                "all://": MockTransport(default_handler),
            },
        ) as client:
            resp = client.get("/api/users")
            assert resp.content == b"api"


class TestMountPriorityEdgeCases:
    """Edge cases for mount routing priority."""

    def test_custom_scheme_mount(self):
        """Custom (non-http/https) scheme mounts work."""
        ftp_handler = _make_handler("ftp")

        with Client(
            mounts={"ftp://": MockTransport(ftp_handler)}
        ) as client:
            resp = client.get("ftp://files.example.com/data")
            assert resp.content == b"ftp"

    def test_scheme_only_http_does_not_match_https(self):
        """http:// mount must not match https:// URLs."""
        http_handler = _make_handler("http")
        https_handler = _make_handler("https")
        default_handler = _make_handler("default")

        with Client(
            mounts={
                "http://": MockTransport(http_handler),
                "https://": MockTransport(https_handler),
                "all://": MockTransport(default_handler),
            }
        ) as client:
            resp = client.get("https://example.com/")
            assert resp.content == b"https"

    def test_longer_path_wins_over_shorter(self):
        """More specific path prefix beats shorter one."""
        short_handler = _make_handler("short")
        long_handler = _make_handler("long")

        with Client(
            mounts={
                "http://example.com/api": MockTransport(short_handler),
                "http://example.com/api/v2": MockTransport(long_handler),
            }
        ) as client:
            resp = client.get("http://example.com/api/v2/resource")
            assert resp.content == b"long"

    def test_catchall_always_lowest_priority(self):
        """Catch-all always loses to any more-specific mount."""
        catchall = _make_handler("catchall")
        scheme = _make_handler("scheme")
        host = _make_handler("host")

        with Client(
            mounts={
                "all://": MockTransport(catchall),
                "http://": MockTransport(scheme),
                "http://example.com": MockTransport(host),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"host"

    def test_mount_none_transport_falls_through(self):
        """Passing None as transport value falls through to default transport."""
        def handler(request):
            return Response(200, content=b"default")

        with Client(
            transport=MockTransport(handler),
            mounts={"http://none.example.com": None},
        ) as client:
            resp = client.get("http://none.example.com/")
            assert resp.content == b"default"

    def test_empty_mounts_dict(self):
        """Empty mounts dict falls through to default transport."""
        def handler(request):
            return Response(200, content=b"default")

        with Client(transport=MockTransport(handler), mounts={}) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"default"

    def test_host_case_insensitive(self):
        """Mount matching is case-insensitive for hosts."""
        upper_handler = _make_handler("upper")

        with Client(
            mounts={
                "http://Example.Com": MockTransport(upper_handler),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"upper"

    def test_path_exact_match(self):
        """Exact path match (no trailing content) works."""
        handler = _make_handler("exact")

        with Client(
            mounts={"http://example.com/api": MockTransport(handler)}
        ) as client:
            resp = client.get("http://example.com/api")
            assert resp.content == b"exact"

    def test_mount_with_query_string_ignored(self):
        """Query strings don't affect mount matching."""
        handler = _make_handler("matched")

        with Client(
            mounts={"http://example.com/api": MockTransport(handler)}
        ) as client:
            resp = client.get("http://example.com/api?key=value")
            assert resp.content == b"matched"


class TestMountPatternValidation:
    """Test that malformed mount patterns are rejected at construction."""

    def test_valid_patterns_accepted(self):
        for pattern in [
            "all://", "http://", "https://",
            "http://example.com", "https://example.com:8080",
            "all://*.example.com", "https://*.example.com",
        ]:
            _validate_mount_pattern(pattern)

    def test_missing_scheme_rejected(self):
        with pytest.raises(ValueError, match="scheme"):
            Client(mounts={"example.com": MockTransport(_make_handler("x"))})

    def test_bad_wildcard_rejected(self):
        with pytest.raises(ValueError, match="Wildcard"):
            Client(mounts={"all://*": MockTransport(_make_handler("x"))})

    def test_bare_wildcard_rejected(self):
        with pytest.raises(ValueError, match="Wildcard"):
            Client(mounts={"all://*": MockTransport(_make_handler("x"))})

    def test_bare_wildcard_dot_rejected(self):
        with pytest.raises(ValueError, match="Wildcard"):
            Client(mounts={"all://*.": MockTransport(_make_handler("x"))})


class TestWildcardDomainMounts:
    """Tests for wildcard domain mount patterns (Track 3)."""

    def test_wildcard_matches_subdomain(self):
        handler = _make_handler("wildcard")
        with Client(
            mounts={"all://*.example.com": MockTransport(handler)}
        ) as client:
            resp = client.get("http://sub.example.com/")
            assert resp.content == b"wildcard"

    def test_wildcard_matches_deep_subdomain(self):
        handler = _make_handler("deep")
        with Client(
            mounts={"all://*.example.com": MockTransport(handler)}
        ) as client:
            resp = client.get("http://a.b.example.com/")
            assert resp.content == b"deep"

    def test_wildcard_does_not_match_apex(self):
        handler = _make_handler("wildcard")
        default = _make_handler("default")
        with Client(
            mounts={
                "all://*.example.com": MockTransport(handler),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("http://example.com/")
            assert resp.content == b"default"

    def test_wildcard_scheme_specific(self):
        handler = _make_handler("https-wildcard")
        default = _make_handler("default")
        with Client(
            mounts={
                "https://*.example.com": MockTransport(handler),
                "all://": MockTransport(default),
            }
        ) as client:
            resp = client.get("https://sub.example.com/")
            assert resp.content == b"https-wildcard"
            resp2 = client.get("http://sub.example.com/")
            assert resp2.content == b"default"

    def test_wildcard_beats_catchall(self):
        handler = _make_handler("wildcard")
        catchall = _make_handler("catchall")
        with Client(
            mounts={
                "all://*.example.com": MockTransport(handler),
                "all://": MockTransport(catchall),
            }
        ) as client:
            resp = client.get("http://sub.example.com/")
            assert resp.content == b"wildcard"

    def test_exact_host_beats_wildcard(self):
        exact = _make_handler("exact")
        wildcard = _make_handler("wildcard")
        with Client(
            mounts={
                "http://foo.example.com": MockTransport(exact),
                "all://*.example.com": MockTransport(wildcard),
            }
        ) as client:
            resp = client.get("http://foo.example.com/")
            assert resp.content == b"exact"


class TestMountPriorityAsync:
    """Async mount priority edge cases."""

    @pytest.mark.asyncio
    async def test_async_host_port_beats_host_path(self):
        async def port_handler(request):
            return Response(200, content=b"port")

        async def path_handler(request):
            return Response(200, content=b"path")

        async with AsyncClient(
            mounts={
                "http://example.com:8080": MockTransport(port_handler),
                "http://example.com/api": MockTransport(path_handler),
            }
        ) as client:
            resp = await client.get("http://example.com:8080/api/endpoint")
            assert resp.content == b"port"

    @pytest.mark.asyncio
    async def test_async_custom_scheme(self):
        async def ftp_handler(request):
            return Response(200, content=b"ftp-async")

        async with AsyncClient(
            mounts={"ftp://": MockTransport(ftp_handler)}
        ) as client:
            resp = await client.get("ftp://files.example.com/")
            assert resp.content == b"ftp-async"


class TestAsyncMountRouting:
    @pytest.mark.asyncio
    async def test_async_mount_dispatch(self):
        async def handler(request):
            return Response(200, content=b"async-mount")

        async with AsyncClient(
            mounts={"http://": MockTransport(handler)}
        ) as client:
            resp = await client.get("http://example.com/")
            assert resp.content == b"async-mount"

    @pytest.mark.asyncio
    async def test_async_transport_constructor(self):
        async def handler(request):
            return Response(200, content=b"async-transport")

        async with AsyncClient(
            async_transport=MockTransport(handler)
        ) as client:
            resp = await client.get("http://example.com/")
            assert resp.content == b"async-transport"


class TestTransportOwnership:
    """Tests for transport close deduplication (Track 6)."""

    def test_duplicate_mount_instance_closed_once(self):
        close_count = []

        class CountingTransport:
            def handle_request(self, request):
                return Response(200)

            def close(self):
                close_count.append(1)

        transport = CountingTransport()
        with Client(
            mounts={
                "http://a.example.com": transport,
                "http://b.example.com": transport,
            }
        ) as client:
            client.get("http://a.example.com/")
        # The same transport instance should only be closed once.
        assert sum(close_count) == 1

    def test_different_mount_instances_closed_separately(self):
        close_count = []

        class CountingTransport:
            def __init__(self):
                pass

            def handle_request(self, request):
                return Response(200)

            def close(self):
                close_count.append(1)

        t1 = CountingTransport()
        t2 = CountingTransport()
        with Client(
            mounts={
                "http://a.example.com": t1,
                "http://b.example.com": t2,
            }
        ) as client:
            client.get("http://a.example.com/")
        # Two different instances → closed twice.
        assert sum(close_count) == 2