python-3.x - 带有 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
解决方案
在阅读了固定装置和标记后,我得出结论,我尝试使用的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
推荐阅读
- plsql - 如何在 HSQL DB 中创建具有最大行值的序列?
- javascript - Snap.svg 的多个实例导致损坏
- python - 如何使用 BeautifulSoup 根据 Python 中的数据自动化属性从 div 类中抓取内容?
- mysql - 使用左连接让 Group by 在 MySQL 5.7 中工作
- python - 哪种 ML 模型最适合用于预测客户保留的时间序列活动日志数据?
- spring - 过滤嵌套数组弹簧弹性搜索
- django - 从 StackedInline 模型 Django 中预填充 slug 字段
- asp.net - 无法将值 NULL 插入列“TaskID”、表“TEAM.dbo.Task”;列不允许空语句已终止
- laravel-5 - 在 Laravel 5.4 中将 Json 数据转换为 XML
- javascript - 如何访问特定的动态创建的元素?