4.2 参数化应用
1. 单一参数化 / 多参数化
# content of test_mark_parametrize.py mport pytest @pytest.mark.parametrize("test_case", [1, 2, 3, 'orange', 'apple']) def test_string(test_case): # 单一参数化 print(f"\n我们的测试数据:{test_case}") @pytest.mark.parametrize("test_input, expected", [("3 + 5", 8), ("2 + 5", 7), ("7 * 5", 30), ]) def test_eval(test_input, expected): # 多参数化 # eval将字符串str当成有效的表达式来求值并返回计算结果 assert eval(test_input) == expected
2. 多个参数化
# content of test_multi.py """多个参数化,将会变成组合的形式,示例将产生 3*2 = 6 个组合""" import pytest @pytest.mark.parametrize('test_input', [1, 2, 3]) @pytest.mark.parametrize('test_output, expected', [(1, 2), (3, 4)]) def test_multi(test_input, test_output, expected): pass
3. pytestmark 实现参数化
# content of test_module.py import pytest # 通过对 pytestmark 赋值,参数化一个测试模块 pytestmark = pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)]) def test_module(test_input, expected): assert test_input + 1 == expected
4.4 argnames 参数
1. argnames 与测试方法中的参数关系
# 1) 测试方法未声明, mark.parametrize 中声明 # if run this only, report "function uses no argument 'expected' @pytest.mark.parametrize('input, expected', [(1, 2)]) def test_sample1(input): assert input + 1 == 1
# 2) 测试方法参数声明的范围小于 mark.parametrize 中声明的范围:parametrize 定义了 expected,又在方法入参中赋值 expected,将出错 # if run this only, report "function already takes an argument 'expected' with a default value" @pytest.mark.parametrize('input, expected', [(1, 2)]) def test_sample2(input, expected = 2): assert input + 1 == 1
# content of test_mark_param_sub.py import pytest @pytest.fixture def expected3(): return 2 # 3) test_sample3 没有定义 expected,test_sample3 的参数 expected3 可以从 fixture 中获取 @pytest.mark.parametrize('input3', [(1)]) def test_sample3(input3, expected3): assert input3 + 1 == expected3 @pytest.fixture def expected4(): return 2 # 4)parametrize() 的参数化值覆盖了 fixture 的值 @pytest.mark.parametrize('input4, expected4', [(1, 2), [2, 3], set([3, 4])]) def test_sample4(input4, expected4): assert input4 + 1 == expected4
4.5 argvalues 参数
1
2
标签:parametrize,--,Chapter4,DDT,expected,pytest,test,input,mark From: https://www.cnblogs.com/bruce-he/p/17966180