我有一组对象,我需要为我的测试类中的每个测试运行这些对象。我想参数化 TestClass 中的每个测试函数。最终目标是有类似的东西:
@pytest.mark.parametrize('test_input', [1, 2, 3, 4])
class TestClass:
def test_something1(self, test_input):
# test code here, runs each time for the parametrize
但是根据我的理解,你不能传递输入参数,或者至少调用
@pytest.mark.parametrize
在类里面,这些标记用于 defs
不是 class
秒我现在所拥有的:
class TestClass:
def test_something1(self):
for i in stuff:
# test code here
def test_something2(self):
for i in stuff:
# test code here
...
有没有办法传递参数化类本身或 TestClass 中的每个函数? 也许是
@pytest.mark.parametrize
里面@pytest.fixture...(autouse=True).
我想将我的测试组织成一个类,因为它反射(reflect)了我正在测试的文件。因为我在至少十几个不同的测试中循环这些对象,所以调用类的循环比在每个
def
中更容易。 .
最佳答案
您可以申请 parametrize
到类(class)。来自 the docs :
@pytest.mark.parametrize
allows one to define multiple sets of arguments and fixtures at the test function or class.
相同的数据将发送到类中的所有测试方法。
@pytest.mark.parametrize('test_input', [1, 2, 3, 4])
class TestClass:
def test_something1(self, test_input):
pass
def test_something2(self, test_input):
pass
如果您使用以下内容运行测试
pytest -v
您将获得以下输出:=========================================================================================== test session starts ============================================================================================
platform darwin -- Python 3.7.3, pytest-4.4.2, py-1.8.0, pluggy-0.11.0 -- /Users/user/.local/share/virtualenvs/stack-overlfow-pycharm-L-07rBZ9/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/user/Documents/spikes/stack-overlfow-pycharm
collected 8 items
test_class.py::TestClass::test_something1[1] PASSED [ 12%]
test_class.py::TestClass::test_something1[2] PASSED [ 25%]
test_class.py::TestClass::test_something1[3] PASSED [ 37%]
test_class.py::TestClass::test_something1[4] PASSED [ 50%]
test_class.py::TestClass::test_something2[1] PASSED [ 62%]
test_class.py::TestClass::test_something2[2] PASSED [ 75%]
test_class.py::TestClass::test_something2[3] PASSED [ 87%]
test_class.py::TestClass::test_something2[4] PASSED [100%]
========================================================================================= 8 passed in 0.03 seconds =========================================================================================
这正是您想要的。
关于python - 使用 pytest 参数化类测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729007/