"""Unit tests for user context utility functions.""" from unittest.mock import MagicMock from flask import request from owsrequest import constants as grass_const import pytest from werkzeug import exceptions from analytics import context from analytics import logic from tests.unit.fixtures import fixture_api app = fixture_api.APP def test_get_current_user(monkeypatch): """Test user creation and obtaining from the context.""" user_id = 10918 with app.test_request_context(): request.headers = { grass_const.GRASS_ACCOUNT_ID: str(user_id), grass_const.GRASS_ACCOUNT_TYPE: 'SUBACCOUNT' } user = context.get_current_user() assert user.id == user_id assert user.type == 'S' user_mock = MagicMock(return_value=MagicMock()) monkeypatch.setattr(logic, 'user', user_mock) user_from_context = context.get_current_user() assert user_from_context == user assert not user_mock.called # Proves that the second time # the user has been taken from the context @pytest.mark.parametrize( 'id, type', [(None, None), ('10918', None), (None, 'SUBACCOUNT'), ('10918', 'UNKNOWN'), ('ID_109@18', 'UNKNOWN'), ] ) def test_get_current_user_negative(id, type): """Test user creation with bad headers.""" with app.test_request_context(): with pytest.raises(exceptions.Forbidden): request.headers = { grass_const.GRASS_ACCOUNT_ID: id, grass_const.GRASS_ACCOUNT_TYPE: type } context.get_current_user()