aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar MarkKoz <[email protected]>2020-02-12 09:16:46 -0800
committerGravatar MarkKoz <[email protected]>2020-02-12 10:07:58 -0800
commit22a55534ef13990815a6f69d361e2a12693075d5 (patch)
tree9740dc12eca3851c8885a3910e28b30a908508d5
parentSync tests: use async_test decorator (diff)
Tests: fix unawaited error for MockAPIClient
This error is due to the use of an actual instance of APIClient as the spec for the mock. recreate() is called in __init__ which in turn creates a task for the _create_session coroutine. The approach to the solution is to use the type for the spec rather than and instance, thus avoiding any call of __init__. However, without an instance, instance attributes will not be included in the spec. Therefore, they are defined as class attributes on the actual APIClient class definition and given default values. Alternatively, a subclass of APIClient could have been made in the tests.helpers module to define those class attributes. However, it seems easier to maintain if the attributes are in the original class definition.
-rw-r--r--bot/api.py5
-rw-r--r--tests/helpers.py6
2 files changed, 5 insertions, 6 deletions
diff --git a/bot/api.py b/bot/api.py
index a9d2baa4d..d5880ba18 100644
--- a/bot/api.py
+++ b/bot/api.py
@@ -32,6 +32,9 @@ class ResponseCodeError(ValueError):
class APIClient:
"""Django Site API wrapper."""
+ session: Optional[aiohttp.ClientSession] = None
+ loop: asyncio.AbstractEventLoop = None
+
def __init__(self, loop: asyncio.AbstractEventLoop, **kwargs):
auth_headers = {
'Authorization': f"Token {Keys.site_api}"
@@ -42,7 +45,7 @@ class APIClient:
else:
kwargs['headers'] = auth_headers
- self.session: Optional[aiohttp.ClientSession] = None
+ self.session = None
self.loop = loop
self._ready = asyncio.Event(loop=loop)
diff --git a/tests/helpers.py b/tests/helpers.py
index a40673bb9..9d9dd5da6 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -337,10 +337,6 @@ class MockUser(CustomMockMixin, unittest.mock.Mock, ColourMixin, HashableMixin):
self.mention = f"@{self.name}"
-# Create an APIClient instance to get a realistic MagicMock of `bot.api.APIClient`
-api_client_instance = APIClient(loop=unittest.mock.MagicMock())
-
-
class MockAPIClient(CustomMockMixin, unittest.mock.MagicMock):
"""
A MagicMock subclass to mock APIClient objects.
@@ -350,7 +346,7 @@ class MockAPIClient(CustomMockMixin, unittest.mock.MagicMock):
"""
def __init__(self, **kwargs) -> None:
- super().__init__(spec_set=api_client_instance, **kwargs)
+ super().__init__(spec_set=APIClient, **kwargs)
# Create a Bot instance to get a realistic MagicMock of `discord.ext.commands.Bot`