pytest动态生成测试方法

Nag*_*nan 10 python pytest python-unittest

嗨我如何动态生成测试方法列表或文件数量.假设我在json中有file1,file2和filen以及输入值.现在我需要为下面的多个值运行相同的测试,

class Test_File(unittest.TestCase):
    def test_$FILE_NAME(self):
        return_val = validate_data($FILE_NAME)
        assert return_val
Run Code Online (Sandbox Code Playgroud)

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

py.test test_rotate.py --tb=long --junit-xml=results.xml --html=results.html -vv
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

请告诉我如何指定py测试以在报告时动态生成test_came方法.

我期待本博客中提到的确切内容" http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases "

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

当我们使用如下夹具时,我得到的错误就像需要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) 
Run Code Online (Sandbox Code Playgroud)

当我执行上面的操作时,我收到以下错误,

 >               testMethod()
 E               TypeError: test_eval() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

ada*_*rsh 10

可能对您有所帮助.

然后你的测试类看起来像

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