首页 > 解决方案 > 如何使用 pytest 中的 setUp 作为异步方法?

问题描述

我有以下代码:

import asyncio
import pytest

from mymodule import myasyncfunction
from unittest import TestCase


class TestDummy(TestCase):
    def setUp(self):
        await myasyncfunction()

    @pytest.mark.asyncio
    async def test_dummy(self):
        assert False

测试通过,因为它根本没有进入测试。它只说:

RuntimeWarning:从未等待协程“TestDummy.setUp”

如何使设置功能异步?

观察:如果我从 TestCase 中删除继承,测试会运行,但之前不会进入 setUp 函数,这是必需的。

标签: pythonpytestpytest-asyncio

解决方案


解决方案是将方法定义为夹具,而不是使用传统的 setUp() 方法。

import pytest

class TestClass:
    @pytest.fixture
    def setup(self):
        pass

    @pytest.mark.asyncio
    async def test_some_stuff(setup):
        pass

正如您所发现的,当类从 Unitest.Testcase 继承时,使用 pytest-asyncio 的 setUp() 方法不起作用:

TestPersonClass 不是 unittest.TestCase 的子类。如果是,测试仍然会成功——但成功将是误报,因为等待表达式之后的代码不会运行。

为什么会这样?答案很复杂,值得单独发表一篇文章,但 tl;dr 版本是在 pytest-asyncio 的源代码的第 93 行,作者期望事件循环从 pytest 夹具传递到测试中,而 unittest.TestCase方法不能直接接收夹具函数参数。

有关上述说明,请参见本博文的结尾: https ://jacobbridges.github.io/post/unit-testing-with-asyncio/

有关使用 pytest-asyncio 进行测试的一些不错的教程,请参见:1) https://www.roguelynn.com/words/asyncio-testing/ 2) https://medium.com/ideas-at-igenius/testing-asyncio- python-code-with-pytest-a2f3628f82bc


推荐阅读