73 lines
2.5 KiB
Python
73 lines
2.5 KiB
Python
import pytest
|
|
import requests
|
|
from aare.gui.auth import auth
|
|
|
|
# pytest-mock provides the 'mocker' fixture, which is a wrapper around the
|
|
# standard unittest.mock. It simplifies mocking by automatically handling
|
|
# cleanup (unpatching) after each test, and providing a more "pytest-native"
|
|
# feel compared to using @patch decorators or context managers.
|
|
|
|
def test_auth_success(mocker):
|
|
"""
|
|
Test successful authentication using pytest-mock's mocker fixture.
|
|
|
|
In standard pytest/unittest, you would typically use:
|
|
with mock.patch('requests.post') as mock_post:
|
|
...
|
|
Or a decorator:
|
|
@patch('requests.post')
|
|
def test_auth(mock_post):
|
|
...
|
|
|
|
pytest-mock allows you to use the 'mocker' fixture directly in the function arguments.
|
|
This avoids deeply nested context managers and makes it easier to mock multiple things.
|
|
"""
|
|
|
|
# We mock 'requests.post' to simulate a successful server response.
|
|
# mocker.patch returns a MagicMock object.
|
|
mock_post = mocker.patch("requests.post")
|
|
|
|
# Configure the mock response
|
|
mock_response = mocker.Mock()
|
|
mock_response.status_code = 200
|
|
mock_response.json.return_value = {"access_token": "fake_token_abc.123.xyz"}
|
|
mock_post.return_value = mock_response
|
|
|
|
# Call the function under test
|
|
token = auth("http://test-server")
|
|
|
|
# Verify the results
|
|
assert token == "fake_token_abc.123.xyz"
|
|
mock_post.assert_called_once()
|
|
|
|
# Check that it was called with the expected URL
|
|
args, kwargs = mock_post.call_args
|
|
assert args[0] == "http://test-server/token"
|
|
|
|
def test_auth_network_failure(mocker):
|
|
"""
|
|
Test authentication failure due to network error using mocker.
|
|
"""
|
|
# Mock requests.post to raise an exception
|
|
mock_post = mocker.patch("requests.post")
|
|
mock_post.side_effect = requests.RequestException("Connection refused")
|
|
|
|
with pytest.raises(RuntimeError) as excinfo:
|
|
auth("http://test-server")
|
|
|
|
assert "Cannot reach AareDAQ server" in str(excinfo.value)
|
|
|
|
def test_auth_no_url_returns_dummy_jwt(mocker):
|
|
"""
|
|
Test that when base_url is None, it returns a dummy JWT without network calls.
|
|
We can use mocker to verify that requests.post was NEVER called.
|
|
"""
|
|
mock_post = mocker.patch("requests.post")
|
|
mocker.patch("os.getlogin", return_value="testuser")
|
|
|
|
token = auth(None)
|
|
|
|
assert isinstance(token, str)
|
|
assert token.count('.') == 2 # Basic JWT structure check
|
|
mock_post.assert_not_called()
|