python - 如何使用 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 函数,这是必需的。
解决方案
解决方案是将方法定义为夹具,而不是使用传统的 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
推荐阅读
- git - Git 错误:“更新被拒绝,因为您当前分支的尖端落后”
- c# - 使用所有值减去一些值检查对象中的重复项
- python - Python- 带有 Statsmodels 的 ARMA 样本内预测函数
- java - 使用 Jackson 将 json 字符串转换为通用 Map
- node.js - Twiml Connect 方法问题
- xml - Odoo 11 自定义报告
- bash - PHP Curl 转换为 Bash Curl 问题
- image - Swift 5 Migration 已更改圆形图像
- r - Optim 函数返回错误的解决方案
- c# - 访问 Servicestack 请求和响应过滤器属性中的 JWT 令牌中的有效负载