1+ import asyncio
12from time import sleep
23from unittest import TestCase
34
5+ from httpx import ASGITransport , AsyncClient
46from starlette .endpoints import HTTPEndpoint
57from starlette .responses import JSONResponse
68from starlette .routing import Route , Router
7- from starlette .testclient import TestClient
89
910from piccolo_api .rate_limiting .middleware import (
1011 InMemoryLimitProvider ,
@@ -27,23 +28,34 @@ def test_limit(self):
2728 InMemoryLimitProvider (limit = 5 , timespan = 1 , block_duration = 1 ),
2829 )
2930
30- client = TestClient (app )
31+ # We have to use `httpx.AsyncClient` directly, because `TestClient`
32+ # was broken in this PR:
33+ # https://github.com/encode/starlette/pull/2377
34+ # `TestClient` no longer sends the client IP and port.
35+ # If a fix is released, we can go back to using `TestClient` directly.
36+ client = AsyncClient (
37+ transport = ASGITransport (app = app ),
38+ base_url = "http://testserver" ,
39+ )
40+
41+ async def run_test ():
42+ successful = 0
43+ for _ in range (20 ):
44+ response = await client .get ("/" )
45+ if response .status_code == 429 :
46+ break
47+ else :
48+ successful += 1
3149
32- successful = 0
33- for i in range (20 ):
34- response = client .get ("/" )
35- if response .status_code == 429 :
36- break
37- else :
38- successful += 1
50+ self .assertEqual (successful , 5 )
3951
40- self .assertEqual (successful , 5 )
52+ # After the 'block_duration' has expired, requests should be
53+ # allowed again.
54+ sleep (1.1 )
55+ response = await client .get ("/" )
56+ self .assertEqual (response .status_code , 200 )
4157
42- # After the 'block_duration' has expired, requests should be allowed
43- # again.
44- sleep (1.1 )
45- response = client .get ("/" )
46- self .assertEqual (response .status_code , 200 )
58+ asyncio .run (run_test ())
4759
4860 def test_memory_usage (self ):
4961 """
0 commit comments