Skip to content

Commit 439c905

Browse files
committed
Add TokenHelper test codes
1 parent 171c313 commit 439c905

2 files changed

Lines changed: 79 additions & 0 deletions

File tree

tests/core/helpers/test_token.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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)

tests/support/token.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
INVALID_REFRESH_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoxfQ.VF_eJEtfxZ9PEOqWunr26x0jF2n0o2dyKpmMwisIISY"
22

33
USER_ID_1_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJyZWZyZXNoIiwidXNlcl9pZCI6MX0.p3PLbILjOq4-i2OmkH2uARu6UQun01dxPArSribeQ8w"
4+
5+
EXPIRED_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjEzNDU0NDYwNzJ9.3GaF7JKtagEsnUXlujCF_3KFJvNXPpP18G5quV4C0Go"

0 commit comments

Comments
 (0)