首页 > 解决方案 > 带有 pytest-datafiles 的参数化夹具

问题描述

我有一个 Python 函数,可以处理我想要为其设置测试方案的不同类型的文件。对于它可以处理的每种不同的文件类型,我都有一个测试文件。我想使用 pytest-datafiles 以便自动在 tmpdir 中的副本上执行测试。我正在尝试设置一个参数化的夹具,类似于@pytest.fixture(params=[...]),以便为每个测试文件自动调用测试函数。我如何实现这一目标?

我尝试了下面的代码,但是我的数据文件没有复制到 tmpdir,并且测试集合失败,因为test_files()夹具没有产生任何输出。我对 pytest 很陌生,所以我可能不完全理解它是如何工作的。

@pytest.fixture(params = [1,2])
@pytest.mark.datafiles('file1.txt','file1.txt')
def test_files(request,datafiles):
    for testfile in datafiles.listdir():
        yield testfile

@pytest.fixture(params = ['expected_output1','expected_output2'])
def expected_output(request):
    return request.param

def my_test_function(test_files,expected_output):
    assert myFcn(test_files) == expected_output

标签: python-3.xpytestdata-files

解决方案


在阅读了固定装置和标记后,我得出结论,我尝试使用的pytest.mark.datafiles方式可能是不可能的。相反,我使用了 pytest 中的内置tmpdir功能,如下所示。(另外,我命名我的夹具函数的事实test_files()可能会搞砸,因为 pytest 会将它识别为测试函数。)

testFileNames = {1:'file1.txt', 2:'file2.txt'}
expectedOutputs = {1:'expected_output1', 2:'expected_output2'}

@pytest.fixture(params = [1,2])
def testfiles(request,tmpdir):
    shutil.copy(testFileNames[request.param],tmpdir)
    return os.path.join(tmpdir,testFileNames[request.param])

@pytest.fixture(params = [1,2])
def expected_output(request):
    return expectedOutputs[request.param]

def my_test_function(testfiles,expected_output):
    assert myFcn(testfiles) == expected_output

推荐阅读