-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathtest_authorized.py
More file actions
66 lines (52 loc) · 2.59 KB
/
Copy pathtest_authorized.py
File metadata and controls
66 lines (52 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Unit tests for the /authorized REST API endpoint."""
import pytest
from fastapi import HTTPException
from starlette.datastructures import Headers
from app.endpoints.authorized import authorized_endpoint_handler
from authentication.utils import extract_user_token
MOCK_AUTH = ("test-id", "test-user", True, "token")
@pytest.mark.asyncio
async def test_authorized_endpoint() -> None:
"""Test the authorized endpoint handler."""
response = await authorized_endpoint_handler(auth=MOCK_AUTH)
assert response.model_dump() == {
"user_id": "test-id",
"username": "test-user",
"skip_userid_check": True,
}
@pytest.mark.asyncio
async def test_authorized_unauthorized() -> None:
"""Test the authorized endpoint handler behavior under unauthorized conditions.
Note: In real scenarios, FastAPI's dependency injection would prevent the handler
from being called if auth fails. This test simulates what would happen if somehow
invalid auth data reached the handler.
"""
# Test scenario 1: None auth data (complete auth failure)
with pytest.raises(TypeError):
# This would occur if auth dependency somehow returned None
await authorized_endpoint_handler(
auth=None # pyright:ignore[reportArgumentType]
)
# Test scenario 2: Invalid auth tuple structure
with pytest.raises(ValueError):
# This would occur if auth dependency returned malformed data
await authorized_endpoint_handler(
auth=("incomplete-auth-data",) # pyright:ignore[reportArgumentType]
)
@pytest.mark.asyncio
async def test_authorized_dependency_unauthorized() -> None:
"""Test that auth dependency raises HTTPException with 403 for unauthorized access."""
# Test the auth utility function that would be called by auth dependencies
# This simulates the unauthorized scenario that would prevent the handler from being called
# Test case 1: No Authorization header (400 error from extract_user_token)
headers_no_auth = Headers({})
with pytest.raises(HTTPException) as exc_info:
extract_user_token(headers_no_auth)
assert exc_info.value.status_code == 401
assert exc_info.value.detail == "No Authorization header found"
# Test case 2: Invalid Authorization header format (400 error from extract_user_token)
headers_invalid_auth = Headers({"Authorization": "InvalidFormat"})
with pytest.raises(HTTPException) as exc_info:
extract_user_token(headers_invalid_auth)
assert exc_info.value.status_code == 401
assert exc_info.value.detail == "No token found in Authorization header"