Advertisement
SportyScripter

#DLDTest

Mar 27th, 2024
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.67 KB | None | 0 0
  1. from auth.utils import (
  2. get_hashed_password,
  3. password_context)
  4. import unittest
  5. import pytest
  6. import asyncio
  7. from unittest.mock import Mock, patch , MagicMock
  8. from fastapi import HTTPException, status
  9. from auth.utils import verify_password, get_hashed_password, create_access_token, get_user, get_current_user
  10. from db.session import SessionLocal
  11. from auth.models import User
  12. from sqlalchemy.orm import Session
  13. from jose import JWTError
  14.  
  15. def test_get_hashed_password():
  16.     test_password = "superSecret123"
  17.     hashed_password = get_hashed_password(test_password)
  18.     assert password_context.verify(test_password, hashed_password), "The hashed password does not match the original password."
  19.  
  20. user_data = {
  21.     "id": "123",
  22.     "username": "testuser",
  23.     "email": "[email protected]",
  24.     "hashed_password": get_hashed_password("test123"),
  25.     "is_active": True,
  26.     "role": "user"
  27. }
  28.  
  29. @pytest.fixture
  30. def test_user():
  31.     return User(**user_data)
  32.  
  33. @pytest.fixture
  34. def db_session_mock(test_user):
  35.     db_session = MagicMock()
  36.     db_session.query.return_value.filter.return_value.first.return_value = test_user
  37.     return db_session
  38.  
  39. @pytest.fixture
  40. def credentials():
  41.     return Mock(credentials="mocked_token")
  42.  
  43. def test_verify_password():
  44.     password = "test123"
  45.     hashed_password = get_hashed_password(password)
  46.     assert verify_password(password, hashed_password) == True
  47.     assert verify_password("wrongpassword", hashed_password) == False
  48.  
  49. def test_create_access_token():
  50.     token = create_access_token("user_id")
  51.     assert isinstance(token, str) and len(token) > 0
  52.  
  53.  
  54. def test_get_user_found(db_session_mock):
  55.     user_id = "123"
  56.     user = get_user(user_id, db_session_mock)
  57.     assert user.id == user_id
  58.  
  59. def test_get_user_not_found(db_session_mock):
  60.     db_session_mock.query.return_value.filter.return_value.first.return_value = None
  61.     with pytest.raises(HTTPException) as excinfo:
  62.         get_user("not_existing_id", db_session_mock)
  63.     assert excinfo.value.status_code == 404
  64.  
  65.  
  66. @pytest.fixture
  67. def test_user():
  68.     return User(
  69.         id="123",
  70.         username="test_username",
  71.         email="[email protected]",
  72.         hashed_password="fake_hashed_password",
  73.         is_active=True,
  74.         role="user"
  75.     )
  76.  
  77. # Testowanie get_current_user
  78. @pytest.mark.asyncio
  79. async def test_get_current_user_success(mocker, test_user):
  80.     # Mockowanie zależności
  81.     mock_jwt_decode = mocker.patch("jose.jwt.decode", return_value={"sub": test_user.id})
  82.     mock_get_user = mocker.patch("auth.utils.get_user", return_value=test_user)
  83.  
  84.     # Mockowanie zależności HTTPBearer i Depends
  85.     mock_credentials = MagicMock()
  86.     mock_credentials.credentials = "fake_token"
  87.     mock_db_session = MagicMock(spec=Session)
  88.  
  89.     # Wywołanie testowanej funkcji
  90.     result_user = await get_current_user(credentials=mock_credentials, db=mock_db_session)
  91.  
  92.     # Asercje
  93.     assert result_user == test_user
  94.     mock_jwt_decode.assert_called_once()
  95.     mock_get_user.assert_called_once_with(test_user.id, mock_db_session)
  96.  
  97. # Testowanie get_current_user z błędnym tokenem
  98. @pytest.mark.asyncio
  99. @pytest.mark.asyncio
  100. async def test_get_current_user_invalid_token(mocker):
  101.     mocker.patch("jose.jwt.decode", side_effect=JWTError("Token is invalid"))
  102.  
  103.     # Przygotowanie danych wejściowych
  104.     mock_credentials = MagicMock()
  105.     mock_credentials.credentials = "invalid_token"
  106.     mock_db_session = MagicMock(spec=Session)
  107.  
  108.     # Oczekiwanie na wyjątek HTTPException
  109.     with pytest.raises(HTTPException) as exc_info:
  110.         await get_current_user(credentials=mock_credentials, db=mock_db_session)
  111.  
  112.     assert exc_info.value.status_code == 401
  113.  
  114.  
Tags: #test#python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement