pytest系列教程(1) 简介–The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries. 官网地址 https://docs.pytest.org/en/7.2.x/ 中文翻译地址 https://learning-pytest.readthedocs.io/zh/latest/doc/intro/getting-started.html 1.安装(python环境已安装,pip正常) python -m pip install pytest
2.创建你的第一个测试
# test_001.py
import pytest
def add(x):
return x + 1
def test_true():
assert add(9) == 10
def test_false():
assert add(8) == 4
if __name__ == "__main__":
pytest.main(['-vs', 'test_001.py'])
test_001.py::test_true PASSED
test_001.py::test_false FAILED
================================== FAILURES ===================================
_________________________________ test_false __________________________________
def test_false():
> assert add(8) == 4
E assert 9 == 4
E +9
E -4
test_001.py:13: AssertionError
- generated html file: file:///D:/workspaces/pytest_test/pytest_02/report.html -
=========================== short test summary info ===========================
FAILED test_001.py::test_false - assert 9 == 4
========================= 1 failed, 1 passed in 0.17s =========================
Process finished with exit code 0
注解 pytest 使用 . 标识测试成功(PASSED) pytest 使用 F 标识测试失败(FAILED) Pytest 支持多种从命令行运行和选择测试的方法及参数输入
if __name__ == '__main__':
# print('ok')
# (1)运行全部
pytest.main()
# os.system("allure generate ./temp -o ./allure-report --clean")
# (2)运行指定模块
# pytest.main(["-vs", "test_0001.py"])
# (3)运行指定文件夹(目录)
# pytest.main(["-vs", "../pytest_test"])
# (4)通过nodeid指定测试用例运行,nodeid = 模块名,分隔符,类名,方法名,函数名组成
# pytest.main(["-vs", "../pytest_test/test_0001.py::test_04"])
# (5)多线程或分布式运行测试用例
# pytest.main(["-vs", "../pytest_test/test_0001.py", "-n=2"])
# (6)失败用例重跑
# pytest.main(["-vs", "../pytest_test/test_0001.py", "--reruns=1"])
# (7)只要有一个用例错了,测试停止
# pytest.main(["-vs", "../pytest_test/test_0001.py", "-x"]) # 用的较少
# (8)出现2个用例失败就停止
# pytest.main(["-vs", "../pytest_test/test_0001.py", "--maxfail=2"]) # 用的较少
# (9)根据测试用例的部分字符串指定测试用例
# pytest.main(["-vs", "../pytest_test/test_0001.py", "-k=AA", ])
-s 表示输出调试信息,包括print打印信息 pytest -s ./pytest_1 或 pytest.main([‘-s’, ‘./pytest_1/test_login.py’]) -v 表示输出用例执行详细信息 -vs 表示既输出调试信息同时输出执行详细信息 -n [n] 支持多线程或者分布式运行测试用例 –reruns [n] 失败用例重跑 -x 只要存在失败用例则停止执行 –maxfail [n] 只要存在max个失败用例则停止执行 -k [xx] 根据测试用例的部分字符串执行用例 如:pytest test.py -k ‘关键字A or 关键字B’ –html [xx.html] 生成测试报告(需要先安装pytest-html) 如:pytest pytest-demp.py --html-./report.html
3.编写原则 pytest将在当前目录及其子目录中运行 test_.py 或 _test.py 形式的所有文件 pytest 可以很容易地创建一个包含多个测试的类: 可指定运行测试类下测试用例:python -m pytest -s test_001.py::setup_class 或 pytest.main([“-vs”, “…/pytest_test/test_001.py::test_04”])
# test_001.py
class TestDemo:
def setup_class(self):
print("这是一个setup_class")
def teardown_class(self):
print("这是一个teardown_class")
推荐阅读
发表评论