async test does not run in pytest

Question:

I am trying to test an async function. Thus, I have an async test. When I use pycharm to set breakpoints in this test, they don’t break. The things which are supposed to print to console do not print. And, the test takes 0 seconds. pytest lists the test as PASSED, but it clearly isn’t actually executing the code in context.

Here is the code:

import unittest.mock
import pytest
from app.listener import ListenerCog


class ListenerCogTestCase(unittest.TestCase):
    def setUp(self):
        # Create a mock discord.Client object
        self.client = unittest.mock.Mock()

        # Create a ListenerCog instance and pass the mock client as the bot attribute
        self.listener_cog = ListenerCog(self.client)

    @pytest.mark.asyncio
    async def test_on_ready(self):
        # Call the on_ready method of the ListenerCog instance
        await self.listener_cog.on_ready()

        # Assert that the "Running!" message is printed
        self.assertIn("Running!", self.stdout.getvalue())

What I’ve tried:

  • enable python.debug.asyncio.repl in pycharm registry
  • add arguments to pytest including --capture=no -s and --no-conv

Nothing seems to be working. Would really appreciate some guidance here if anyone is accustomed to debugging async tests.

Asked By: melchoir55

||

Answers:

According to pytest-asyncio documentation:

Note that test classes subclassing the standard unittest library are
not supported. Users are advised to use
unittest.IsolatedAsyncioTestCase or an async framework such as
asynctest.

Did you consider removing the unittest.TestCase inheritance and rewriting your test class without it?

Answered By: Peter K
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.