python - 为目录中的每个文件运行 pytest

标签 python flask pytest glob

我正在尝试构建一个例程,为当前目录中的每个 PDF 文档调用 Pytest 类......让我解释一下
假设我有这个测试文件

import pytest

class TestHeader:
    #asserts...

class TestBody:
    #asserts...
此脚本需要测试我的 cwd 中的每个 pdf 文档
这是我最好的尝试:
import glob
import pytest

class TestHeader:
    #asserts...

class TestBody:
    #asserts...

filelist = glob.glob('*.pdf')

for file in filelist:
    #magically call pytest for each file
我将如何处理这个?
编辑:补充我的问题。
我有一个巨大的函数来提取每个文档的数据,我们称之为 extract_pdf此函数返回一个元组(标题,正文)。
当前的尝试如下所示:
import glob
import pytest

class TestHeader:
    #asserts...

class TestBody:
    #asserts...

filelist = glob.glob('*.pdf')

for file in filelist:
    header, body = extract_pdf(file)
    pytest.main(<pass header and body as args for pytest>)
我需要在测试之前解析每个文档。可以这样做吗?

最佳答案

通过动态参数化测试用例来做到这一点的最佳方法..
这可以使用 pytest_generate_tests 来实现钩..

def pytest_generate_tests(metafunc):
    filelist = glob.glob('*.pdf')
    metafunc.parametrize("fileName", filelist )
注意:fileName应该是您的测试函数的参数之一。
这将导致为目录中的每个文件执行测试用例,测试用例将类似于
TestFunc[File1]
TestFunc[File2]
TestFunc[File3]
.
.
等等..

关于python - 为目录中的每个文件运行 pytest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63210834/

相关文章:

python - 将 python-dotenv 与 pytest 一起使用的最佳方法,或者使用单独配置的 pytest 测试/开发环境的最佳方法

python - pytest - 测试流程顺序

python - python中字典的多键值查找

python - 数据迁移以替换文本字段中单词的实例?

python - HTTP 404 - 无法将 url 参数传递给 flask 路由

python - ImportError:没有名为 bs4 的模块(BeautifulSoup)

python - 从 Python 中编译的正则表达式中提取命名组正则表达式模式

python - Pandas 用不同大小的 block 替换行 block

python - 使用Python-Flask自动创建路由和html文件

python - 如何将脚本作为pytest测试运行