Skip to content

Commit 93861a1

Browse files
committed
feat: add api keys rotating - add url_builder.py tests
1 parent 2f411ea commit 93861a1

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

aioetherscan/url_builder.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,14 +108,19 @@ def rotate_api_key(self) -> None:
108108
next_api_key = self._get_next_api_key()
109109

110110
self._logger.info(
111-
f'Rotating API key from {self._mask_api_key(prev_api_key)} to {self._mask_api_key(next_api_key)}'
111+
f'Rotating API key from {self._mask_api_key(prev_api_key)!r} to {self._mask_api_key(next_api_key)!r}'
112112
)
113113

114114
self._api_key = next_api_key
115115

116116
@staticmethod
117-
def _mask_api_key(api_key: str, masked_chars_count: int = 4) -> str:
118-
return '*' * (len(api_key) - masked_chars_count) + api_key[-masked_chars_count:]
117+
def _mask_api_key(api_key: str, masked_chars_count: int = 30, symbol: str = '*') -> str:
118+
api_key_len = len(api_key)
119+
if masked_chars_count >= api_key_len or masked_chars_count <= 0:
120+
return symbol * len(api_key)
121+
122+
right_part = api_key[-(api_key_len - masked_chars_count) :]
123+
return right_part.rjust(len(api_key), symbol)
119124

120125
@property
121126
def keys_count(self) -> int:

tests/test_url_builder.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from unittest.mock import patch
1+
from itertools import cycle
2+
from unittest.mock import patch, Mock
23

34
import pytest
45
import pytest_asyncio
@@ -130,3 +131,42 @@ def test_get_link(ub):
130131
path = 'some_path'
131132
ub.get_link(path)
132133
join_mock.assert_called_once_with(ub.BASE_URL, path)
134+
135+
136+
@pytest.mark.parametrize(
137+
'api_key,masked_chars_count,expected',
138+
[
139+
('abc', 4, '***'),
140+
('abc', 2, '**c'),
141+
('abcd', 4, '****'),
142+
('abcdef', 4, '****ef'),
143+
],
144+
)
145+
def test_mask_api_key(ub, api_key, masked_chars_count, expected):
146+
assert ub._mask_api_key(api_key, masked_chars_count) == expected
147+
148+
assert ub._mask_api_key('qwe', 2, '#') == '##e'
149+
150+
151+
def test_keys_count(ub):
152+
ub._api_keys = [1, 2]
153+
assert ub.keys_count == 2
154+
155+
156+
def test_rotate_api_key(ub):
157+
api_keys = ['one', 'two', 'three']
158+
first, second, _ = api_keys
159+
160+
ub._api_keys = api_keys
161+
ub._api_keys_cycle = cycle(ub._api_keys)
162+
ub._api_key = ub._get_next_api_key()
163+
164+
assert ub._api_key == first
165+
166+
ub._logger = Mock()
167+
ub._logger.info = Mock()
168+
169+
ub.rotate_api_key()
170+
171+
ub._logger.info.assert_called_once()
172+
assert ub._api_key == second

0 commit comments

Comments
 (0)