pytest--测试的参数化

导言

实际测试过程中,测试用例可能需要支持多种场景,可以把场景强相关的部分抽象为参数,通过对参数赋值来驱动用例的执行。参数化对的行为表现在不同的层级上:

  • fixture的参数化
  • 测试用例的参数化:使用@pytest.mark.parametrize可以在测试用例、测试类甚至是测试模块中标记多个参数或者fixture的组合
  • 也可以通过pytest_generate_tests这个钩子方法自定义参数化的方案。源码:
#_pytest/python.py
def parametrize(self, argnames, argvalues, indirect=False, ids = None,scope = None)

参数分析如下:

  • argnames:一个逗号分隔的字符串或者一个元组、列表,表明指定对的参数名。对于argnames,还是有一些限制:

  • 只能是被标记对象入参的子集
    @pytest.mark.parametrize('input, expected', [(1,2)])
    def test_sample(input):
    assert input + 1 =1

  • 不能是被标记对象入参中,定义了默认值的参数:

@pytest.mark.parametrize('innput, expected' , [(1,2)])
def test_sample(input, expected = 2)
		assert input +  1 == expected

虽然test_sample声明了expected参数,但是也赋予了一个默认值,如果我们在标记中强行声明,会得到错误:

In test_sample: function already takes an argument 'expected' with a default value
  • 会覆盖同名的fixture
import pytest
@pytest.fixture()
def excepted():
    return 1

@pytest.mark.parametrize('input, excepted', [(1,2)])
def test_sample(input , excepted):
    assert input + 1 == excepted

测试结果:

D:\pytest\exercise\chapter11>pytest test_mark.py
================================================================= test session starts ==================================================================
platform win32 -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: D:\pytest\exercise\chapter11
plugins: allure-pytest-2.8.36
collected 1 item                                                                                                                                        

test_mark.py .                                                                                                                                    [100%]

================================================================== 1 passed in 0.04s ===================================================================

test_sample标记中对的excepted(2)覆盖了同名对的fixture excepted(1),所以测试用例通过。

  • argvalues:一个可迭代对象,表明对argnames参数的赋值,具体有以下几种情况:
  • 如果argnames包含多个参数,那么argvalues的迭代返回元素必须是可度量的(即支持len()方法),并且长度和argnames声明参数对的个数相等,所以它可以是元组、列表、集合等,表明所有入参的实参:
@pytest.mark.parametrize('input,excepted',[(1,2),[2,3]],set([3,4]))
def test_sample(input,excepted):
    assert input + 1 == excepted

测试结果:

D:\pytest\exercise\chapter11>pytest test_mark.py
================================================================= test session starts ==================================================================
platform win32 -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: D:\pytest\exercise\chapter11
plugins: allure-pytest-2.8.36
collected 0 items / 1 error                                                                                                                             

======================================================================== ERRORS ============================&#

你可能感兴趣的:(pytest)