|
| 1 | +from types import SimpleNamespace |
| 2 | +from unittest.mock import MagicMock |
| 3 | + |
| 4 | +from flask import Response |
| 5 | +from pytest import fixture |
| 6 | + |
| 7 | +from tests.resource_test_base import ResourceTestBase |
| 8 | + |
| 9 | + |
| 10 | +class TestTokenRefresh(ResourceTestBase): |
| 11 | + module = 'servicex.resources.users.token_refresh' |
| 12 | + endpoint = '/token/refresh' |
| 13 | + fake_token = 'abcd' |
| 14 | + |
| 15 | + @fixture(autouse=True, scope="class") |
| 16 | + def unwrap(self): |
| 17 | + """Remove the @jwt_refresh_token_required decorator.""" |
| 18 | + from servicex.resources.users.token_refresh import TokenRefresh |
| 19 | + TokenRefresh.post = TokenRefresh.post.__wrapped__ |
| 20 | + |
| 21 | + @fixture |
| 22 | + def jwt_funcs(self, mocker) -> SimpleNamespace: |
| 23 | + m = self.module |
| 24 | + patch = mocker.patch |
| 25 | + |
| 26 | + return SimpleNamespace( |
| 27 | + get_jwt_identity=patch(f"{m}.get_jwt_identity", return_value=sub), |
| 28 | + create_access_token=patch(f"{m}.create_access_token", return_value=self.fake_token), |
| 29 | + get_raw_jwt=patch(f"{m}.get_raw_jwt", return_value={"jti": "1234"}), |
| 30 | + decode_token=mocker.patch(f"{m}.decode_token") |
| 31 | + ) |
| 32 | + |
| 33 | + @fixture |
| 34 | + def mock_user(self, mocker) -> MagicMock: |
| 35 | + return mocker.patch(f"{self.module}.UserModel.find_by_sub").return_value |
| 36 | + |
| 37 | + def make_request(self, client): |
| 38 | + response: Response = client.post(self.endpoint) |
| 39 | + assert response.status_code == 200 |
| 40 | + assert response.json == {'access_token': self.fake_token} |
| 41 | + |
| 42 | + def test_post_valid_refresh_token(self, client, jwt_funcs, mock_user): |
| 43 | + jwt_funcs.decode_token.return_value = jwt_funcs.get_raw_jwt.return_value |
| 44 | + self.make_request(client) |
| 45 | + |
| 46 | + def test_post_invalid_refresh_token(self, client, jwt_funcs, mock_user): |
| 47 | + jwt_funcs.decode_token.return_value = {"jti": "this value will not match"} |
| 48 | + response: Response = client.post(self.endpoint) |
| 49 | + assert response.status_code == 401 |
| 50 | + assert response.json == {"message": "Invalid or outdated refresh token"} |
| 51 | + |
| 52 | + def test_post_user_mgmt_disabled(self, jwt_funcs): |
| 53 | + client = self._test_client(extra_config={'DISABLE_USER_MGMT': True}) |
| 54 | + self.make_request(client) |
| 55 | + jwt_funcs.get_jwt_identity.assert_called_once() |
0 commit comments