python - pytest动态生成测试方法

标签 python pytest python-unittest

您好,我如何为列表或文件数量动态生成测试方法。 假设我有 file1、file2 和 filen,其输入值在 json 中。现在我需要对多个值运行相同的测试,如下所示,

class Test_File(unittest.TestCase):
    def test_$FILE_NAME(self):
        return_val = validate_data($FILE_NAME)
        assert return_val

我正在使用以下命令运行 py.test 以生成 html 和 junit 报告

py.test test_rotate.py --tb=long --junit-xml=results.xml --html=results.html -vv

目前我手动定义的方法如下,

def test_lease_file(self):
    return_val = validate_data(lease_file)
    assert return_val

def test_string_file(self):
    return_val = validate_data(string_file)
    assert return_val

 def test_data_file(self):
    return_val = validate_data(data_file)
    assert return_val

请告诉我如何指定 py test 在提供报告时动态生成 test_came 方法。

我很期待这个博客“http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases”中提到的内容

但是上面的博客使用了 unittest,如果我使用它,我将无法生成 html 和 junit 报告

当我们像下面这样使用 fixtures 时,我得到了它需要 2 个参数的错误,

test_case = []
class Memory_utlization(unittest.TestCase):
@classmethod
def setup_class(cls):
    fname = "test_order.txt"
    with open(fname) as f:
        content = f.readlines()
    file_names = []
    for i in content:
        file_names.append(i.strip())
    data = tuple(file_names)
    test_case.append(data)
    logging.info(test_case) # here test_case=[('dhcp_lease.json'),('dns_rpz.json'),]

@pytest.mark.parametrize("test_file",test_case)
def test_eval(self,test_file):
    logging.info(test_case) 

当我执行上面的命令时,出现以下错误,

 >               testMethod()
 E               TypeError: test_eval() takes exactly 2 arguments (1 given)

最佳答案

This可能会帮助你。

你的测试类看起来像

class Test_File():
    @pytest.mark.parametrize(
        'file', [
            (lease_file,),
            (string_file,),
            (data_file,)
        ]
    )
    def test_file(self, file):
        assert validate_data(file)

关于python - pytest动态生成测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35579875/

相关文章:

python - scipy.optimize.minimize,一次计算约束及其雅可比

python - Seaborn 箱线图单个箱间距

python - pytest 说当我不使用时找不到 fixture

python - 执行pytest时如何获取rootdir参数值

python - 一种在 setup() 中输出 pyunit 测试名称的方法

PyQt QTest 单击 QMenu

python - django-cacheops 不适用于南方

python - 如何从 feedparser 解析的 feed 文章中渲染 django 模板中的 html 内容

python - 类型错误 : missing 1 required positional argument while using pytest fixture

Python 单元测试和多线程