aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Sebastiaan Zeeff <[email protected]>2019-11-13 17:29:09 +0100
committerGravatar Sebastiaan Zeeff <[email protected]>2019-11-13 17:29:09 +0100
commit7f4829e9fab007690d48188f499bfcc1a7baa437 (patch)
treeb402adeeaafd196fbe7260a02766f432526cf91e
parentPrevent setting unknown attributes on d.py mocks (diff)
Prevent await warnings for MockBot's create_task
Previously, the coroutine object passed to `MockBot.loop.create_task` would trigger a `RuntimeWarning` for not being awaited as we do not actually create a task for it. To prevent these warnings, coroutine objects passed will now automatically be closed.
-rw-r--r--tests/helpers.py8
-rw-r--r--tests/test_helpers.py12
2 files changed, 19 insertions, 1 deletions
diff --git a/tests/helpers.py b/tests/helpers.py
index 35f2c288c..8a14aeef4 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -227,7 +227,8 @@ class MockMember(CustomMockMixin, unittest.mock.Mock, ColourMixin, HashableMixin
if roles:
self.roles.extend(roles)
- self.mention = f"@{self.name}"
+ if 'mention' not in kwargs:
+ self.mention = f"@{self.name}"
# Create a Bot instance to get a realistic MagicMock of `discord.ext.commands.Bot`
@@ -251,6 +252,11 @@ class MockBot(CustomMockMixin, unittest.mock.MagicMock):
# is technically incorrect, since it's a regular def.)
self.wait_for = AsyncMock()
+ # Since calling `create_task` on our MockBot does not actually schedule the coroutine object
+ # as a task in the asyncio loop, this `side_effect` calls `close()` on the coroutine object
+ # to prevent "has not been awaited"-warnings.
+ self.loop.create_task.side_effect = lambda coroutine: coroutine.close()
+
# Create a TextChannel instance to get a realistic MagicMock of `discord.TextChannel`
channel_data = {
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index e879ef97a..7894e104a 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -202,6 +202,18 @@ class DiscordMocksTests(unittest.TestCase):
mock = mock_type(mention=mention)
self.assertEqual(mock.mention, mention)
+ def test_create_test_on_mock_bot_closes_passed_coroutine(self):
+ """`bot.loop.create_task` should close the passed coroutine object to prevent warnings."""
+ async def dementati():
+ """Dummy coroutine for testing purposes."""
+
+ coroutine_object = dementati()
+
+ bot = helpers.MockBot()
+ bot.loop.create_task(coroutine_object)
+ with self.assertRaises(RuntimeError, msg="cannot reuse already awaited coroutine"):
+ asyncio.run(coroutine_object)
+
class MockObjectTests(unittest.TestCase):
"""Tests the mock objects and mixins we've defined."""