Debian Codegraph @

tests/test_csrf_async.py

raw symbols SCIP
1 import pytest
2 from django.conf import settings
3
4 from ninja import NinjaAPI
5 from ninja.security import APIKeyCookie
6 from ninja.testing import TestAsyncClient as BaseTestAsyncClient
7
8
9 class AnyCookieAuth(APIKeyCookie):
10 """A mock authentication class that accepts any cookie value.
11 To test CSRF functionality without specific authentication logic.
12 """
13
14 def authenticate(self, request, key):
15 return True
16
17
18 class TestAsyncClient(BaseTestAsyncClient):
19 """Custom TestClient that forces CSRF checks"""
20
21 def _build_request(self, *args, **kwargs):
22 request = super()._build_request(*args, **kwargs)
23 request._dont_enforce_csrf_checks = False
24 return request
25
26
27 TOKEN = "1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD"
28 COOKIES = {settings.CSRF_COOKIE_NAME: TOKEN}
29
30
31 @pytest.mark.asyncio
32 async def test_csrf_off():
33 csrf_OFF = NinjaAPI(urls_namespace="csrf_OFF")
34
35 @csrf_OFF.post("/post")
36 async def post_off(request):
37 return {"success": True}
38
39 client = TestAsyncClient(csrf_OFF)
40 response = await client.post("/post", COOKIES=COOKIES)
41 assert response.status_code == 200
42
43
44 @pytest.mark.asyncio
45 async def test_csrf_on():
46 csrf_ON = NinjaAPI(urls_namespace="csrf_ON", auth=AnyCookieAuth())
47
48 @csrf_ON.post("/post")
49 async def post_on(request):
50 return {"success": True}
51
52 client = TestAsyncClient(csrf_ON)
53
54 response = await client.post("/post", COOKIES=COOKIES)
55 assert response.status_code == 403
56
57 # check with token in formdata
58 response = await client.post(
59 "/post", {"csrfmiddlewaretoken": TOKEN}, COOKIES=COOKIES
60 )
61 assert response.status_code == 200
62
63 # check with headers
64 response = await client.post(
65 "/post", COOKIES=COOKIES, headers={"X-CSRFTOKEN": TOKEN}
66 )
67 assert response.status_code == 200
68
69
70 @pytest.mark.asyncio
71 async def test_csrf_exempt_async():
72 """Test that csrf_exempt functionality works with async operations"""
73 csrf_ON = NinjaAPI(urls_namespace="csrf_exempt_async", auth=AnyCookieAuth())
74
75 # Define the async function and manually set csrf_exempt attribute
76 async def post_on_with_exempt(request):
77 return {"success": True}
78
79 # Manually set the csrf_exempt attribute (simulating what @csrf_exempt would do)
80 post_on_with_exempt.csrf_exempt = True
81
82 # Register with the API
83 csrf_ON.post("/post/csrf_exempt")(post_on_with_exempt)
84
85 client = TestAsyncClient(csrf_ON)
86
87 # This should succeed even without CSRF token because of csrf_exempt attribute
88 response = await client.post("/post/csrf_exempt", COOKIES=COOKIES)
89 assert response.status_code == 200