Test未被执行.使用夹具



我有一个简单的Python库,我使用以下命令来运行测试:

python setup.py pytest

下面的测试按预期工作:

def test_out():
assert 1 == 2

测试结果:

platform linux -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /media/drive2/src
collected 1 item                                                                                                                                                                           
tests/test_error.py F

当添加@pytest.fixture时,测试不执行:

import pytest
@pytest.fixture
def test_out():
assert 1 == 2

测试结果:

platform linux -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /media/drive2/src
collected 0 items  

这种行为的原因是什么,以及如何以一种不会阻止测试运行的方式添加@pytest.fixture?

(我想用capsys.readouterr(),所以我认为需要@pytest.fixture)

首先,pytest.fixture是一个装饰器,所以它会影响下面的函数,正确的使用方法是将它们放在一起(中间没有空行),像这样:

import pytest
@pytest.fixture
def test_out():
assert 1 == 2   # This still makes no sense, see answer below

@pytest.fixture只是表示修饰函数的返回值将作为其他测试函数的参数使用。(修饰函数不会作为测试运行)。

来自pytest文档:

"fixture",在字面意义上,是每个排序步骤和数据。它们是测试所需要的一切。

下面是一个类似于使用fixture的测试的示例:

import pytest
@pytest.fixture
def my_number():
return 2
def test_out(my_number):
assert 1 == my_number  # This will fail

当您创建夹具my_number时,重新定义的值可以用作其他测试函数的参数(在本例中为test_out)。

当您必须在几个测试中创建相同的东西时,这很有用。您可以创建一个fixture,而不是在每个测试中重复代码。

最新更新