Fix unit tests

This commit is contained in:
Erwan MATHIEU 2024-09-26 09:12:40 +02:00
parent 3199437403
commit 57cd7a99a0
3 changed files with 30 additions and 20 deletions

View File

@ -80,12 +80,12 @@ def test_errorLoginState(application):
with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance"): # Don't want triggers for account information to actually make HTTP requests. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance"): # Don't want triggers for account information to actually make HTTP requests.
account._onLoginStateChanged(True, "BLARG!") account._onLoginStateChanged(True, "BLARG!")
# Even though we said that the login worked, it had an error message, so the login failed. # Even though we said that the login worked, it had an error message, so the login failed.
account.loginStateChanged.emit.called_with(False) account.loginStateChanged.emit.assert_called_with(False)
with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance"): with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance"):
account._onLoginStateChanged(True) account._onLoginStateChanged(True)
account._onLoginStateChanged(False, "OMGZOMG!") account._onLoginStateChanged(False, "OMGZOMG!")
account.loginStateChanged.emit.called_with(False) account.loginStateChanged.emit.assert_called_with(False)
def test_sync_success(): def test_sync_success():
account = Account(MagicMock()) account = Account(MagicMock())

View File

@ -50,9 +50,10 @@ def quality_changes_container():
def test_createMachineWithUnknownDefinition(application, container_registry): def test_createMachineWithUnknownDefinition(application, container_registry):
application.getContainerRegistry = MagicMock(return_value=container_registry) application.getContainerRegistry = MagicMock(return_value=container_registry)
with patch("cura.CuraApplication.CuraApplication.getInstance", MagicMock(return_value=application)): with patch("cura.CuraApplication.CuraApplication.getInstance", MagicMock(return_value=application)):
with patch("UM.ConfigurationErrorMessage.ConfigurationErrorMessage.getInstance") as mocked_config_error: mocked_config_error = MagicMock()
with patch("UM.ConfigurationErrorMessage.ConfigurationErrorMessage.getInstance", MagicMock(return_value=mocked_config_error)):
assert CuraStackBuilder.createMachine("Whatever", "NOPE") is None assert CuraStackBuilder.createMachine("Whatever", "NOPE") is None
assert mocked_config_error.addFaultyContainers.called_with("NOPE") mocked_config_error.addFaultyContainers.assert_called_once_with("NOPE")
def test_createMachine(application, container_registry, definition_container, global_variant, material_instance_container, def test_createMachine(application, container_registry, definition_container, global_variant, material_instance_container,

View File

@ -3,6 +3,7 @@
from datetime import datetime from datetime import datetime
from unittest.mock import MagicMock, Mock, patch from unittest.mock import MagicMock, Mock, patch
from pytest import fixture
from PyQt6.QtGui import QDesktopServices from PyQt6.QtGui import QDesktopServices
from PyQt6.QtNetwork import QNetworkReply from PyQt6.QtNetwork import QNetworkReply
@ -59,6 +60,17 @@ NO_REFRESH_AUTH_RESPONSE = AuthenticationResponse(
MALFORMED_AUTH_RESPONSE = AuthenticationResponse(success=False) MALFORMED_AUTH_RESPONSE = AuthenticationResponse(success=False)
@fixture
def http_request_manager():
mock_reply = Mock() # The user profile that the service should respond with.
mock_reply.error = Mock(return_value=QNetworkReply.NetworkError.NoError)
http_mock = Mock()
http_mock.get = lambda url, headers_dict, callback, error_callback, timeout: callback(mock_reply)
http_mock.readJSON = Mock(return_value={"data": {"user_id": "id_ego_or_superego", "username": "Ghostkeeper"}})
http_mock.setDelayRequests = Mock()
return http_mock
def test_cleanAuthService() -> None: def test_cleanAuthService() -> None:
""" """
Ensure that when setting up an AuthorizationService, no data is set. Ensure that when setting up an AuthorizationService, no data is set.
@ -72,18 +84,20 @@ def test_cleanAuthService() -> None:
assert authorization_service.getAccessToken() is None assert authorization_service.getAccessToken() is None
def test_refreshAccessTokenSuccess(): def test_refreshAccessTokenSuccess(http_request_manager):
authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences()) authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
authorization_service.initialize() authorization_service.initialize()
with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()): with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()):
authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE) authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
authorization_service.onAuthStateChanged.emit = MagicMock() authorization_service.onAuthStateChanged.emit = MagicMock()
with patch.object(AuthorizationHelpers, "getAccessTokenUsingRefreshToken", return_value=SUCCESSFUL_AUTH_RESPONSE): with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value=http_request_manager)):
authorization_service.refreshAccessToken() with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()):
assert authorization_service.onAuthStateChanged.emit.called_with(True) with patch.object(AuthorizationHelpers, "getAccessTokenUsingRefreshToken", side_effect=lambda refresh_token, callback: callback(SUCCESSFUL_AUTH_RESPONSE)):
authorization_service.refreshAccessToken()
authorization_service.onAuthStateChanged.emit.assert_called_once_with(logged_in = True)
def test__parseJWTNoRefreshToken(): def test__parseJWTNoRefreshToken(http_request_manager):
""" """
Tests parsing the user profile if there is no refresh token stored, but there is a normal authentication token. Tests parsing the user profile if there is no refresh token stored, but there is a normal authentication token.
@ -94,13 +108,8 @@ def test__parseJWTNoRefreshToken():
authorization_service._storeAuthData(NO_REFRESH_AUTH_RESPONSE) authorization_service._storeAuthData(NO_REFRESH_AUTH_RESPONSE)
mock_callback = Mock() # To log the final profile response. mock_callback = Mock() # To log the final profile response.
mock_reply = Mock() # The user profile that the service should respond with.
mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.NoError)
http_mock = Mock()
http_mock.get = lambda url, headers_dict, callback, error_callback, timeout: callback(mock_reply)
http_mock.readJSON = Mock(return_value = {"data": {"user_id": "id_ego_or_superego", "username": "Ghostkeeper"}})
with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)): with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_request_manager)):
authorization_service._parseJWT(mock_callback) authorization_service._parseJWT(mock_callback)
mock_callback.assert_called_once() mock_callback.assert_called_once()
profile_reply = mock_callback.call_args_list[0][0][0] profile_reply = mock_callback.call_args_list[0][0][0]
@ -175,9 +184,10 @@ def test_refreshAccessTokenFailed():
""" """
authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences()) authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
authorization_service.initialize() authorization_service.initialize()
with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()):
authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
authorization_service.onAuthStateChanged.emit = MagicMock()
def mock_refresh(self, refresh_token, callback): # Refreshing gives a valid token.
callback(FAILED_AUTH_RESPONSE)
mock_reply = Mock() # The response that the request should give, containing an error about it failing to authenticate. mock_reply = Mock() # The response that the request should give, containing an error about it failing to authenticate.
mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.AuthenticationRequiredError) # The reply is 403: Authentication required, meaning the server responded with a "Can't do that, Dave". mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.AuthenticationRequiredError) # The reply is 403: Authentication required, meaning the server responded with a "Can't do that, Dave".
http_mock = Mock() http_mock = Mock()
@ -187,10 +197,9 @@ def test_refreshAccessTokenFailed():
with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.readJSON", Mock(return_value = {"error_description": "Mock a failed request!"})): with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.readJSON", Mock(return_value = {"error_description": "Mock a failed request!"})):
with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)): with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE) authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
authorization_service.onAuthStateChanged.emit = MagicMock() with patch("cura.OAuth2.AuthorizationHelpers.AuthorizationHelpers.getAccessTokenUsingRefreshToken", side_effect=lambda refresh_token, callback: callback(FAILED_AUTH_RESPONSE)):
with patch("cura.OAuth2.AuthorizationHelpers.AuthorizationHelpers.getAccessTokenUsingRefreshToken", mock_refresh):
authorization_service.refreshAccessToken() authorization_service.refreshAccessToken()
assert authorization_service.onAuthStateChanged.emit.called_with(False) authorization_service.onAuthStateChanged.emit.assert_called_with(logged_in = False)
def test_refreshAccesTokenWithoutData(): def test_refreshAccesTokenWithoutData():
authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences()) authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())