繁体   English   中英

为什么我只能通过在测试脚本中使用夹具(来自 pytest)来获取函数作为返回值?

[英]Why do I only get a function as a return value by using a fixture (from pytest) in a test script?

我想为我的代码编写测试函数并决定使用 pytest。 我查看了本教程: https : //semaphoreci.com/community/tutorials/testing-python-applications-with-pytest

我的真实代码涉及另一个脚本,我写的,所以我做了一个例子,它也产生了同样的问题,但不依赖于我的其他代码。

@pytest.fixture()
def example():
    value = 10
    return value

def test_value(example):
    print(example)
    assert(example == 10)

test_value(example)

当我用这个玩具示例运行我的脚本时,打印返回一个函数:

<0x0391E540 处的功能示例>

并且断言失败。

如果我尝试用括号调用 example() ,我会得到:

失败:直接调用夹具“example_chunks”。 Fixtures 不是直接调用的,而是在测试函数请求它们作为参数时自动创建的。 有关固定装置的更多信息,请参阅https://docs.pytest.org/en/stable/fixture.html ,以及https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly了解如何更新您的代码。

我敢肯定,我在这里遗漏了一些重要的东西,但搜索谷歌对我没有帮助,这就是为什么我希望这里有人可以提供一些帮助。

  1. 从脚本中删除此行
test_value(example)
  1. 使用pytest file.py运行您的脚本文件

Fixtures 会被 pytest 自动解析

在您的示例中,您直接运行代码,而夹具只是简单的函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM