MCPcopy Create free account
hub / github.com/aio-libs/aiohttp / run_tests

Function run_tests

examples/token_refresh_middleware.py:261–323  ·  view source on GitHub ↗

Run all token refresh middleware tests.

()

Source from the content-addressed store, hash-verified

259
260
261async def run_tests() -> None:
262 """Run all token refresh middleware tests."""
263 # Create token refresh middleware
264 # In a real app, this refresh token would be securely stored
265 token_middleware = TokenRefreshMiddleware(
266 token_endpoint="http://localhost:8080/token/refresh",
267 refresh_token="demo_refresh_token_12345",
268 )
269
270 async with ClientSession(middlewares=(token_middleware,)) as session:
271 print("=== Test 1: First request (will trigger token refresh) ===")
272 async with session.get("http://localhost:8080/api/protected") as resp:
273 if resp.status == 200:
274 data = await resp.json()
275 print(f"Success! Response: {data}")
276 else:
277 print(f"Failed with status: {resp.status}")
278
279 print("\n=== Test 2: Second request (uses cached token) ===")
280 async with session.get("http://localhost:8080/api/user") as resp:
281 if resp.status == 200:
282 data = await resp.json()
283 print(f"User info: {data}")
284 else:
285 print(f"Failed with status: {resp.status}")
286
287 print("\n=== Test 3: Multiple concurrent requests ===")
288 print("(Should only refresh token once)")
289 coros: list[Coroutine[Any, Any, ClientResponse]] = []
290 for i in range(3):
291 coro = session.get("http://localhost:8080/api/protected")
292 coros.append(coro)
293
294 responses = await asyncio.gather(*coros)
295 for i, resp in enumerate(responses):
296 async with resp:
297 if resp.status == 200:
298 print(f"Request {i + 1}: Success")
299 else:
300 print(f"Request {i + 1}: Failed with {resp.status}")
301
302 print("\n=== Test 4: Simulate token expiry ===")
303 # For demo purposes, force token expiry
304 token_middleware.token_expires_at = time.time() - 1
305
306 print("Token expired, next request should trigger refresh...")
307 async with session.get("http://localhost:8080/api/protected") as resp:
308 if resp.status == 200:
309 data = await resp.json()
310 print(f"Success after token refresh! Response: {data}")
311 else:
312 print(f"Failed with status: {resp.status}")
313
314 print("\n=== Test 5: Request without middleware (no auth) ===")
315 # Make a request without any middleware to show the difference
316 async with session.get(
317 "http://localhost:8080/api/protected",
318 middlewares=(), # Bypass all middleware for this request

Callers 1

mainFunction · 0.70

Calls 5

ClientSessionClass · 0.90
appendMethod · 0.80
getMethod · 0.45
jsonMethod · 0.45

Tested by

no test coverage detected