分解pytest夹具的常见设置代码



我正在用pytest编写一些测试,我认为这是一个简单的问题,但不确定正确的方法。我有一些代码如下:

@pytest.fixture
def obj1():
...setup object 1...
return obj
@pytest.fixture
def obj2():
....setup object 2 ...
return obj
def test_val_obj_1(obj1):
...some common boilerplate...
output = some_function(obj1)
assert output['important_key'] == some_values
def test_val_obj_2(obj2):
...some common boilerplate...
output = some_function(obj2)
assert output['important_key'] == some_values

对于我的两个测试,...some common boilerplate...和some_function((是相同的,所以我更希望在其他地方使用它。我只是定义了一个正常的函数来做这件事吗?还是我需要对固定装置做一些特定的事情?我还没有完全沉浸在";参数化的";fixture在文档中,无法确定这是我所问的,还是不同的用例。

parameterized可能会对您有所帮助,但这可能取决于样板中发生的情况

@pytest.mark.parametrize("obj,some_value", [(obj1, some_value), (obj2, some_value)])
def test_val_obj(obj, some_value):
...some common boilerplate...
output = some_function(obj)
assert output['important_key'] == some_value

最新更新