test_oauth2.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python3
  2. # coding=utf-8
  3. import configparser
  4. from pathlib import Path
  5. from unittest.mock import MagicMock
  6. import pytest
  7. from bdfr.exceptions import BulkDownloaderException
  8. from bdfr.oauth2 import OAuth2Authenticator, OAuth2TokenManager
  9. @pytest.fixture()
  10. def example_config() -> configparser.ConfigParser:
  11. out = configparser.ConfigParser()
  12. config_dict = {'DEFAULT': {'user_token': 'example'}}
  13. out.read_dict(config_dict)
  14. return out
  15. @pytest.mark.online
  16. @pytest.mark.parametrize('test_scopes', (
  17. {'history', },
  18. {'history', 'creddits'},
  19. {'account', 'flair'},
  20. {'*', },
  21. ))
  22. def test_check_scopes(test_scopes: set[str]):
  23. OAuth2Authenticator._check_scopes(test_scopes)
  24. @pytest.mark.parametrize(('test_scopes', 'expected'), (
  25. ('history', {'history', }),
  26. ('history creddits', {'history', 'creddits'}),
  27. ('history, creddits, account', {'history', 'creddits', 'account'}),
  28. ('history,creddits,account,flair', {'history', 'creddits', 'account', 'flair'}),
  29. ))
  30. def test_split_scopes(test_scopes: str, expected: set[str]):
  31. result = OAuth2Authenticator.split_scopes(test_scopes)
  32. assert result == expected
  33. @pytest.mark.online
  34. @pytest.mark.parametrize('test_scopes', (
  35. {'random', },
  36. {'scope', 'another_scope'},
  37. ))
  38. def test_check_scopes_bad(test_scopes: set[str]):
  39. with pytest.raises(BulkDownloaderException):
  40. OAuth2Authenticator._check_scopes(test_scopes)
  41. def test_token_manager_read(example_config: configparser.ConfigParser):
  42. mock_authoriser = MagicMock()
  43. mock_authoriser.refresh_token = None
  44. test_manager = OAuth2TokenManager(example_config, MagicMock())
  45. test_manager.pre_refresh_callback(mock_authoriser)
  46. assert mock_authoriser.refresh_token == example_config.get('DEFAULT', 'user_token')
  47. def test_token_manager_write(example_config: configparser.ConfigParser, tmp_path: Path):
  48. test_path = tmp_path / 'test.cfg'
  49. mock_authoriser = MagicMock()
  50. mock_authoriser.refresh_token = 'changed_token'
  51. test_manager = OAuth2TokenManager(example_config, test_path)
  52. test_manager.post_refresh_callback(mock_authoriser)
  53. assert example_config.get('DEFAULT', 'user_token') == 'changed_token'
  54. with open(test_path, 'r') as file:
  55. file_contents = file.read()
  56. assert 'user_token = changed_token' in file_contents