|
| 1 | +""" |
| 2 | +Tests for PostHog Django middleware in async context. |
| 3 | +
|
| 4 | +These tests verify that the middleware correctly handles: |
| 5 | +1. Async user access (request.auser() in Django 5) |
| 6 | +2. Exception capture in both sync and async views |
| 7 | +3. No SynchronousOnlyOperation errors in async context |
| 8 | +
|
| 9 | +Tests run directly against the ASGI application without needing a server. |
| 10 | +""" |
| 11 | + |
| 12 | +import os |
| 13 | +import django |
| 14 | + |
| 15 | +# Setup Django before importing anything else |
| 16 | +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testdjango.settings") |
| 17 | +django.setup() |
| 18 | + |
| 19 | +import pytest # noqa: E402 |
| 20 | +from httpx import AsyncClient, ASGITransport # noqa: E402 |
| 21 | +from django.core.asgi import get_asgi_application # noqa: E402 |
| 22 | + |
| 23 | + |
| 24 | +@pytest.fixture(scope="session") |
| 25 | +def asgi_app(): |
| 26 | + """Shared ASGI application for all tests.""" |
| 27 | + return get_asgi_application() |
| 28 | + |
| 29 | + |
| 30 | +@pytest.mark.asyncio |
| 31 | +async def test_async_user_access(asgi_app): |
| 32 | + """ |
| 33 | + Test that middleware can access request.user in async context. |
| 34 | +
|
| 35 | + In Django 5, this requires using await request.auser() instead of request.user |
| 36 | + to avoid SynchronousOnlyOperation error. |
| 37 | +
|
| 38 | + Without authentication, request.user is AnonymousUser which doesn't |
| 39 | + trigger the lazy loading bug. This test verifies the middleware works |
| 40 | + in the common case. |
| 41 | + """ |
| 42 | + async with AsyncClient( |
| 43 | + transport=ASGITransport(app=asgi_app), base_url="http://testserver" |
| 44 | + ) as ac: |
| 45 | + response = await ac.get("/test/async-user") |
| 46 | + |
| 47 | + assert response.status_code == 200 |
| 48 | + data = response.json() |
| 49 | + assert data["status"] == "success" |
| 50 | + assert "django_version" in data |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.django_db(transaction=True) |
| 54 | +@pytest.mark.asyncio |
| 55 | +async def test_async_authenticated_user_access(asgi_app): |
| 56 | + """ |
| 57 | + Test that middleware can access an authenticated user in async context. |
| 58 | +
|
| 59 | + This is the critical test that triggers the SynchronousOnlyOperation bug |
| 60 | + in v6.7.11. When AuthenticationMiddleware sets request.user to a |
| 61 | + SimpleLazyObject wrapping a database query, accessing user.pk or user.email |
| 62 | + in async context causes the error. |
| 63 | +
|
| 64 | + In v6.7.11, extract_request_user() does getattr(user, "is_authenticated", False) |
| 65 | + which triggers the lazy object evaluation synchronously. |
| 66 | +
|
| 67 | + The fix uses await request.auser() instead to avoid this. |
| 68 | + """ |
| 69 | + from django.contrib.auth import get_user_model |
| 70 | + from django.test import Client |
| 71 | + from asgiref.sync import sync_to_async |
| 72 | + from django.test import override_settings |
| 73 | + |
| 74 | + # Create a test user (must use sync_to_async since we're in async test) |
| 75 | + User = get_user_model() |
| 76 | + |
| 77 | + @sync_to_async |
| 78 | + def create_or_get_user(): |
| 79 | + user, created = User.objects.get_or_create( |
| 80 | + username="testuser", |
| 81 | + defaults={ |
| 82 | + |
| 83 | + }, |
| 84 | + ) |
| 85 | + if created: |
| 86 | + user.set_password("testpass123") |
| 87 | + user.save() |
| 88 | + return user |
| 89 | + |
| 90 | + user = await create_or_get_user() |
| 91 | + |
| 92 | + # Create a session with authenticated user (sync operation) |
| 93 | + @sync_to_async |
| 94 | + def create_session(): |
| 95 | + client = Client() |
| 96 | + client.force_login(user) |
| 97 | + return client.cookies.get("sessionid") |
| 98 | + |
| 99 | + session_cookie = await create_session() |
| 100 | + |
| 101 | + if not session_cookie: |
| 102 | + pytest.skip("Could not create authenticated session") |
| 103 | + |
| 104 | + # Make request with session cookie - this should trigger the bug in v6.7.11 |
| 105 | + # Disable exception capture to see the SynchronousOnlyOperation clearly |
| 106 | + with override_settings(POSTHOG_MW_CAPTURE_EXCEPTIONS=False): |
| 107 | + async with AsyncClient( |
| 108 | + transport=ASGITransport(app=asgi_app), |
| 109 | + base_url="http://testserver", |
| 110 | + cookies={"sessionid": session_cookie.value}, |
| 111 | + ) as ac: |
| 112 | + response = await ac.get("/test/async-user") |
| 113 | + |
| 114 | + assert response.status_code == 200 |
| 115 | + data = response.json() |
| 116 | + assert data["status"] == "success" |
| 117 | + assert data["user_authenticated"] |
| 118 | + |
| 119 | + |
| 120 | +@pytest.mark.asyncio |
| 121 | +async def test_sync_user_access(asgi_app): |
| 122 | + """ |
| 123 | + Test that middleware works with sync views. |
| 124 | +
|
| 125 | + This should always work regardless of middleware version. |
| 126 | + """ |
| 127 | + async with AsyncClient( |
| 128 | + transport=ASGITransport(app=asgi_app), base_url="http://testserver" |
| 129 | + ) as ac: |
| 130 | + response = await ac.get("/test/sync-user") |
| 131 | + |
| 132 | + assert response.status_code == 200 |
| 133 | + data = response.json() |
| 134 | + assert data["status"] == "success" |
| 135 | + |
| 136 | + |
| 137 | +@pytest.mark.asyncio |
| 138 | +async def test_async_exception_capture(asgi_app): |
| 139 | + """ |
| 140 | + Test that middleware handles exceptions from async views. |
| 141 | +
|
| 142 | + The middleware's process_exception() method captures view exceptions to PostHog |
| 143 | + before Django converts them to 500 responses. This test verifies the exception |
| 144 | + causes a 500 response. See test_exception_capture.py for tests that verify |
| 145 | + actual exception capture to PostHog. |
| 146 | + """ |
| 147 | + async with AsyncClient( |
| 148 | + transport=ASGITransport(app=asgi_app), base_url="http://testserver" |
| 149 | + ) as ac: |
| 150 | + response = await ac.get("/test/async-exception") |
| 151 | + |
| 152 | + # Django returns 500 for unhandled exceptions |
| 153 | + assert response.status_code == 500 |
| 154 | + |
| 155 | + |
| 156 | +@pytest.mark.asyncio |
| 157 | +async def test_sync_exception_capture(asgi_app): |
| 158 | + """ |
| 159 | + Test that middleware handles exceptions from sync views. |
| 160 | +
|
| 161 | + The middleware's process_exception() method captures view exceptions to PostHog. |
| 162 | + This test verifies the exception causes a 500 response. |
| 163 | + """ |
| 164 | + async with AsyncClient( |
| 165 | + transport=ASGITransport(app=asgi_app), base_url="http://testserver" |
| 166 | + ) as ac: |
| 167 | + response = await ac.get("/test/sync-exception") |
| 168 | + |
| 169 | + # Django returns 500 for unhandled exceptions |
| 170 | + assert response.status_code == 500 |
0 commit comments