Skip to content

Commit 488db49

Browse files
authored
refactor: refactor http usage (Top-gg-Community#85)
2 parents 9cbf317 + 4177fe5 commit 488db49

File tree

10 files changed

+330
-703
lines changed

10 files changed

+330
-703
lines changed

tests/test_autopost.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
from aiohttp import ClientSession
66
from pytest_mock import MockerFixture
77

8-
from topgg import DBLClient, StatsWrapper
8+
from topgg import DBLClient
99
from topgg.autopost import AutoPoster
10-
from topgg.errors import ServerError, TopGGException, Unauthorized
10+
from topgg.errors import HTTPException, TopGGException
11+
12+
13+
MOCK_TOKEN = ".eyJfdCI6IiIsImlkIjoiMzY0ODA2MDI5ODc2NTU1Nzc2In0=."
1114

1215

1316
@pytest.fixture
@@ -17,7 +20,7 @@ def session() -> ClientSession:
1720

1821
@pytest.fixture
1922
def autopost(session: ClientSession) -> AutoPoster:
20-
return AutoPoster(DBLClient("", session=session))
23+
return AutoPoster(DBLClient(MOCK_TOKEN, session=session))
2124

2225

2326
@pytest.mark.asyncio
@@ -29,15 +32,15 @@ async def test_AutoPoster_breaks_autopost_loop_on_401(
2932
response.status = 401
3033

3134
mocker.patch(
32-
"topgg.DBLClient.post_guild_count", side_effect=Unauthorized(response, {})
35+
"topgg.DBLClient.post_guild_count", side_effect=HTTPException(response, {})
3336
)
3437

3538
callback = mock.Mock()
36-
autopost = DBLClient("", session=session).autopost().stats(callback)
39+
autopost = DBLClient(MOCK_TOKEN, session=session).autopost().stats(callback)
3740
assert isinstance(autopost, AutoPoster)
3841
assert not isinstance(autopost.stats()(callback), AutoPoster)
3942

40-
with pytest.raises(Unauthorized):
43+
with pytest.raises(HTTPException):
4144
await autopost.start()
4245

4346
callback.assert_called_once()
@@ -73,7 +76,7 @@ async def test_AutoPoster_error_callback(
7376
response = mock.Mock("reason, status")
7477
response.reason = "Internal Server Error"
7578
response.status = 500
76-
side_effect = ServerError(response, {})
79+
side_effect = HTTPException(response, {})
7780

7881
mocker.patch("topgg.DBLClient.post_guild_count", side_effect=side_effect)
7982
task = autopost.on_error(error_callback).stats(mock.Mock()).start()

tests/test_client.py

Lines changed: 22 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,137 +1,54 @@
1-
import typing as t
2-
31
import mock
42
import pytest
5-
from aiohttp import ClientSession
63

74
import topgg
8-
from topgg import errors
9-
10-
11-
@pytest.fixture
12-
def session() -> ClientSession:
13-
return mock.Mock(ClientSession)
14-
15-
16-
@pytest.fixture
17-
def client() -> topgg.DBLClient:
18-
client = topgg.DBLClient(token="TOKEN", default_bot_id=1234)
19-
client.http = mock.Mock(topgg.http.HTTPClient)
20-
return client
21-
22-
23-
@pytest.mark.asyncio
24-
async def test_HTTPClient_with_external_session(session: ClientSession):
25-
http = topgg.http.HTTPClient("TOKEN", session=session)
26-
assert not http._own_session
27-
await http.close()
28-
session.close.assert_not_called()
29-
30-
31-
@pytest.mark.asyncio
32-
async def test_HTTPClient_with_no_external_session(session: ClientSession):
33-
http = topgg.http.HTTPClient("TOKEN")
34-
http.session = session
35-
assert http._own_session
36-
await http.close()
37-
session.close.assert_called_once()
385

396

40-
@pytest.mark.asyncio
41-
async def test_DBLClient_get_bot_votes_with_no_default_bot_id():
42-
client = topgg.DBLClient("TOKEN")
43-
with pytest.raises(
44-
errors.ClientException,
45-
match="you must set default_bot_id when constructing the client.",
46-
):
47-
await client.get_bot_votes()
7+
MOCK_TOKEN = ".eyJfdCI6IiIsImlkIjoiMzY0ODA2MDI5ODc2NTU1Nzc2In0=."
488

499

5010
@pytest.mark.asyncio
5111
async def test_DBLClient_post_guild_count_with_no_args():
52-
client = topgg.DBLClient("TOKEN", default_bot_id=1234)
12+
client = topgg.DBLClient(MOCK_TOKEN)
5313
with pytest.raises(TypeError, match="stats or guild_count must be provided."):
5414
await client.post_guild_count()
5515

5616

57-
@pytest.mark.parametrize(
58-
"method, kwargs",
59-
[
60-
(topgg.DBLClient.get_guild_count, {}),
61-
(topgg.DBLClient.get_bot_info, {}),
62-
(
63-
topgg.DBLClient.generate_widget,
64-
{
65-
"options": topgg.types.WidgetOptions(),
66-
},
67-
),
68-
],
69-
)
7017
@pytest.mark.asyncio
71-
async def test_DBLClient_get_guild_count_with_no_id(
72-
method: t.Callable, kwargs: t.Dict[str, t.Any]
73-
):
74-
client = topgg.DBLClient("TOKEN")
75-
with pytest.raises(
76-
errors.ClientException, match="bot_id or default_bot_id is unset."
77-
):
78-
await method(client, **kwargs)
79-
80-
81-
@pytest.mark.asyncio
82-
async def test_closed_DBLClient_raises_exception():
83-
client = topgg.DBLClient("TOKEN")
84-
assert not client.is_closed
85-
await client.close()
86-
assert client.is_closed
87-
with pytest.raises(errors.ClientException, match="client has been closed."):
88-
await client.get_weekend_status()
89-
90-
91-
@pytest.mark.asyncio
92-
async def test_DBLClient_get_weekend_status(client: topgg.DBLClient):
93-
client.http.get_weekend_status = mock.AsyncMock()
18+
async def test_DBLClient_get_weekend_status(monkeypatch):
19+
client = topgg.DBLClient(MOCK_TOKEN)
20+
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock())
9421
await client.get_weekend_status()
95-
client.http.get_weekend_status.assert_called_once()
22+
client._DBLClient__request.assert_called_once()
9623

9724

9825
@pytest.mark.asyncio
99-
async def test_DBLClient_post_guild_count(client: topgg.DBLClient):
100-
client.http.post_guild_count = mock.AsyncMock()
26+
async def test_DBLClient_post_guild_count(monkeypatch):
27+
client = topgg.DBLClient(MOCK_TOKEN)
28+
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock())
10129
await client.post_guild_count(guild_count=123)
102-
client.http.post_guild_count.assert_called_once()
30+
client._DBLClient__request.assert_called_once()
10331

10432

10533
@pytest.mark.asyncio
106-
async def test_DBLClient_get_guild_count(client: topgg.DBLClient):
107-
client.http.get_guild_count = mock.AsyncMock(return_value={})
34+
async def test_DBLClient_get_guild_count(monkeypatch):
35+
client = topgg.DBLClient(MOCK_TOKEN)
36+
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock(return_value={}))
10837
await client.get_guild_count()
109-
client.http.get_guild_count.assert_called_once()
38+
client._DBLClient__request.assert_called_once()
11039

