python - 为什么测试功能看不到我的 py.test 装置?

标签 python unit-testing python-2.7 pytest

我有以下结构:

demo/
  conftest.py
  test_1.py
  test_2.py

conftest.py 内容为:

import pytest
@pytest.fixture()

def my_fixture():
print  "testing"*

test_1.py内容为:

def test_my_fixture(my_fixture):
    my_fixture

test_2.py内容为:

 import pytest

 @pytest.mark.usefixtures('my_fixture')
 def test_my_fixture():
     my_fixture

当使用 py.test -s 执行测试时,我在 test_2.py 中得到 fixture 的 NameError 但在 中没有test_1.py;为什么?

这是输出:

================ test session starts ================
platform linux2 -- Python 2.7.3 -- py-1.4.26 -- pytest-2.6.4
plugins: timeout, random
collected 2 items 

test_1.py testing
.
test_2.py testing
F

===================== FAILURES ======================
__________________ test_my_fixture __________________

    def test_my_fixture():
>       my_fixture
E       NameError: global name 'my_fixture' is not defined

test_2.py:7: NameError

最佳答案

当您不需要直接访问 fixture 对象( fixture 函数的返回值)时,使用pytest.mark.usefixtures标记。

如果您需要访问 fixture 对象,请使用 fixture-as-function-argument(代码中的第一种方式)。


第二个代码错误的原因:my_fixture没有在函数(不是局部变量)或模块(不是全局变量)中定义,也不是内置对象;但是代码正在尝试访问它; 名称错误

只是不要尝试访问 my_fixture。 fixture 对象将为 None,因为 my_fixture 函数不返回任何内容。

关于python - 为什么测试功能看不到我的 py.test 装置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410763/

相关文章:

python - 在 Python 2.7.3 中使用字典作为 switch 语句

python - 如何使用方法更改类属性?

python - 我需要一个带有 Nose 的python单元测试sqlalchemy模型的样本

项目类路径测试中缺少 java ee api

unit-testing - 在 Golang 中制作模拟 gin.Context

java - apache pdfbox - 如何测试文档是否被展平?

python 2.7 vs 3编码解码字节字符串

python - 使用 sklearn 中的 minmaxScalar 缩放 NumPy 数组中具有多个特征的特定特征

python os.system() 没有以我的权限运行?

python-2.7 - aws cloudformation lambda python 错误处理程序