|
| 1 | +import pytest |
| 2 | +import jwt |
| 3 | +from starlette.responses import JSONResponse |
| 4 | + |
| 5 | +from app.auth.controllers.create_token import create_token, JWT_SECRET_KEY, JWT_ALGORITHM |
| 6 | +from app.auth.models.token_request import TokenRequest |
| 7 | +from app.auth.models.token_response import TokenResponse |
| 8 | +from app.user.models.user_status_enum import UserStatusEnum |
| 9 | +from app.user.models.verification_status_enum import VerificationStatusEnum |
| 10 | + |
| 11 | + |
| 12 | +@pytest.mark.asyncio |
| 13 | +async def test_create_token_success(monkeypatch): |
| 14 | + monkeypatch.setenv("JWT_SECRET_KEY", "test_secret") |
| 15 | + |
| 16 | + class DummyUser: |
| 17 | + id = "507f1f77bcf86cd799439011" |
| 18 | + name = "John" |
| 19 | + type = "admin" |
| 20 | + verification_status = VerificationStatusEnum.VERIFIED.value |
| 21 | + status = UserStatusEnum.ACTIVE.value |
| 22 | + def verify_credential(self, cred): |
| 23 | + return True |
| 24 | + |
| 25 | + async def mock_find_one(_query): |
| 26 | + return DummyUser() |
| 27 | + |
| 28 | + async def mock_project_get(_id): |
| 29 | + return None |
| 30 | + |
| 31 | + class MockUser: |
| 32 | + identifier = "identifier" |
| 33 | + find_one = staticmethod(mock_find_one) |
| 34 | + |
| 35 | + class MockProject: |
| 36 | + get = staticmethod(mock_project_get) |
| 37 | + |
| 38 | + monkeypatch.setattr("app.auth.controllers.create_token.User", MockUser) |
| 39 | + monkeypatch.setattr("app.auth.controllers.create_token.Project", MockProject) |
| 40 | + |
| 41 | + req = TokenRequest(identifier="user", credential="pass", project=None, satellites=None) |
| 42 | + res = await create_token(req, "req-id") |
| 43 | + |
| 44 | + assert isinstance(res, TokenResponse) |
| 45 | + decoded = jwt.decode(res.access_token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM]) |
| 46 | + assert decoded["user_id"] == "507f1f77bcf86cd799439011" |
| 47 | + assert decoded["token_type"] == "access" |
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.asyncio |
| 51 | +async def test_create_token_invalid_user(monkeypatch): |
| 52 | + async def mock_find_one(_query): |
| 53 | + return None |
| 54 | + |
| 55 | + class MockUser: |
| 56 | + identifier = "identifier" |
| 57 | + find_one = staticmethod(mock_find_one) |
| 58 | + |
| 59 | + monkeypatch.setattr("app.auth.controllers.create_token.User", MockUser) |
| 60 | + |
| 61 | + req = TokenRequest(identifier="bad", credential="pass", project=None, satellites=None) |
| 62 | + res = await create_token(req, "req-id") |
| 63 | + |
| 64 | + assert isinstance(res, JSONResponse) |
| 65 | + assert res.status_code == 404 |
0 commit comments