1、pytest 是 python 的第三方单元测试框架,比自带 unittest 更简洁和高效
2、安装 pytest
pip install pytest
3、验证 pytest 是否安装成功
pip show pytest
4、使用 pytest 执行测试需要遵行的规则
-
.py 测试文件必须以 test_ 开头(或者以 _test 结尾)
-
测试类必须以 Test 开头,并且不能有 init 方法
-
测试方法必须以 test_ 开头
-
断言必须使用 assert,pytest 中没有自带的断言方法
5、实例讲解
- demo1
- demo1 发现结果中没有用例的执行打印结果
# test_demo.py
import pytest
def test_01():
print("test_01")
def test_02():
print("test_02")
def test_03():
print("test_03")
if __name__ == '__main__':
pytest.main()
# 结果如下
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: D:\work_doc\CodeFile\practice\pytest_demo
plugins: html-2.1.1, metadata-1.9.0
collected 3 items
test_demo1.py ... [100%]
============================== 3 passed in 0.05s ==============================
Process finished with exit code 0
- demo2
- demo2 中在 main() 中加入 ["-s"],结果中就可以展示打印结果
import pytest
def test_01():
print("test_01")
def test_02():
print("test_02")
def test_03():
print("test_03")
if __name__ == '__main__':
pytest.main(["-s"]) # 在 main() 中加入 ["-s"]
# 结果如下
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: D:\work_doc\CodeFile\practice\pytest_demo
plugins: html-2.1.1, metadata-1.9.0
collected 3 items
test_demo1.py test_01
.test_02
.test_03
.
============================== 3 passed in 0.02s ==============================
Process finished with exit code 0
- demo3
- 运行指定的用例文件
# test_demo1.py
def test_01():
print("test_01")
def test_02():
print("test_02")
def test_03():
print("test_03")
# run_all.py
import pytest
if __name__ == '__main__':
pytest.main(["D:/test_demo1.py"])
# 结果如下
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: D:\
plugins: html-2.1.1, metadata-1.9.0
collected 3 items
test_demo1.py ... [100%]
============================== 3 passed in 0.01s ==============================
Process finished with exit code 0
- demo4
- 运行指定目录下的用例文件
# demo1/test_demo1.py demo1 目录下的 test_demo1.py 文件
def test_01():
print("test_01")
def test_02():
print("test_02")
def test_03():
print("test_03")
# demo2/test_demo2.py demo2 目录下的 test_demo2.py 文件
def test_04():
print("test_04")
def test_05():
print("test_05")
def test_06():
print("test_06")
import pytest
if __name__ == '__main__':
pytest.main(["D:/demo1","D:/demo2"]) # 指定 D:/demo1 和 D:/demo2 目录
# 结果如下
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: D:
plugins: html-2.1.1, metadata-1.9.0
collected 6 items
demo1\test_demo1.py ... [ 50%]
demo2\test_demo2.py ... [100%]
============================== 6 passed in 0.04s ==============================
Process finished with exit code 0
来源:oschina
链接:https://my.oschina.net/u/4340499/blog/4277063