Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pytest
- from auth.utils import verify_password, get_hashed_password, create_access_token, get_user, get_current_user, password_context
- from auth.models import User
- from fastapi import HTTPException
- from jose import jwt, JWTError
- import asyncio
- # Klasa pomocnicza do symulacji sesji DB
- class FakeDBSession:
- def __init__(self, user=None):
- self.user = user
- def query(self, model):
- return self
- def filter(self, *args, **kwargs):
- return self
- def first(self):
- return self.user
- class FakeCredentials:
- def __init__(self, credentials):
- self.credentials = credentials
- # Funkcja do symulowania jwt.decode bez użycia MagicMock
- def fake_jwt_decode(token, key, algorithms):
- if token == "valid_token":
- return {"sub": "123"}
- else:
- raise JWTError("Token is invalid")
- @pytest.fixture
- def test_user():
- user_data = {
- "id": "123",
- "username": "testuser",
- "hashed_password": get_hashed_password("test123"),
- "is_active": True,
- "role": "user"
- }
- return User(**user_data)
- def test_get_hashed_password():
- test_password = "superSecret123"
- hashed_password = get_hashed_password(test_password)
- assert password_context.verify(test_password, hashed_password), "The hashed password does not match the original password."
- def test_get_user_found(test_user):
- user_id = "123"
- fake_db = FakeDBSession(user=test_user)
- user = get_user(user_id, fake_db)
- assert user.id == user_id
- def test_get_user_not_found():
- fake_db = FakeDBSession()
- with pytest.raises(HTTPException) as exc_info:
- get_user("not_existing_id", fake_db)
- assert exc_info.value.status_code == 404
- @pytest.mark.asyncio
- async def test_get_current_user_success(test_user, monkeypatch):
- def fake_jwt_decode(token, key, algorithms):
- return {"sub": test_user.id}
- monkeypatch.setattr("jose.jwt.decode", fake_jwt_decode)
- fake_db = FakeDBSession(user=test_user)
- mock_credentials = FakeCredentials(credentials="valid_token")
- result_user = await get_current_user(credentials=mock_credentials, db=fake_db)
- assert result_user == test_user
- @pytest.mark.asyncio
- async def test_get_current_user_invalid_token(monkeypatch):
- def fake_jwt_decode(token, key, algorithms):
- raise JWTError("Token is invalid")
- monkeypatch.setattr("jose.jwt.decode", fake_jwt_decode)
- fake_db = FakeDBSession()
- mock_credentials = FakeCredentials(credentials="invalid_token")
- with pytest.raises(HTTPException) as exc_info:
- await get_current_user(credentials=mock_credentials, db=fake_db)
- assert exc_info.value.status_code == 401
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement