官網:https://docs.pytest.org/en/latest/
pytest幫你寫出更好的程序
1、An example of a simple test:(一個簡單的例子),命名為test_pytest1.py
1 def funx(x): 2 return x + 1 3 4 5 def test_answer(): 6 assert funx(2) == 5
運行:
- 進入python腳本路徑:pytest test_pytest1.py
root@localhost:/home/ranxf/Python3單元測試/demo# pytest test_pytest1.py
============================= test session starts ==============================
platform linux -- Python 3.5.2, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /home/ranxf/Python3單元測試/demo, inifile:
collected 1 item
test_pytest1.py F
=================================== FAILURES ===================================
_________________________________ test_answer __________________________________
def test_answer():
> assert funx(2) == 5
E assert 3 == 5
E + where 3 = funx(2)
test_pytest1.py:8: AssertionError
=========================== 1 failed in 0.02 seconds ===========================
- 進入python腳本路徑:pytest -q test_pytest1.py(加一個參數-q),運行結果:
root@localhost:/home/ranxf/Python3單元測試/demo# pytest -q test_pytest1.py
F
=================================== FAILURES ===================================
_________________________________ test_answer __________________________________
def test_answer():
> assert funx(2) == 5
E assert 3 == 5
E + where 3 = funx(2)
test_pytest1.py:8: AssertionError
1 failed in 0.02 seconds
兩種運行結果有一點差異,就是少了一些版本信息。
3、一個測試類中創建多個測試用例:

1 # 一個測試類種創建多個測試用例 2 3 4 class TestClass: 5 def test_one(self): 6 x = "this" 7 assert "s" in x 8 9 def test_two(self): 10 x = "hello" 11 assert x == "hi"
4、pytest同樣可以提供main()函數來執行測試用例:
目錄結構:
"""
pytest中同樣提供了main() 來函數來執行測試用例。
pytest/
├── test_pytest1.py
├── test_pytest2.py
└── test_main.py
"""
注:主函數中的文件名只能是test_main.py(如果改為test_pytest3這種格式,將不會遍歷執行同路徑的其他用例)
import pytest def test_main(): assert 5 != 5 if __name__ == "__main__": # pytest.main() # 遍歷相同目錄下的所以test開頭的用例 # pytest.main("-q test_main.py") # 指定測試文件 pytest.main("/root/Documents/python3_1000/1000/python3_pytest") # 指定測試目錄
5、pytest生成Html格式的測試報告:
python3 -m pytest test_main.py --html=report/test_main.html