feat: auto committed
This commit is contained in:
72
services/ai/tests/test_auth.py
Normal file
72
services/ai/tests/test_auth.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""用户上下文提取测试."""
|
||||
|
||||
from src.ai.middleware.auth import UserContext, extract_user_context_from_metadata
|
||||
|
||||
|
||||
class TestUserContext:
|
||||
"""UserContext dataclass 测试."""
|
||||
|
||||
def test_empty_context(self) -> None:
|
||||
"""空上下文."""
|
||||
ctx = UserContext()
|
||||
assert ctx.is_authenticated is False
|
||||
assert ctx.is_empty is True
|
||||
|
||||
def test_authenticated(self) -> None:
|
||||
"""有 user_id 即认证."""
|
||||
ctx = UserContext(user_id="u-1", role="teacher")
|
||||
assert ctx.is_authenticated is True
|
||||
assert ctx.is_empty is False
|
||||
|
||||
def test_only_role_not_authenticated(self) -> None:
|
||||
"""仅有 role 无 user_id 仍非认证."""
|
||||
ctx = UserContext(role="teacher")
|
||||
assert ctx.is_authenticated is False
|
||||
assert ctx.is_empty is False # role 非空故 not empty
|
||||
|
||||
|
||||
class TestExtractFromMetadata:
|
||||
"""gRPC metadata 提取测试."""
|
||||
|
||||
def test_none_metadata(self) -> None:
|
||||
"""None metadata 返回空上下文."""
|
||||
ctx = extract_user_context_from_metadata(None)
|
||||
assert ctx.user_id == ""
|
||||
|
||||
def test_list_metadata(self) -> None:
|
||||
"""list[tuple] 格式 metadata."""
|
||||
metadata = [
|
||||
("x-user-id", "u-123"),
|
||||
("x-user-role", "teacher"),
|
||||
("x-school-id", "s-1"),
|
||||
("x-request-id", "r-1"),
|
||||
]
|
||||
ctx = extract_user_context_from_metadata(metadata)
|
||||
assert ctx.user_id == "u-123"
|
||||
assert ctx.role == "teacher"
|
||||
assert ctx.school_id == "s-1"
|
||||
assert ctx.request_id == "r-1"
|
||||
|
||||
def test_dict_metadata(self) -> None:
|
||||
"""dict 格式 metadata."""
|
||||
metadata = {"x-user-id": "u-456", "x-user-role": "admin"}
|
||||
ctx = extract_user_context_from_metadata(metadata)
|
||||
assert ctx.user_id == "u-456"
|
||||
assert ctx.role == "admin"
|
||||
|
||||
def test_case_insensitive_keys(self) -> None:
|
||||
"""metadata key 大小写不敏感."""
|
||||
metadata = [("X-User-Id", "u-789")]
|
||||
ctx = extract_user_context_from_metadata(metadata)
|
||||
assert ctx.user_id == "u-789"
|
||||
|
||||
def test_non_string_value_in_dict(self) -> None:
|
||||
"""dict 中非字符串值被忽略."""
|
||||
metadata = {"x-user-id": 12345} # type: ignore[dict-item]
|
||||
ctx = extract_user_context_from_metadata(metadata)
|
||||
assert ctx.user_id == ""
|
||||
|
||||
def test_empty_list_metadata(self) -> None:
|
||||
"""空 list metadata."""
|
||||
ctx = extract_user_context_from_metadata([])
|
||||
assert ctx.is_empty is True
|
||||
Reference in New Issue
Block a user