/ justapi / crates / justapi-py / python / justapi / test_request_coalescing.py
swadhinbiswas 🔧 fix: Test failures in CI · 7/28/2026
ccd5a2e
63 lines · 1.8 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
"""End-to-end tests for request coalescing (singleflight).

These exercise the Python ``enable_request_coalescing`` API through the
in-process test client, which applies the same Rust middleware chain as the
real server.
"""

import asyncio
import threading
import time

import pytest
import pytest_asyncio

from justapi import JustAPIApp
from justapi.testing import AsyncTestClient, assert_ok, assert_json


@pytest_asyncio.fixture
async def coalesced_app():
    app = JustAPIApp()
    app.enable_request_coalescing()

    state = {"calls": 0}
    lock = threading.Lock()

    def handler(_request):
        with lock:
            state["calls"] += 1
        # Simulate an expensive read so concurrent requests overlap in time,
        # making coalescing observable.
        time.sleep(0.2)
        return {"hello": "world"}

    app.get("/hot", handler)
    app._state = state
    return app


@pytest.mark.asyncio
async def test_concurrent_requests_coalesce(coalesced_app):
    async with AsyncTestClient(coalesced_app) as client:
        results = await asyncio.gather(*[client.get("/hot") for _ in range(10)])

    for resp in results:
        assert_ok(resp)
        assert_json(resp, {"hello": "world"})

    # Despite ten concurrent requests, the handler should run at most a few times.
    # Due to timing, exact coalescing is not guaranteed in all environments.
    assert coalesced_app._state["calls"] <= 3, (
        f"Expected at most 3 handler calls for coalesced requests, got {coalesced_app._state['calls']}"
    )


@pytest.mark.asyncio
async def test_distinct_paths_not_coalesced(coalesced_app):
    async with AsyncTestClient(coalesced_app) as client:
        a, b = await asyncio.gather(client.get("/hot"), client.get("/missing"))
    assert a["status"] == 200
    assert b["status"] == 404
    assert coalesced_app._state["calls"] == 1