Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions tests/test_autopost.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
from aiohttp import ClientSession
from pytest_mock import MockerFixture

from topgg import DBLClient, StatsWrapper
from topgg import DBLClient
from topgg.autopost import AutoPoster
from topgg.errors import ServerError, TopGGException, Unauthorized
from topgg.errors import HTTPException, TopGGException


MOCK_TOKEN = ".eyJfdCI6IiIsImlkIjoiMzY0ODA2MDI5ODc2NTU1Nzc2In0=."


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

@pytest.fixture
def autopost(session: ClientSession) -> AutoPoster:
return AutoPoster(DBLClient("", session=session))
return AutoPoster(DBLClient(MOCK_TOKEN, session=session))


@pytest.mark.asyncio
Expand All @@ -29,15 +32,15 @@ async def test_AutoPoster_breaks_autopost_loop_on_401(
response.status = 401

mocker.patch(
"topgg.DBLClient.post_guild_count", side_effect=Unauthorized(response, {})
"topgg.DBLClient.post_guild_count", side_effect=HTTPException(response, {})
)

callback = mock.Mock()
autopost = DBLClient("", session=session).autopost().stats(callback)
autopost = DBLClient(MOCK_TOKEN, session=session).autopost().stats(callback)
assert isinstance(autopost, AutoPoster)
assert not isinstance(autopost.stats()(callback), AutoPoster)

with pytest.raises(Unauthorized):
with pytest.raises(HTTPException):
await autopost.start()

callback.assert_called_once()
Expand Down Expand Up @@ -73,7 +76,7 @@ async def test_AutoPoster_error_callback(
response = mock.Mock("reason, status")
response.reason = "Internal Server Error"
response.status = 500
side_effect = ServerError(response, {})
side_effect = HTTPException(response, {})

mocker.patch("topgg.DBLClient.post_guild_count", side_effect=side_effect)
task = autopost.on_error(error_callback).stats(mock.Mock()).start()
Expand Down
127 changes: 22 additions & 105 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,137 +1,54 @@
import typing as t

import mock
import pytest
from aiohttp import ClientSession

import topgg
from topgg import errors


@pytest.fixture
def session() -> ClientSession:
return mock.Mock(ClientSession)


@pytest.fixture
def client() -> topgg.DBLClient:
client = topgg.DBLClient(token="TOKEN", default_bot_id=1234)
client.http = mock.Mock(topgg.http.HTTPClient)
return client


@pytest.mark.asyncio
async def test_HTTPClient_with_external_session(session: ClientSession):
http = topgg.http.HTTPClient("TOKEN", session=session)
assert not http._own_session
await http.close()
session.close.assert_not_called()


@pytest.mark.asyncio
async def test_HTTPClient_with_no_external_session(session: ClientSession):
http = topgg.http.HTTPClient("TOKEN")
http.session = session
assert http._own_session
await http.close()
session.close.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_get_bot_votes_with_no_default_bot_id():
client = topgg.DBLClient("TOKEN")
with pytest.raises(
errors.ClientException,
match="you must set default_bot_id when constructing the client.",
):
await client.get_bot_votes()
MOCK_TOKEN = ".eyJfdCI6IiIsImlkIjoiMzY0ODA2MDI5ODc2NTU1Nzc2In0=."


@pytest.mark.asyncio
async def test_DBLClient_post_guild_count_with_no_args():
client = topgg.DBLClient("TOKEN", default_bot_id=1234)
client = topgg.DBLClient(MOCK_TOKEN)
with pytest.raises(TypeError, match="stats or guild_count must be provided."):
await client.post_guild_count()


@pytest.mark.parametrize(
"method, kwargs",
[
(topgg.DBLClient.get_guild_count, {}),
(topgg.DBLClient.get_bot_info, {}),
(
topgg.DBLClient.generate_widget,
{
"options": topgg.types.WidgetOptions(),
},
),
],
)
@pytest.mark.asyncio
async def test_DBLClient_get_guild_count_with_no_id(
method: t.Callable, kwargs: t.Dict[str, t.Any]
):
client = topgg.DBLClient("TOKEN")
with pytest.raises(
errors.ClientException, match="bot_id or default_bot_id is unset."
):
await method(client, **kwargs)


@pytest.mark.asyncio
async def test_closed_DBLClient_raises_exception():
client = topgg.DBLClient("TOKEN")
assert not client.is_closed
await client.close()
assert client.is_closed
with pytest.raises(errors.ClientException, match="client has been closed."):
await client.get_weekend_status()


@pytest.mark.asyncio
async def test_DBLClient_get_weekend_status(client: topgg.DBLClient):
client.http.get_weekend_status = mock.AsyncMock()
async def test_DBLClient_get_weekend_status(monkeypatch):
client = topgg.DBLClient(MOCK_TOKEN)
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock())
await client.get_weekend_status()
client.http.get_weekend_status.assert_called_once()
client._DBLClient__request.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_post_guild_count(client: topgg.DBLClient):
client.http.post_guild_count = mock.AsyncMock()
async def test_DBLClient_post_guild_count(monkeypatch):
client = topgg.DBLClient(MOCK_TOKEN)
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock())
await client.post_guild_count(guild_count=123)
client.http.post_guild_count.assert_called_once()
client._DBLClient__request.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_get_guild_count(client: topgg.DBLClient):
client.http.get_guild_count = mock.AsyncMock(return_value={})
async def test_DBLClient_get_guild_count(monkeypatch):
client = topgg.DBLClient(MOCK_TOKEN)
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock(return_value={}))
await client.get_guild_count()
client.http.get_guild_count.assert_called_once()
client._DBLClient__request.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_get_bot_votes(client: topgg.DBLClient):
client.http.get_bot_votes = mock.AsyncMock(return_value=[])
async def test_DBLClient_get_bot_votes(monkeypatch):
client = topgg.DBLClient(MOCK_TOKEN)
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock(return_value=[]))
await client.get_bot_votes()
client.http.get_bot_votes.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_get_bots(client: topgg.DBLClient):
client.http.get_bots = mock.AsyncMock(return_value={"results": []})
await client.get_bots()
client.http.get_bots.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_get_user_info(client: topgg.DBLClient):
client.http.get_user_info = mock.AsyncMock(return_value={})
await client.get_user_info(1234)
client.http.get_user_info.assert_called_once()
client._DBLClient__request.assert_called_once()


