1
0
Fork 0
mirror of synced 2024-06-26 10:00:20 +12:00
bulk-downloader-for-reddit/tests/test_oauth2.py

72 lines
2.3 KiB
Python
Raw Normal View History

2021-03-08 14:37:01 +13:00
#!/usr/bin/env python3
# coding=utf-8
import configparser
2021-03-09 22:32:51 +13:00
from pathlib import Path
2021-03-08 14:37:01 +13:00
from unittest.mock import MagicMock
import pytest
2021-04-12 19:58:32 +12:00
from bdfr.exceptions import BulkDownloaderException
from bdfr.oauth2 import OAuth2Authenticator, OAuth2TokenManager
2021-03-08 14:37:01 +13:00
@pytest.fixture()
def example_config() -> configparser.ConfigParser:
out = configparser.ConfigParser()
config_dict = {'DEFAULT': {'user_token': 'example'}}
out.read_dict(config_dict)
return out
@pytest.mark.online
@pytest.mark.parametrize('test_scopes', (
{'history', },
{'history', 'creddits'},
{'account', 'flair'},
{'*', },
2021-03-08 14:37:01 +13:00
))
def test_check_scopes(test_scopes: set[str]):
2021-03-08 14:37:01 +13:00
OAuth2Authenticator._check_scopes(test_scopes)
2021-03-08 15:34:03 +13:00
@pytest.mark.parametrize(('test_scopes', 'expected'), (
('history', {'history', }),
('history creddits', {'history', 'creddits'}),
('history, creddits, account', {'history', 'creddits', 'account'}),
('history,creddits,account,flair', {'history', 'creddits', 'account', 'flair'}),
))
def test_split_scopes(test_scopes: str, expected: set[str]):
result = OAuth2Authenticator.split_scopes(test_scopes)
assert result == expected
2021-03-08 14:37:01 +13:00
@pytest.mark.online
@pytest.mark.parametrize('test_scopes', (
2021-03-09 22:32:51 +13:00
{'random', },
{'scope', 'another_scope'},
2021-03-08 14:37:01 +13:00
))
2021-03-09 22:32:51 +13:00
def test_check_scopes_bad(test_scopes: set[str]):
2021-03-08 14:37:01 +13:00
with pytest.raises(BulkDownloaderException):
OAuth2Authenticator._check_scopes(test_scopes)
def test_token_manager_read(example_config: configparser.ConfigParser):
mock_authoriser = MagicMock()
mock_authoriser.refresh_token = None
test_manager = OAuth2TokenManager(example_config, MagicMock())
2021-03-08 14:37:01 +13:00
test_manager.pre_refresh_callback(mock_authoriser)
assert mock_authoriser.refresh_token == example_config.get('DEFAULT', 'user_token')
2021-03-09 22:32:51 +13:00
def test_token_manager_write(example_config: configparser.ConfigParser, tmp_path: Path):
test_path = tmp_path / 'test.cfg'
2021-03-08 14:37:01 +13:00
mock_authoriser = MagicMock()
mock_authoriser.refresh_token = 'changed_token'
2021-03-09 22:32:51 +13:00
test_manager = OAuth2TokenManager(example_config, test_path)
2021-03-08 14:37:01 +13:00
test_manager.post_refresh_callback(mock_authoriser)
assert example_config.get('DEFAULT', 'user_token') == 'changed_token'
with test_path.open('r') as file:
2021-03-09 22:32:51 +13:00
file_contents = file.read()
assert 'user_token = changed_token' in file_contents