gpt4 book ai didi

python - pytest 是否支持在测试文件中使用函数工厂?

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

示例 test.py文件:

import torch

def one():
return torch.tensor(0.0132005215)

def two():
return torch.tensor(4.4345855713e-05)

def three():
return torch.tensor(7.1525573730e-07)


def test_method(method, expected_value):
value = method()
assert(torch.isclose(value, expected_value))

def test_one():
test_method(one, torch.tensor(0.0132005215))

def test_two():
test_method(two, torch.tensor(4.4345855713e-05))

def test_three():
test_method(three, torch.tensor(7.1525573730e-07))
# test_method(three, torch.tensor(1.0))

if __name__ == '__main__':
test_one()
test_two()
test_three()

基本上,我有几个要测试的函数(这里称为 onetwothree ),所有函数都具有相同的签名但内部结构不同。因此,而不是编写函数 test_one() , test_two()等,从而复制代码,我写了一个“函数工厂”(这是正确的术语吗?) test_method ,它将函数、预期结果作为输入并返回 assert 的结果命令。

如您所见,现在测试是手动执行的:我运行脚本 test.py ,看屏幕,如果没有 Assertion error打印出来,我很高兴。当然,我想通过使用 pytest 来改进这一点。 ,因为有人告诉我它是最简单和最常用的 Python 测试框架之一。问题是通过查看 pytest documentation我的印象是 pytest将尝试运行名称以 test_ 开头的所有函数.当然,测试 test_method本身没有任何意义。你能帮我重构这个测试脚本,以便我可以用 pytest 运行它吗? ?

最佳答案

在 pytest 中,您可以使用 test parametrization为达到这个。在您的情况下,您必须为测试提供不同的参数:

import pytest

@pytest.mark.parametrize("method, expected_value",
[(one, 0.0132005215),
(two, 4.4345855713e-05),
(three, 7.1525573730e-07)])
def test_method(method, expected_value):
value = method()
assert(torch.isclose(value, expected_value))

如果您运行 python -m pytest -rA (有关输出选项,请参阅 the documentation),您将获得三个测试的输出,例如:
======================================================= PASSES ========================================================
=============================================== short test summary info ===============================================
PASSED test.py::test_method[one-0.0132005215]
PASSED test.py::test_method[two-4.4345855713e-05]
PASSED test.py::test_method[three-7.152557373e-07]
================================================== 3 passed in 0.07s ==================================================

如果您不喜欢灯具名称,可以修改它们:
@pytest.mark.parametrize("method, expected_value",
[(one, 0.0132005215),
(two, 4.4345855713e-05),
(three, 7.1525573730e-07),
],
ids=["one", "two", "three"])
...

这给你:
=============================================== short test summary info ===============================================
PASSED test.py::test_method[one]
PASSED test.py::test_method[two]
PASSED test.py::test_method[three]
================================================== 3 passed in 0.06s ==================================================

关于python - pytest 是否支持在测试文件中使用函数工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61775604/

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