前言
在真正测试时,我们时常需要用到不同的参数进行传参,如何实现呢?pytest框架 @pytest.mark.parametrize 的方法可以很轻松实现。
@pytest.mark.parametrize
应用场景:比如测试登录场景的时候,需要输入不同的测试账号和测试密码,实际上我们不可能写若干个测试用例去测试登录,最好是保持用例不变只变参数,
该方法就是实现这种场景的最佳选择。
1 #测试demo
2 # content of test_expectation.py
3 import pytest
4 #test_input,expected 就是后面对应的参数
5 @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
6 def test_eval(test_input, expected):
7 assert eval(test_input) == expected
运行结果:
1 $ pytest 2 =========================== test session starts ============================ 3 platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-0.x.y 4 cachedir: $PYTHON_PREFIX/.pytest_cache 5 rootdir: $REGENDOC_TMPDIR 6 collected 3 items 7 8 test_expectation.py ..F [100%] 9 10 ================================= FAILURES ================================= 11 ____________________________ test_eval[6*9-42] _____________________________ 12 13 test_input = '6*9', expected = 42 14 15 @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)]) 16 def test_eval(test_input, expected): 17 > assert eval(test_input) == expected 18 E AssertionError: assert 54 == 42 19 E + where 54 = eval('6*9') 20 21 test_expectation.py:6: AssertionError 22 ========================= short test summary info ========================== 23 FAILED test_expectation.py::test_eval[6*9-42] - AssertionError: assert 54... 24 ======================= 1 failed, 2 passed in 0.12s ========================
pytest.mark.xfail
表示将该用例标记成xfail失败,并且该用例中的后续代码不会执行。一般这种场景可以用于已经知道此条用例会失败,或者功能未实现
这样可以避免代码重复运行,提高效率。
1 # content of test_expectation.py 2 import pytest 3 4 5 @pytest.mark.parametrize( 6 "test_input,expected", 7 [("3+5", 8), ("2+4", 6), pytest.param("6*9", 42, marks=pytest.mark.xfail)], 8 ) 9 def test_eval(test_input, expected): 10 assert eval(test_input) == expected
运行结果:
1 $ pytest 2 =========================== test session starts ============================ 3 platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-0.x.y 4 cachedir: $PYTHON_PREFIX/.pytest_cache 5 rootdir: $REGENDOC_TMPDIR 6 collected 3 items 7 8 test_expectation.py ..x [100%] 9 10 ======================= 2 passed, 1 xfailed in 0.12s =======================
两组参数时,就可以组成排列组合的几种结果, x=0/y=2
, x=1/y=2
, x=0/y=3
, and x=1/y=3
四种情况。
1 import pytest 2 3 4 @pytest.mark.parametrize("x", [0, 1]) 5 @pytest.mark.parametrize("y", [2, 3]) 6 def test_foo(x, y): 7 pass
运行结果:
collecting ... collected 4 items testdemo.py::test_foo[2-0] testdemo.py::test_foo[2-1] testdemo.py::test_foo[3-0] testdemo.py::test_foo[3-1] ============================== 4 passed in 0.06s ============================== Process finished with exit code 0 PASSED [ 25%]PASSED
关注个人公众号:测试开发进阶之路