pytest参数化自定义测试用例标题

  pytest使用装饰器@pytest.mark.parametrize进行参数化后,在控制台或者测试报告中的测试用例标题都是以参数组合起来命名的,这样的标题看起来不太直观,我们想要展示我们自己定义的标题,这时候需要用到装饰器@pytest.mark.parametrize参数化的另外一个参数ids来实现。

没有使用ids之前:

# file_name: test_parametrize.py


import pytest


def return_user():
    return [('lwjnicole', '12345'), ('nicole', '123111')]


class Test_D:

    @pytest.mark.parametrize("username,password",return_user())
    def test_login(self, username, password):
        print("username = {}, password = {}".format(username, password))
        assert username == "lwjnicole"


if __name__ == '__main__':
    pytest.main(['-s', 'test_parametrize.py'])

运行结果:

pytest参数化自定义测试用例标题

  从结果中可以看到用例的标题是由所有参数组合而来的,这样看起来不怎么直观。

使用ids自定义测试用例标题:

# file_name: test_parametrize.py


import pytest


def return_user():
    return [('lwjnicole', '12345'), ('nicole', '123111')]


class Test_D:

    @pytest.mark.parametrize("username,password",
                             return_user(),
                             ids=[
                                 "login success",
                                 "login fail"
                             ])
    def test_login(self, username, password):
        print("username = {}, password = {}".format(username, password))
        assert username == "lwjnicole"


if __name__ == '__main__':
    pytest.main(['-s', 'test_parametrize.py'])

运行结果:

pytest参数化自定义测试用例标题

  从结果中可以看到用例的标题已经不再是各参数的组合了,而是我们在参数ids中定义的,这样我们就实现了测试用例标题的自定义。