Skip to content

Commit

Permalink
Fix unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wawanbreton committed Sep 26, 2024
1 parent 3199437 commit 57cd7a9
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 20 deletions.
4 changes: 2 additions & 2 deletions tests/API/TestAccount.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
account._onLoginStateChanged(True, "BLARG!")
# 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"):
account._onLoginStateChanged(True)
account._onLoginStateChanged(False, "OMGZOMG!")
account.loginStateChanged.emit.called_with(False)
account.loginStateChanged.emit.assert_called_with(False)

def test_sync_success():
account = Account(MagicMock())
Expand Down
5 changes: 3 additions & 2 deletions tests/Settings/TestCuraStackBuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ def quality_changes_container():
def test_createMachineWithUnknownDefinition(application, container_registry):
application.getContainerRegistry = MagicMock(return_value=container_registry)
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 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,
Expand Down
41 changes: 25 additions & 16 deletions tests/TestOAuth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from datetime import datetime
from unittest.mock import MagicMock, Mock, patch
from pytest import fixture

from PyQt6.QtGui import QDesktopServices
from PyQt6.QtNetwork import QNetworkReply
Expand Down Expand Up @@ -59,6 +60,17 @@
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:
"""
Ensure that when setting up an AuthorizationService, no data is set.
Expand All @@ -72,18 +84,20 @@ def test_cleanAuthService() -> None:

assert authorization_service.getAccessToken() is None

def test_refreshAccessTokenSuccess():
def test_refreshAccessTokenSuccess(http_request_manager):
authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
authorization_service.initialize()
with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()):
authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
authorization_service.onAuthStateChanged.emit = MagicMock()

with patch.object(AuthorizationHelpers, "getAccessTokenUsingRefreshToken", return_value=SUCCESSFUL_AUTH_RESPONSE):
authorization_service.refreshAccessToken()
assert authorization_service.onAuthStateChanged.emit.called_with(True)
with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value=http_request_manager)):
with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()):
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.
Expand All @@ -94,13 +108,8 @@ def test__parseJWTNoRefreshToken():
authorization_service._storeAuthData(NO_REFRESH_AUTH_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)
mock_callback.assert_called_once()
profile_reply = mock_callback.call_args_list[0][0][0]
Expand Down Expand Up @@ -175,9 +184,10 @@ def test_refreshAccessTokenFailed():
"""
authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
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.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()
Expand All @@ -187,10 +197,9 @@ def mock_refresh(self, refresh_token, callback): # Refreshing gives a valid tok
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)):
authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
authorization_service.onAuthStateChanged.emit = MagicMock()
with patch("cura.OAuth2.AuthorizationHelpers.AuthorizationHelpers.getAccessTokenUsingRefreshToken", mock_refresh):
with patch("cura.OAuth2.AuthorizationHelpers.AuthorizationHelpers.getAccessTokenUsingRefreshToken", side_effect=lambda refresh_token, callback: callback(FAILED_AUTH_RESPONSE)):
authorization_service.refreshAccessToken()
assert authorization_service.onAuthStateChanged.emit.called_with(False)
authorization_service.onAuthStateChanged.emit.assert_called_with(logged_in = False)

def test_refreshAccesTokenWithoutData():
authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
Expand Down

0 comments on commit 57cd7a9

Please sign in to comment.