pytest.mark.parametrize装饰器可以实现测试用例参数化。
需求:实现检查一定的输入和期望输出测试功能例子
import pytest @pytest.mark.parametrize("test_input, expected", [("2+3", 5), ("33+44", 77), ("2+100", 100) ]) def test_eval(test_input, expected): print("------开始用例-------") assert eval(test_input) == expected if __name__ == '__main__': pytest.main(["-s", "test_expectation.py"])
标记单个测试实例在参数化,例如使用内置的mark.xfail
import pytest @pytest.mark.parametrize("test_input, expected", [("2+3", 5), ("33+44", 77), pytest.param("2+100", 100, marks=pytest.mark.xfail) ]) def test_eval(test_input, expected): print("------开始用例-------") assert eval(test_input) == expected if __name__ == '__main__': pytest.main(["-s", "test_expectation2.py"])
运行结果:(当用例失败,显示xfailed)
test_expectation2.py ------开始用例------- .------开始用例------- .------开始用例------- x ======================2 passed, 1 xfailed in 0.15s ======================