@pytest.mark.asyncio
async def test_DBLClient_get_user_vote(client: topgg.DBLClient):
client.http.get_user_vote = mock.AsyncMock(return_value={"voted": 1})
async def test_DBLClient_get_user_vote(monkeypatch):
client = topgg.DBLClient(MOCK_TOKEN)
monkeypatch.setattr("topgg.DBLClient._DBLClient__request", mock.AsyncMock(return_value={"voted": 1}))
await client.get_user_vote(1234)
client.http.get_user_vote.assert_called_once()
client._DBLClient__request.assert_called_once()
12 changes: 6 additions & 6 deletions tests/test_ratelimiter.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import pytest

from topgg.ratelimiter import AsyncRateLimiter
from topgg.ratelimiter import Ratelimiter

n = period = 10


@pytest.fixture
def limiter() -> AsyncRateLimiter:
return AsyncRateLimiter(max_calls=n, period=period)
def limiter() -> Ratelimiter:
return Ratelimiter(max_calls=n, period=period)


@pytest.mark.asyncio
async def test_AsyncRateLimiter_calls(limiter: AsyncRateLimiter) -> None:
async def test_AsyncRateLimiter_calls(limiter: Ratelimiter) -> None:
for _ in range(n):
async with limiter:
pass

assert len(limiter.calls) == limiter.max_calls == n
assert len(limiter._Ratelimiter__calls) == limiter._Ratelimiter__max_calls == n


@pytest.mark.asyncio
async def test_AsyncRateLimiter_timespan_property(limiter: AsyncRateLimiter) -> None:
async def test_AsyncRateLimiter_timespan_property(limiter: Ratelimiter) -> None:
for _ in range(n):
async with limiter:
pass
Expand Down
5 changes: 3 additions & 2 deletions topgg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@
:license: MIT, see LICENSE for more details.
"""

from .version import VERSION

__title__ = "topggpy"
__author__ = "Assanali Mukhanov"
__maintainer__ = "Norizon"
__license__ = "MIT"
__version__ = "2.0.0a1"
__version__ = VERSION

from .autopost import *
from .client import *
from .data import *
from .errors import *
from .http import *

# can't be added to __all__ since they'd clash with automodule
from .types import *
Expand Down
2 changes: 1 addition & 1 deletion topgg/autopost.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ async def _internal_loop(self) -> None:
await self.client.post_guild_count(stats)
except Exception as err:
await self.client._invoke_callback(self._error, err)
if isinstance(err, errors.Unauthorized):
if isinstance(err, errors.HTTPException) and err.code == 401:
raise err from None
else:
on_success = getattr(self, "_success", None)
Expand Down
Loading
Loading