/
test_token_manager.py
91 lines (75 loc) · 2.86 KB
/
test_token_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""Test asyncpraw.util.refresh_token_manager."""
import aiofiles
import pytest
from asynctest import mock
from asyncpraw.util.token_manager import BaseTokenManager, FileTokenManager
from .. import UnitTest
from ..test_reddit import DummyTokenManager
class DummyAuthorizer:
def __init__(self, refresh_token):
self.refresh_token = refresh_token
class TestBaseTokenManager(UnitTest):
def test_init_base_fail(self):
with pytest.raises(TypeError):
BaseTokenManager()
def test_reddit(self):
manager = DummyTokenManager()
manager.reddit = "dummy"
assert manager.reddit == "dummy"
def test_reddit__must_only_be_set_once(self):
manager = DummyTokenManager()
manager.reddit = "dummy"
with pytest.raises(RuntimeError) as excinfo:
manager.reddit = None
assert (
str(excinfo.value)
== "``reddit`` can only be set once and is done automatically"
)
class TestFileTokenManager(UnitTest):
def setUp(self):
aiofiles.threadpool.wrap.register(mock.MagicMock)(
lambda *args, **kwargs: aiofiles.threadpool.AsyncBufferedIOBase(
*args, **kwargs
)
)
super(TestFileTokenManager, self).setUp()
async def test_post_refresh_token_callback__writes_to_file(self):
authorizer = DummyAuthorizer("token_value")
manager = FileTokenManager("mock/dummy_path")
mock_file = mock.MagicMock()
with mock.patch(
"aiofiles.threadpool.sync_open", return_value=mock_file
) as mock_open:
await manager.post_refresh_callback(authorizer)
assert authorizer.refresh_token == "token_value"
mock_open.assert_called_once_with(
"mock/dummy_path",
mode="w",
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
)
mock_open().write.assert_called_once_with("token_value")
async def test_pre_refresh_token_callback__reads_from_file(self):
authorizer = DummyAuthorizer(None)
manager = FileTokenManager("mock/dummy_path")
mock_file = mock.MagicMock()
mock_file.read = mock.MagicMock(return_value="token_value\n")
with mock.patch(
"aiofiles.threadpool.sync_open", return_value=mock_file
) as mock_open:
await manager.pre_refresh_callback(authorizer)
assert authorizer.refresh_token == "token_value"
mock_open.assert_called_once_with(
"mock/dummy_path",
mode="r",
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
)