"""Tests for the owsusers model.""" from unittest import mock import pytest from owsrequest import request as requests from requests.models import HTTPError, Response from permissions.models import owsusers from permissions.types import AdminIdentity, ProfileInfo def test_get_auth0_user_organizations(monkeypatch): """Test get_auth0_user_organizations.""" auth0_user_id = '99143f6bac789b006a2e3cb4' ows_users_response = Response() ows_users_response.status_code = 200 admin = AdminIdentity( id='555df6b6-661b-4d5b-bc0f-df83cf46eb75', first_name='Test', last_name='Test', name='Test Test', user_types=['label'], email='test@test.com', active='Y', auth0_user_id='auth0|test', settings_profile=ProfileInfo( profile_id=1234, profile_type='SettingsProfile', roles=[], uuid='555df6b6-661b-4d5b-bc0f-df83cf46eb75', ), default_brand='awal', ) ows_users_response.json = mock.MagicMock(return_value=['awal', 'orchard']) monkeypatch.setattr(requests, 'get', mock.MagicMock(return_value=ows_users_response)) result = owsusers.get_auth0_user_organizations(admin=admin, auth0_user_id=auth0_user_id) requests.get.assert_called_once_with( 'ows-users', '/auth0/99143f6bac789b006a2e3cb4/organizations', headers={ 'content-type': 'application/json', 'Orchard-Profile-Id': str(admin.settings_profile.profile_id), 'Orchard-Profile-Type': admin.settings_profile.profile_type, }, ) # check that `orchard` convert to `theorchard` assert result == ['awal', 'theorchard'] @pytest.fixture def admin_identity(): """Return an admin identity.""" return AdminIdentity( id='555df6b6-661b-4d5b-bc0f-df83cf46eb75', first_name='Test', last_name='Test', name='Test Test', user_types=['label'], email='test@test.com', active='Y', auth0_user_id='auth0|test', settings_profile=ProfileInfo( profile_id=1234, profile_type='SettingsProfile', roles=[], uuid='555df6b6-661b-4d5b-bc0f-df83cf46eb75', ), default_brand='awal', ) @pytest.fixture def create_invite_params(admin_identity): """Return params needed to create an auth0 org invite.""" user_metadata = { 'orchardIdentityId': '660adba7-9590-454e-8ae8-498cf71319e4', 'user_types': ['label'], 'username': 'e@ma.il', 'vend_contact_id': 99999, 'type': 'alw', 'inviteTracking': 'abase64encodedstring', 'auth0_user_id': 'auth0 | 660adba7-9590-454e-8ae8-498cf71319e4', } return { 'email': user_metadata['username'], 'brand': 'awal', 'auth0_application_name': 'settings-login', 'admin': admin_identity, 'user_metadata': user_metadata, } @pytest.fixture def create_member_params(admin_identity): """Return params needed to create an auth0 org member.""" return { 'auth0_user_id': 'auth0|660adba7-9590-454e-8ae8-498cf71319e4', 'brand': 'awal', 'admin': admin_identity, } @mock.patch('permissions.models.owsusers.request') def test_create_auth0_org_invite_request_args(request_mock, create_invite_params): """Test that the request to create the auth0 org invite is called with the expected args.""" owsusers.create_auth0_org_invitation(**create_invite_params) request_mock.process.assert_called_with( application='ows-permissions', # Not in the business of testing anyone's environment variables, # though this should really be 'test' environment=mock.ANY, method='POST', service_name='ows-users', path='/auth0/invite/organization-member', json={ 'email': 'e@ma.il', 'brand': 'awal', 'auth0_application_name': 'settings-login', 'admin_name': 'Test Test', 'user_metadata': { 'orchardIdentityId': '660adba7-9590-454e-8ae8-498cf71319e4', 'user_types': ['label'], 'username': 'e@ma.il', 'vend_contact_id': 99999, 'type': 'alw', 'inviteTracking': 'abase64encodedstring', 'auth0_user_id': 'auth0 | 660adba7-9590-454e-8ae8-498cf71319e4', }, }, headers={ 'content-type': 'application/json', 'Orchard-Profile-Id': '1234', 'Orchard-Profile-Type': 'SettingsProfile', 'Orchard-Identity-Id': '555df6b6-661b-4d5b-bc0f-df83cf46eb75', }, ) @mock.patch('permissions.models.owsusers.request') def test_create_auth0_org_invite_error(request_mock, create_invite_params): """Test that an error received when creating the auth0 org invite is re-raised.""" response_mock = mock.Mock(ok=False) request_mock.process.return_value = response_mock owsusers.create_auth0_org_invitation(**create_invite_params) response_mock.raise_for_status.assert_called() @mock.patch('permissions.models.owsusers.request') def test_create_auth0_org_invite_success(request_mock, create_invite_params): """Test a successful request to create an auth0 org invite.""" response_mock = mock.Mock(ok=True) mock_result = mock.Mock() response_mock.json.return_value = mock_result request_mock.process.return_value = response_mock result = owsusers.create_auth0_org_invitation(**create_invite_params) assert result == mock_result def test_create_auth0_org_member_success(mocker, create_member_params): """Test that the request to create the auth0 org member is called with the expected args.""" request_mock = mocker.patch('permissions.models.owsusers.request') owsusers.create_auth0_org_member(**create_member_params) request_mock.post.assert_called_with( service_name='ows-users', path='/auth0/add/organization-members', json={ 'brand': 'awal', 'members': ['auth0|660adba7-9590-454e-8ae8-498cf71319e4'], }, headers={ 'Content-Type': 'application/json', 'Orchard-Profile-Id': '1234', 'Orchard-Profile-Type': 'SettingsProfile', 'Orchard-Identity-Id': '555df6b6-661b-4d5b-bc0f-df83cf46eb75', }, ) @pytest.mark.parametrize( 'input_brand,expected_brand', [ ('awal', 'awal'), # PROFILE_BRANDS passthrough ('knr', 'knr'), # PROFILE_BRANDS passthrough ('theorchard', 'theorchard'), # PROFILE_BRANDS passthrough ('sme', 'sme'), # PROFILE_BRANDS passthrough ('foundation', 'sme'), # SME_BRANDS → sme ('orchard', 'theorchard'), # unknown → theorchard ('drm', 'theorchard'), # unknown → theorchard ], ) def test_create_auth0_org_member_maps_brand(mocker, admin_identity, input_brand, expected_brand): """Test that the brand is mapped through default_brand_from_brand before sending.""" request_mock = mocker.patch('permissions.models.owsusers.request') owsusers.create_auth0_org_member( brand=input_brand, auth0_user_id='auth0|abc123', admin=admin_identity, ) payload = request_mock.post.call_args.kwargs['json'] assert payload['brand'] == expected_brand def test_create_auth0_org_member_error(mocker, create_member_params): """Test that an error received when creating the auth0 org member is re-raised.""" mocker.patch( 'permissions.models.owsusers.request', mock.Mock( post=mock.Mock( return_value=mock.MagicMock(raise_for_status=mock.Mock(side_effect=HTTPError)) ) ), ) with pytest.raises(HTTPError): owsusers.create_auth0_org_member(**create_member_params) @mock.patch('permissions.models.owsusers.request') def test_set_auth0_vend_contact_id_error(request_mock): """Test that an error received when setting auth0 vend_contact_id is re-raised.""" response_mock = mock.Mock(ok=False) request_mock.process.return_value = response_mock owsusers.set_auth0_vend_contact_id( vend_contact_id=1331011, auth0_user_id='6abe8ab98c', identity_id='i-am-a-uuid', admin_id='im-a-different-uuid', admin_profile_id=29599, ) response_mock.raise_for_status.assert_called() @mock.patch('permissions.models.owsusers.request') def test_set_auth0_vend_contact_id_success(request_mock): """Test a successful request to set primary vend_contact.""" params = { 'vend_contact_id': 1331011, 'auth0_user_id': '60abe08ab98c', 'identity_id': 'i-am-a-uuid', 'admin_id': 'im-a-different-uuid', 'admin_profile_id': 29599, } owsusers.set_auth0_vend_contact_id(**params) request_mock.process.assert_called_with( application='ows-permissions', environment=mock.ANY, method='PUT', service_name='ows-users', path=f'/users/auth0/{params["auth0_user_id"]}/primary', json={'user_id': params['vend_contact_id'], 'identity_id': params['identity_id']}, headers={ 'content-type': 'application/json', 'Orchard-Profile-Id': str(params['admin_profile_id']), 'Orchard-Profile-Type': 'SettingsProfile', 'Orchard-Identity-Id': params['admin_id'], }, ) @mock.patch('permissions.models.owsusers.request') def test_get_auth0_user_success(request_mock): """Test a successful request to get auth0 user.""" auth0_user_id = 'auth0|123456' mock_response_data = { 'user_id': auth0_user_id, 'email': 'test@example.com', 'user_metadata': { 'defaultBrand': 'theorchard', }, } response_mock = mock.Mock(ok=True) response_mock.json.return_value = mock_response_data request_mock.process.return_value = response_mock result = owsusers.get_auth0_user(auth0_user_id) request_mock.process.assert_called_once_with( application='ows-permissions', environment=mock.ANY, method='GET', service_name='ows-users', path=f'/auth0/users/{auth0_user_id}', ) assert result.user_metadata.defaultBrand == 'theorchard' @mock.patch('permissions.models.owsusers.request') def test_get_auth0_user_no_default_brand(request_mock): """Test get auth0 user when defaultBrand is not present.""" auth0_user_id = 'auth0|123456' mock_response_data = { 'user_id': auth0_user_id, 'email': 'test@example.com', 'user_metadata': {}, } response_mock = mock.Mock(ok=True) response_mock.json.return_value = mock_response_data request_mock.process.return_value = response_mock result = owsusers.get_auth0_user(auth0_user_id) assert result.user_metadata.defaultBrand is None @mock.patch('permissions.models.owsusers.request') def test_get_auth0_user_error(request_mock): """Test that an error received when getting auth0 user is re-raised.""" response_mock = mock.Mock(ok=False) request_mock.process.return_value = response_mock owsusers.get_auth0_user('auth0|123456') response_mock.raise_for_status.assert_called()