1

I have a problem with running an asynchronous test.

My example:

import unittest
import asyncio
from asyncio import coroutine
import pytest
import os


class TestEcommerce(unittest.TestCase):

    async def assertFloatAlmostEqual(self, first, second, places=2, msg=""):
        """
        Used to compare float type values with the specified precision.
        Since with each test we can get numbers with slightly different accuracy - however, this is not an error
        :param msg:
        :param first:
        :param second:
        :param places:
        :return:
        """
        self.assertAlmostEqual(first, second, places=places, msg=msg)

    @pytest.mark.asyncio
    async def test_deep_analysis_find_complex(self):
        # Just for an example
        await self.assertFloatAlmostEqual(100.44, 100.445)
        pass

I get this error:

kernel/test/test_demo.py::TestEcommerce::test_deep_analysis_find_complex /usr/lib/python3.10/unittest/case.py:549: RuntimeWarning: coroutine 'TestEcommerce.test_deep_analysis_find_complex' was never awaited method() Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info.

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

I checked a similar question earlier, however, the answers in it did not work for me.

I also tried to remove async from the main function but then I get another error (which is actually expected)

@pytest.mark.asyncio
def test_deep_analysis_find_complex(self):
    # Just for an example
    await self.assertFloatAlmostEqual(100.44, 100.445)
    pass

E await self.assertFloatAlmostEqual(100.44, 100.445) E
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ E SyntaxError: 'await' outside async function

Can you tell me how to run this test?

Here is my environment info:

pip list --format=freeze | grep pytest

pytest==7.4.0
pytest-asyncio==0.21.1

python -V

Python 3.10.6

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
stas stas
  • 95
  • 10

1 Answers1

0

From the pytest-asyncio docs:

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.

You need to use unittest.IsolatedAsyncioTestCase or something like asynctest, not unittest.TestCase.

user2357112
  • 260,549
  • 28
  • 431
  • 505