From 764058f4eba6ec95978251dc484ac3816ff0fb89 Mon Sep 17 00:00:00 2001 From: Rudolf Braun <48672663+BraunRudolf@users.noreply.github.com> Date: Wed, 9 Oct 2024 08:56:18 +0200 Subject: [PATCH] Add Test + Fixtures test+fixtures successful login_for_access_token --- backend-app/tests/unit/conftest.py | 12 ++++++++++- backend-app/tests/unit/test_auth.py | 33 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/backend-app/tests/unit/conftest.py b/backend-app/tests/unit/conftest.py index 0110bcf1..0bba690a 100644 --- a/backend-app/tests/unit/conftest.py +++ b/backend-app/tests/unit/conftest.py @@ -1,5 +1,5 @@ from io import BytesIO -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock import pandas as pd import pytest @@ -319,3 +319,13 @@ def valid_token(valid_token_payload): def mock_jwt_decode(valid_token_payload): """Mock jwt.decode to return a valid payload.""" return MagicMock(return_value=valid_token_payload) + + +@pytest.fixture +def mock_authenticate_user(mock_get_user_by_email_success): + return MagicMock(return_value=mock_get_user_by_email_success) + + +@pytest.fixture +def mock_create_access_token_valid_token(valid_token): + return MagicMock(return_value=valid_token) diff --git a/backend-app/tests/unit/test_auth.py b/backend-app/tests/unit/test_auth.py index f8dd4d65..f523d2e3 100644 --- a/backend-app/tests/unit/test_auth.py +++ b/backend-app/tests/unit/test_auth.py @@ -280,3 +280,36 @@ def test_health_check_wrong_url(client): # Wrong URL response = client.get("/wrong-url") assert response.status_code == 404 # Not Found + + +def test_successful_login( + client, + mock_authenticate_user, + mock_create_access_token_valid_token, + valid_token, + db, + monkeypatch, +): + + monkeypatch.setattr("app.api.auth.authenticate_user", mock_authenticate_user) + monkeypatch.setattr("app.api.auth.create_access_token", mock_create_access_token_valid_token) + + # Prepare the data as if it is coming from OAuth2PasswordRequestForm + login_data = {"username": "user1@example.com", "password": "test1fake_hash"} + + # Send a POST request to the /token endpoint + response = client.post("/token", data=login_data) + + # Assert that the status code is 200 OK + assert response.status_code == 200 + + # Assert that the response JSON contains the correct token + expected_response = { + "access_token": valid_token, + "token_type": "bearer", + "message": "Welcome!", + } + assert response.json() == expected_response + + # # Ensure the authenticate_user was called with correct arguments + mock_authenticate_user.assert_called_once_with("user1@example.com", "test1fake_hash", db=db)