|
1 | | -import asyncio |
| 1 | +import httpx |
2 | 2 | import pytest |
| 3 | +import fakeredis |
| 4 | +from typing import AsyncIterator |
| 5 | +from redis import asyncio as redis |
3 | 6 | from unittest.mock import AsyncMock, patch |
| 7 | +from starlette.testclient import TestClient |
4 | 8 |
|
| 9 | +from app import app |
| 10 | +from lib.store import Store |
5 | 11 |
|
6 | | -@pytest.fixture(scope="session") |
7 | | -def event_loop(): |
8 | | - """Create an instance of the default event loop for the test session.""" |
9 | | - loop = asyncio.new_event_loop() |
10 | | - yield loop |
11 | | - loop.close() |
12 | | - |
13 | | -@pytest.fixture(autouse=True) |
14 | | -def setup_test_environment(): |
15 | | - """Set up test environment before each test.""" |
16 | | - # Mock Redis client to avoid needing actual Redis instance |
17 | | - with patch('app.redis') as mock_redis: |
18 | | - mock_redis.close = AsyncMock() |
19 | | - yield mock_redis |
| 12 | + |
| 13 | +@pytest.fixture |
| 14 | +def anyio_backend(): |
| 15 | + return 'asyncio' |
| 16 | + |
| 17 | +@pytest.fixture |
| 18 | +async def redis_client() -> AsyncIterator[redis.Redis]: |
| 19 | + async with fakeredis.FakeAsyncRedis() as client: |
| 20 | + yield client |
| 21 | + |
| 22 | +@pytest.fixture |
| 23 | +async def test_client(redis_client: redis.Redis) -> AsyncIterator[httpx.AsyncClient]: |
| 24 | + def get_redis_override(*args, **kwargs) -> redis.Redis: |
| 25 | + return redis_client |
| 26 | + |
| 27 | + # Make sure the app has the Redis state set up |
| 28 | + app.state.redis = redis_client |
| 29 | + |
| 30 | + transport = httpx.ASGITransport(app=app) |
| 31 | + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: |
| 32 | + # Patch the `get_redis` method of the `Store` class |
| 33 | + with patch.object(Store, 'get_redis', new=get_redis_override): |
| 34 | + print("") |
| 35 | + yield client |
| 36 | + |
| 37 | +@pytest.fixture |
| 38 | +async def websocket_client(redis_client: redis.Redis): |
| 39 | + """Alternative WebSocket client using Starlette TestClient.""" |
| 40 | + def get_redis_override(*args, **kwargs) -> redis.Redis: |
| 41 | + return redis_client |
| 42 | + |
| 43 | + # Make sure the app has the Redis state set up |
| 44 | + app.state.redis = redis_client |
| 45 | + |
| 46 | + # Patch the `get_redis` method of the `Store` class |
| 47 | + with patch.object(Store, 'get_redis', new=get_redis_override): |
| 48 | + with TestClient(app) as client: |
| 49 | + print("") |
| 50 | + yield client |
| 51 | + |
| 52 | +@pytest.mark.anyio |
| 53 | +async def test_mocks(test_client: httpx.AsyncClient) -> None: |
| 54 | + response = await test_client.get("/nonexistent-endpoint") |
| 55 | + assert response.status_code == 404, "Expected 404 for nonexistent endpoint" |
0 commit comments