|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +import jwt |
| 4 | +import pytest |
| 5 | + |
| 6 | +from core.config import config |
| 7 | +from core.helpers.token import TokenHelper, DecodeTokenException, ExpiredTokenException |
| 8 | +from tests.support.token import EXPIRED_TOKEN |
| 9 | + |
| 10 | + |
| 11 | +@pytest.mark.asyncio |
| 12 | +async def test_encode(): |
| 13 | + # Given |
| 14 | + payload = {"user_id": 1} |
| 15 | + |
| 16 | + # When |
| 17 | + sut = TokenHelper.encode(payload=payload) |
| 18 | + |
| 19 | + # Then |
| 20 | + decoded_token: dict[str, Any] = jwt.decode( |
| 21 | + sut, config.JWT_SECRET_KEY, config.JWT_ALGORITHM |
| 22 | + ) |
| 23 | + assert decoded_token["user_id"] == 1 |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.asyncio |
| 27 | +async def test_decode(): |
| 28 | + # Given |
| 29 | + token = jwt.encode({"user_id": 1}, config.JWT_SECRET_KEY, config.JWT_ALGORITHM) |
| 30 | + |
| 31 | + # When |
| 32 | + sut = TokenHelper.decode(token=token) |
| 33 | + |
| 34 | + # Then |
| 35 | + assert sut == {"user_id": 1} |
| 36 | + |
| 37 | + |
| 38 | +@pytest.mark.asyncio |
| 39 | +async def test_decode_expired_decode_error(): |
| 40 | + # Given |
| 41 | + token = "invalid" |
| 42 | + |
| 43 | + # When, Then |
| 44 | + with pytest.raises(DecodeTokenException): |
| 45 | + TokenHelper.decode(token=token) |
| 46 | + |
| 47 | + |
| 48 | +@pytest.mark.asyncio |
| 49 | +async def test_decode_expired_signature_error(): |
| 50 | + # Given |
| 51 | + token = EXPIRED_TOKEN |
| 52 | + |
| 53 | + # When, Then |
| 54 | + with pytest.raises(ExpiredTokenException): |
| 55 | + TokenHelper.decode(token=token) |
| 56 | + |
| 57 | + |
| 58 | +@pytest.mark.asyncio |
| 59 | +async def test_decode_expired_token(): |
| 60 | + # Given |
| 61 | + token = EXPIRED_TOKEN |
| 62 | + |
| 63 | + # When |
| 64 | + sut: dict[str, Any] = TokenHelper.decode_expired_token(token=token) |
| 65 | + |
| 66 | + # Then |
| 67 | + assert sut["user_id"] == 1 |
| 68 | + |
| 69 | + |
| 70 | +@pytest.mark.asyncio |
| 71 | +async def test_decode_expired_token_decode_error(): |
| 72 | + # Given |
| 73 | + token = "invalid" |
| 74 | + |
| 75 | + # When, Then |
| 76 | + with pytest.raises(DecodeTokenException): |
| 77 | + TokenHelper.decode_expired_token(token=token) |
0 commit comments