如何在pytests之间共享测试运行数据?

tay*_*fun 2 python pytest

我想在不同的 pytest 测试文件之间共享数据和预期的失败。让我举个例子吧。我正在测试 test_a.py 中的 A 类和 test_b.py 中的 B 类。有趣的是,这两个类需要相互兼容,所以我想在相同的数据上测试它们,并将一些数据标记为 xfail。我怎样才能做到这一点?

示例数据:

my_test_data = [
     ('test_data', 'expected_output'),
     pytest.mark.xfail(('another_test', 'failing_output')),
]
Run Code Online (Sandbox Code Playgroud)

我可以把它放在 a 中conftest.py并从测试中导入它,但显式导入感觉不对。

tay*_*fun 5

我已经通过在返回测试数据的夹具上使用参数来解决这个问题。如果将其放入conftest.py文件,则可以自动使用测试文件中的夹具。下面是一个例子:

# in conftest.py file
@pytest.fixture(params=my_test_data)
def my_test(request):
  return request.params
Run Code Online (Sandbox Code Playgroud)

拥有参数化数据返回装置conftest.py意味着您可以在测试中使用该数据而无需导入它:

# in test files themselves
def test_whatever(my_test):
  # Do whatever you like with the test data
  print my_test[0]
Run Code Online (Sandbox Code Playgroud)