11140

11241
@pytest.mark.asyncio
113-
async def test_DBLClient_get_bot_votes(client: topgg.DBLClient):
114-
client.http.get_bot_votes = mock.AsyncMock(return_value=[])
42+
async def test_DBLClient_get_bot_votes(monkeypatch):
43+
client = topgg.DBLClient(MOCK_TOKEN)
44+
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock(return_value=[]))
11545
await client.get_bot_votes()
116-
client.http.get_bot_votes.assert_called_once()
117-
118-
119-
@pytest.mark.asyncio
120-
async def test_DBLClient_get_bots(client: topgg.DBLClient):
121-
client.http.get_bots = mock.AsyncMock(return_value={"results": []})
122-
await client.get_bots()
123-
client.http.get_bots.assert_called_once()
124-
125-
126-
@pytest.mark.asyncio
127-
async def test_DBLClient_get_user_info(client: topgg.DBLClient):
128-
client.http.get_user_info = mock.AsyncMock(return_value={})
129-
await client.get_user_info(1234)
130-
client.http.get_user_info.assert_called_once()
46+
client._DBLClient__request.assert_called_once()
13147

13248

13349
@pytest.mark.asyncio
134-
async def test_DBLClient_get_user_vote(client: topgg.DBLClient):
135-
client.http.get_user_vote = mock.AsyncMock(return_value={"voted": 1})
50+
async def test_DBLClient_get_user_vote(monkeypatch):
51+
client = topgg.DBLClient(MOCK_TOKEN)
52+
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock(return_value={"voted": 1}))
13653
await client.get_user_vote(1234)
137-
client.http.get_user_vote.assert_called_once()
54+
client._DBLClient__request.assert_called_once()

tests/test_ratelimiter.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
import pytest
22

3-
from topgg.ratelimiter import AsyncRateLimiter
3+
from topgg.ratelimiter import Ratelimiter
44

55
n = period = 10
66

77

88
@pytest.fixture
9-
def limiter() -> AsyncRateLimiter:
10-
return AsyncRateLimiter(max_calls=n, period=period)
9+
def limiter() -> Ratelimiter:
10+
return Ratelimiter(max_calls=n, period=period)
1111

1212

1313
@pytest.mark.asyncio
14-
async def test_AsyncRateLimiter_calls(limiter: AsyncRateLimiter) -> None:
14+
async def test_AsyncRateLimiter_calls(limiter: Ratelimiter) -> None:
1515
for _ in range(n):
1616
async with limiter:
1717
pass
1818

19-
assert len(limiter.calls) == limiter.max_calls == n
19+
assert len(limiter._Ratelimiter__calls) == limiter._Ratelimiter__max_calls == n
2020

2121

2222
@pytest.mark.asyncio
23-
async def test_AsyncRateLimiter_timespan_property(limiter: AsyncRateLimiter) -> None:
23+
async def test_AsyncRateLimiter_timespan_property(limiter: Ratelimiter) -> None:
2424
for _ in range(n):
2525
async with limiter:
2626
pass

topgg/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,18 @@
88
:license: MIT, see LICENSE for more details.
99
"""
1010

11+
from .version import VERSION
12+
1113
__title__ = "topggpy"
1214
__author__ = "Assanali Mukhanov"
1315
__maintainer__ = "Norizon"
1416
__license__ = "MIT"
15-
__version__ = "2.0.0a1"
17+
__version__ = VERSION
1618

1719
from .autopost import *
1820
from .client import *
1921
from .data import *
2022
from .errors import *
21-
from .http import *
2223

2324
# can't be added to __all__ since they'd clash with automodule
2425
from .types import *

topgg/autopost.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ async def _internal_loop(self) -> None:
269269
await self.client.post_guild_count(stats)
270270
except Exception as err:
271271
await self.client._invoke_callback(self._error, err)
272-
if isinstance(err, errors.Unauthorized):
272+
if isinstance(err, errors.HTTPException) and err.code == 401:
273273
raise err from None
274274
else:
275275
on_success = getattr(self, "_success", None)

0 commit comments

Comments
 (0)