python - 如何更改 pytest 生成的参数
问题描述
执行 test_equals 函数时是否有可能更改 test_zerodivision 参数
当 test_equals 运行 test_zerodivision 函数参数为 a=1 b=0,但我想更改此函数中的 a 或 b 值
我可以更改 TestClass.params 然后重新加载 pytest_generate_tests 或任何其他方式
我知道如何避免这个问题,但我只想知道如何改变这个值。pytest使用了很多黑魔法,我只是好奇
import pytest
def pytest_generate_tests(metafunc):
# called once per each test function
funcarglist = metafunc.cls.params[metafunc.function.__name__]
argnames = sorted(funcarglist[0])
metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]
for funcargs in funcarglist])
class TestClass(object):
# a map specifying multiple argument sets for a test method
params = {
'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ],
'test_zerodivision': [dict(a=1, b=0), ],
}
def test_equals(self, a, b):
assert a == b
def test_zerodivision(self, a, b):
with pytest.raises(ZeroDivisionError):
a / b
解决方案
我认为您正在搜索pytest.mark.parametrize。以下是如何在您的代码下实现此功能的示例:
import pytest
class TestClass:
@pytest.mark.parametrize(
('a', 'b'),
(
(1, 1),
(3, 3),
('a', 'a')
)
)
def test_equal(self, a, b):
assert a == b
@pytest.mark.parametrize(
('a', 'b'),
(
(1, 0),
(0, 0),
(0.1, 0)
)
)
def test_zerodivision(self, a, b):
with pytest.raises(ZeroDivisionError):
a / b
推荐阅读
- python - 类型错误:参数 1 必须是字符串或只读字符缓冲区,而不是文件(在 Learn python the Hard 的练习 17 中)
- api - 如何在 Smart Quotes 中检索特定客户(客户)的 quoteIds?
- python - 在python中“重新编译”时无法正确打印
- laravel - 无法对 DB 播种器执行集成测试 - 错误:在 null 上调用成员函数 connection()
- java - 如果我们在 start 方法而不是 run 方法中执行整个 Thread 功能会发生什么?
- python - Python打印列表的第一行
- sql-server - SQL Server OPENROWSET Numeric vales 更改为 int
- c++ - 在二叉树中插入未处理的异常抛出
- google-bigquery - Airflow 的 bigqueryoperator 不能与 udf 一起使用
- mysql - 按周和月获取一天的平均小时数