gpt4 book ai didi

python - 如何使用 pytest 中的 setUp 作为异步方法?

转载 作者:行者123 更新时间:2023-12-04 16:45:51 29 4
gpt4 key购买 nike

我有以下代码:

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: coroutine 'TestDummy.setUp' was never awaited



如何使setUp函数异步?

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

最佳答案

解决方案是将方法定义为fixture,而不是使用传统的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 is not a child class of unittest.TestCase. If it was, the test would still succeed – but the success would be a false positive because code after the await expression would not run.

Why is this happening? The answer is complex enough that it deserves a separate post, but the tl;dr version is that on line 93 of pytest-asyncio’s source the author is expecting the event loop to be passed into the test from a pytest fixture, while unittest.TestCase methods cannot directly receive fixture function arguments.



有关上述解释,请参阅本博客文章的结尾:
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

关于python - 如何使用 pytest 中的 setUp 作为异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59353105/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com