1.1 安装pytest
-
命令行执行以下命令
$ pip3 install -U pytest
-
检查版本
$ pytest --version This is pytest version 4.5.0, imported from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pytest.py
1.2 创建你的第一个测试用例
-
创建一个简单的测试方法
#test_sample.py def func(x): return x + 1 def test_a(): print("---test_a----") assert func(3) == 5 #断言失败 def test_b(): print("---test_b---") assert 1 #断言成功
-
执行一下
-
命令行模式
-
命令下执行
$ pytest -s test_sample.py
-
-
主函数模式
-
增加主函数
if __name__ == '__main__': pytest.main(["-s", "test_sample.py"]) #-s 表示支持控制台打印,如果不加,print 不会出现任何内容 #-q 安静模式,不打印信息
-
-
执行结果
============================= test session starts ============================== platform darwin -- Python 3.7.3, pytest-4.5.0, py-1.8.0, pluggy-0.11.0 rootdir: /Users/wuyanhong/PycharmProjects/Inter_AutoTest_W, inifile: pytest.ini plugins: rerunfailures-7.0, ordering-0.6, metadata-1.8.0, html-1.20.0, allure-pytest-2.6.4 collected 2 items test_sample.py ---test_a---- F---test_b--- . =================================== FAILURES =================================== ____________________________________ test_a ____________________________________ def test_a(): print("---test_a----") > assert func(3) == 5 # 断言失败 E assert 4 == 5 E + where 4 = func(3) test_sample.py:9: AssertionError ====================== 1 failed, 1 passed in 0.09 seconds ====================== Process finished with exit code 0
由于
func(3)
并不等于5
,这次测试返回了一个失败报告。- . 表示成功
-
-
如果需要更多信息,可以使用-v或–verbose
-
F 表示失败
Console参数介绍 - -v 用于显示每个测试函数的执行结果 - -q 只显示整体测试结果 - -s 用于显示测试函数中print()函数输出 - -x, --exitfirst, exit instantly on first error or failed test - -h 帮助
1.3 执行pytest测试
-
执行方法
-
py.test -q test_class.py py.test # run all tests below current dir py.test test_mod.py # run tests in module py.test somepath # run all tests below somepath py.test -k stringexpr # only run tests with names that match the # the "string expression", e.g. "MyClass and not method" # will select TestMyClass.test_something # but not TestMyClass.test_method_simple py.test test_mod.py::test_func # only run tests that match the "node ID", # e.g "test_mod.py::test_func" will select # only test_func in test_mod.py
-
如何执行多条测试?
- 测试文件以test_*.py开头或*_test.py结尾 - 测试类以Test开头,并且不能带有 __init__ 方法 - 测试函数以test_开头 - 断言使用基本的assert即可
-
pytest
会执行当前目录及子目录下所有test_*.py
及*_test.py
格式的文件 -
可以设置pytest.ini配置文件,自定义执行文件格式
addopts = -s # 当前目录下的scripts文件夹 -可自定义 testpaths = testcase # 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件 -可自定义 python_files = test_*.py # 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类 -可自定义 python_classes = Test_* # 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类内,以test_开头的方法 -可自定义 python_functions = test_*
-
-
兼容unittest.TestCase
-
- test_*.py or *_test.py files. - @unittest.skip style decorators; - setUp/tearDown; - setUpClass/tearDownClass; - setUpModule/tearDownModule;
来源:CSDN
作者:demon119
链接:https://blog.csdn.net/demon119/article/details/103714111