1. 程式人生 > 實用技巧 >Pytest的基本操作講解

Pytest的基本操作講解

前言

Python測試框架之前一直用的是unittest+HTMLTestRunner,聽到有人說pytest很好用,所以這段時間就看了看pytest文件,在這裡做個記錄。

官方文件介紹:

Pytest is a framework that makes building simple and scalable tests easy. Tests are expressive and readable—no boilerplate code required. Get started in minutes with a small unit test or complex functional test for your application or library.

pytest是一個非常成熟的全功能的Python測試框架,主要有以下幾個特點:

  • 簡單靈活,容易上手
  • 支援引數化
  • 能夠支援簡單的單元測試和複雜的功能測試,還可以用來做selenium/appnium等自動化測試、介面自動化測試(pytest+requests)
  • pytest具有很多第三方外掛,並且可以自定義擴充套件,比較好用的如pytest-selenium(整合selenium)、pytest-html(完美html測試報告生成)、pytest-rerunfailures(失敗case重複執行)、pytest-xdist(多CPU分發)等
  • 測試用例的skip和xfail處理
  • 可以很好的和jenkins整合
  • report框架----allure 也支援了pytest

1、pytest安裝

1.1安裝

pip install -U pytest

1.2驗證安裝

pytest --version # 會展示當前已安裝版本

1.3pytest文件

官方文件:https://docs.pytest.org/en/latest/contents.html

在pytest框架中,有如下約束:

所有的單測檔名都需要滿足test_*.py格式或*_test.py格式。
在單測檔案中,測試類以Test開頭,並且不能帶有init方法(注意:定義class時,需要以T開頭,不然pytest是不會去執行該class的)
在單測類中,可以包含一個或多個test_開頭的函式。
此時,在執行pytest命令時,會自動從當前目錄及子目錄中尋找符合上述約束的測試函式來執行。

1.4 Pytest執行方式

  1. # file_name: test_abc.py
  2. import pytest # 引入pytest包
  3. def test_a(): # test開頭的測試函式
  4. print("------->test_a")
  5. assert 1 # 斷言成功
  6. def test_b():
  7. print("------->test_b")
  8. assert 0 # 斷言失敗
  9. if __name__ == '__main__':
  10. pytest.main("-s test_abc.py") # 呼叫pytest的main函式執行測試

1.測試類主函式模式

  pytest.main("-s  test_abc.py")

2.命令列模式

  1. pytest 檔案路徑/測試檔名
  2. 例如:pytest ./test_abc.py

1.5PytestExit Code 含義清單

  • Exit code 0 所有用例執行完畢,全部通過
  • Exit code 1 所有用例執行完畢,存在Failed的測試用例
  • Exit code 2 使用者中斷了測試的執行
  • Exit code 3 測試執行過程發生了內部錯誤
  • Exit code 4 pytest 命令列使用錯誤
  • Exit code 5 未採集到可用測試用例檔案

1.6如何獲取幫助資訊

檢視 pytest 版本

pytest --version

顯示可用的內建函式引數

pytest --fixtures

通過命令列檢視幫助資訊及配置檔案選項

pytest --help

1.7控制測試用例執行

1.在第N個用例失敗後,結束測試執行

  1. pytest -x # 第01次失敗,就停止測試
  2. pytest --maxfail=2 # 出現2個失敗就終止測試

2.指定測試模組

pytest test_mod.py

3.指定測試目錄

pytest testing/

4.通過關鍵字表達式過濾執行

pytest -k "MyClass and not method"

這條命令會匹配檔名、類名、方法名匹配表示式的用例,這裡這條命令會執行 TestMyClass.test_something, 不會執行 TestMyClass.test_method_simple

5.通過 node id 指定測試用例

nodeid由模組檔名、分隔符、類名、方法名、引數構成,舉例如下:
執行模組中的指定用例

pytest test_mod.py::test_func

執行模組中的指定方法

ytest test_mod.py::TestClass::test_method

6.通過標記表示式執行

pytest -m slow

這條命令會執行被裝飾器 @pytest.mark.slow 裝飾的所有測試用例

7.通過包執行測試

pytest --pyargs pkg.testing

這條命令會自動匯入包 pkg.testing,並使用該包所在的目錄,執行下面的用例。

1.8 多程序執行cases

當cases量很多時,執行時間也會變的很長,如果想縮短指令碼執行的時長,就可以用多程序來執行。

安裝pytest-xdist:

pip install -U pytest-xdist

執行模式:

pytest test_se.py -n NUM

其中NUM填寫併發的程序數。

1.9 重試執行cases

在做介面測試時,有事會遇到503或短時的網路波動,導致case執行失敗,而這並非是我們期望的結果,此時可以就可以通過重試執行cases的方式來解決。

安裝pytest-rerunfailures:

pip install -U pytest-rerunfailures

執行模式:

pytest test_se.py --reruns NUM

NUM填寫重試的次數。

1.10 顯示print內容

在執行測試指令碼時,為了除錯或列印一些內容,我們會在程式碼中加一些print內容,但是在執行pytest時,這些內容不會顯示出來。如果帶上-s,就可以顯示了。

執行模式:

pytest test_se.py -s

另外,pytest的多種執行模式是可以疊加執行的,比如說,你想同時執行4個程序,又想打印出print的內容。可以用:

pytest test_se.py -s -n 4

2.Pytest的setup和teardown函式

1.setup和teardown主要分為:模組級,類級,功能級,函式級。
2.存在於測試類內部
程式碼示例:

  • 函式級別setup()/teardown()

運行於測試方法的始末,即:執行一次測試函式會執行一次setup和teardown

  1. import pytest
  2. class Test_ABC:
  3. # 函式級開始
  4. def setup(self):
  5. print("------->setup_method")
  6. # 函式級結束
  7. def teardown(self):
  8. print("------->teardown_method")
  9. def test_a(self):
  10. print("------->test_a")
  11. assert 1
  12. def test_b(self):
  13. print("------->test_b")
  14. if __name__ == '__main__':
  15. pytest.main("-s test_abc.py")
  1. 執行結果:
  2. test_abc.py
  3. ------->setup_method # 第一次 setup()
  4. ------->test_a
  5. .
  6. ------->teardown_method # 第一次 teardown()
  7. ------->setup_method # 第二次 setup()
  8. ------->test_b
  9. .
  10. ------->teardown_method # 第二次 teardown()
  • 2.2.類級別

運行於測試類的始末,即:在一個測試內只執行一次setup_class和teardown_class,不關心測試類內有多少個測試函式。
程式碼示例:

  1. import pytest
  2. class Test_ABC:
  3. # 測試類級開始
  4. def setup_class(self):
  5. print("------->setup_class")
  6. # 測試類級結束
  7. def teardown_class(self):
  8. print("------->teardown_class")
  9. def test_a(self):
  10. print("------->test_a")
  11. assert 1
  12. def test_b(self):
  13. print("------->test_b")
  14. if __name__ == '__main__':
  15. pytest.main("-s test_abc.py")
  1. 執行結果:
  2. test_abc.py
  3. ------->setup_class # 第一次 setup_class()
  4. ------->test_a
  5. .
  6. ------->test_b
  7. F
  8. ------->teardown_class # 第一次 teardown_class()

3.Pytest配置檔案

pytest的配置檔案通常放在測試目錄下,名稱為pytest.ini,命令列執行時會使用該配置檔案中的配置.

  1. #配置pytest命令列執行引數
  2. [pytest]
  3. addopts = -s ... # 空格分隔,可新增多個命令列引數 -所有引數均為外掛包的引數配置測試搜尋的路徑
  4. testpaths = ./scripts # 當前目錄下的scripts資料夾 -可自定義
  5. #配置測試搜尋的檔名稱
  6. python_files = test*.py
  7. #當前目錄下的scripts資料夾下,以test開頭,以.py結尾的所有檔案 -可自定義
  8. 配置測試搜尋的測試類名
  9. python_classes = Test_*
  10. #當前目錄下的scripts資料夾下,以test開頭,以.py結尾的所有檔案中,以Test開頭的類 -可自定義
  11. 配置測試搜尋的測試函式名
  12. python_functions = test_*
  13. #當前目錄下的scripts資料夾下,以test開頭,以.py結尾的所有檔案中,以Test開頭的類內,以test_開頭的方法 -可自定義

4 Pytest常用外掛

外掛列表網址:https://plugincompat.herokuapp.com
包含很多外掛包,大家可依據工作的需求選擇使用。

4.1 前置條件:

1.檔案路徑:

  1. - Test_App
  2. - - test_abc.py
  3. - - pytest.ini

2.pyetst.ini配置檔案內容:

  1. [pytest]
  2. # 命令列引數
  3. addopts = -s
  4. # 搜尋檔名
  5. python_files = test_*.py
  6. # 搜尋的類名
  7. python_classes = Test_*
  8. #搜尋的函式名
  9. python_functions = test_*

4.2 Pytest測試報告

pytest-HTML是一個外掛,pytest用於生成測試結果的HTML報告。相容Python 2.7,3.6

安裝方式:pip install pytest-html

pip install pytest-html

通過命令列方式,生成xml/html格式的測試報告,儲存於使用者指定路徑。外掛名稱:pytest-html

使用方法: 命令列格式:pytest --html=使用者路徑/report.html

示例:

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. def test_a(self):
  8. print("------->test_a")
  9. assert 1
  10. def test_b(self):
  11. print("------->test_b")
  12. assert 0 # 斷言失敗```
  13. 執行方式:
  14. 1.修改Test_App/pytest.ini檔案,新增報告引數,即:addopts = -s --html=./report.html
  15. # -s:輸出程式執行資訊
  16. # --html=./report.html 在當前目錄下生成report.html檔案
  17. ️ 若要生成xml檔案,可將--html=./report.html 改成 --html=./report.xml
  18. 2.命令列進入Test_App目錄
  19. 3.執行命令: pytest
  20. 執行結果:
  21. 1.在當前目錄會生成assets資料夾和report.html檔案

5.pytest的高階用法(一)

前置條件:

1.檔案路徑:

  1. Test_App
  2. - - test_abc.py
  3. - - pytest.ini

2.pyetst.ini配置檔案內容:

  1. [pytest]
  2. 命令列引數
  3. addopts = -s
  4. 搜尋檔名
  5. python_files = test*.py
  6. 搜尋的類名
  7. python_classes = Test*
  8. 搜尋的函式名
  9. python_functions = test_*

5.1pytest之fixture

fixture修飾器來標記固定的工廠函式,在其他函式,模組,類或整個工程呼叫它時會被啟用並優先執行,通常會被用於完成預置處理和重複操作。

方法:fixture(scope="function", params=None, autouse=False, ids=None, name=None)
常用引數:

  1. scope:被標記方法的作用域
  2. function" (default):作用於每個測試方法,每個test都執行一次
  3. "class":作用於整個類,每個class的所有test只執行一次
  4. "module":作用於整個模組,每個module的所有test只執行一次
  5. "session:作用於整個session(慎用),每個session只執行一次
  6. params:(list型別)提供引數資料,供呼叫標記方法的函式使用
  7. autouse:是否自動執行,預設為False不執行,設定為True自動執行

5.2fixture第一個例子(通過引數引用)

示例:

  1. class Test_ABC:
  2. @pytest.fixture()
  3. def before(self):
  4. print("------->before")
  5. def test_a(self,before): # ️ test_a方法傳入了被fixture標識的函式,已變數的形式
  6. print("------->test_a")
  7. assert 1
  8. if __name__ == '__main__':
  9. pytest.main("-s test_abc.py")
  10. 執行結果:
  11. test_abc.py
  12. ------->before # 發現before會優先於測試函式執行
  13. ------->test_a
  14. .

5.3.fixture第二個例子(通過函式引用)

示例:

  1. import pytest
  2. @pytest.fixture() # fixture標記的函式可以應用於測試類外部
  3. def before():
  4. print("------->before")
  5. @pytest.mark.usefixtures("before")
  6. class Test_ABC:
  7. def setup(self):
  8. print("------->setup")
  9. def test_a(self):
  10. print("------->test_a")
  11. assert 1
  12. if __name__ == '__main__':
  13. pytest.main("-s test_abc.py")
  14. 執行結果:
  15. test_abc.py
  16. ------->before # 發現before會優先於測試類執行
  17. ------->setup
  18. ------->test_a
  19. .

5.4.fixture第三個例子(預設設定為執行)

示例:

  1. import pytest
  2. @pytest.fixture(autouse=True) # 設定為預設執行
  3. def before():
  4. print("------->before")
  5. class Test_ABC:
  6. def setup(self):
  7. print("------->setup")
  8. def test_a(self):
  9. print("------->test_a")
  10. assert 1
  11. if __name__ == '__main__':
  12. pytest.main("-s test_abc.py")
  13. 執行結果:
  14. test_abc.py
  15. ------->before # 發現before自動優先於測試類執行
  16. ------->setup
  17. ------->test_a
  18. .

5.5.fixture第四個例子(設定作用域為function)

示例:

  1. import pytest
  2. @pytest.fixture(scope='function',autouse=True) # 作用域設定為function,自動執行
  3. def before():
  4. print("------->before")
  5. class Test_ABC:
  6. def setup(self):
  7. print("------->setup")
  8. def test_a(self):
  9. print("------->test_a")
  10. assert 1
  11. def test_b(self):
  12. print("------->test_b")
  13. assert 1
  14. if __name__ == '__main__':
  15. pytest.main("-s test_abc.py")
  16. 執行結果:
  17. test_abc.py
  18. ------->before # 執行第一次
  19. ------->setup
  20. ------->test_a
  21. .------->before # 執行第二次
  22. ------->setup
  23. ------->test_b
  24. .

5.6.fixture第五個例子(設定作用域為class)

示例:

  1. import pytest
  2. @pytest.fixture(scope='class',autouse=True) # 作用域設定為class,自動執行
  3. def before():
  4. print("------->before")
  5. class Test_ABC:
  6. def setup(self):
  7. print("------->setup")
  8. def test_a(self):
  9. print("------->test_a")
  10. assert 1
  11. def test_b(self):
  12. print("------->test_b")
  13. assert 1
  14. if __name__ == '__main__':
  15. pytest.main("-s test_abc.py")
  16. 執行結果:
  17. test_abc.py
  18. ------->before # 發現只執行一次
  19. ------->setup
  20. ------->test_a
  21. .
  22. ------->setup
  23. ------->test_b
  24. .

5.7.fixture第六個例子(返回值)

示例一:

  1. import pytest
  2. @pytest.fixture()
  3. def need_data():
  4. return 2 # 返回數字2
  5. class Test_ABC:
  6. def test_a(self,need_data):
  7. print("------->test_a")
  8. assert need_data != 3 # 拿到返回值做一次斷言
  9. if __name__ == '__main__':
  10. pytest.main("-s test_abc.py")
  11. 執行結果:
  12. test_abc.py
  13. ------->test_a
  14. .
  15. ``

示例二:

  1. import pytest
  2. @pytest.fixture(params=[1, 2, 3])
  3. def need_data(request): # 傳入引數request 系統封裝引數
  4. return request.param # 取列表中單個值,預設的取值方式
  5. class Test_ABC:
  6. def test_a(self,need_data):
  7. print("------->test_a")
  8. assert need_data != 3 # 斷言need_data不等於3
  9. if __name__ == '__main__':
  10. pytest.main("-s test_abc.py")
  11. 執行結果:
  12. # 可以發現結果運行了三次
  13. test_abc.py
  14. 1
  15. ------->test_a
  16. .
  17. 2
  18. ------->test_a
  19. .
  20. 3
  21. ------->test_a
  22. F

6.Pytest高階用法(二)

前置條件:

1.檔案路徑:

  1. - Test_App
  2. - - test_abc.py
  3. - - pytest.ini

2.pyetst.ini配置檔案內容:

  1. [pytest]
  2. 命令列引數
  3. addopts = -s
  4. 搜尋檔名
  5. python_files = test_*.py
  6. 搜尋的類名
  7. python_classes = Test_*
  8. 搜尋的函式名
  9. python_functions = test_*

6.1.跳過測試函式

  1. 根據特定的條件,不執行標識的測試函式.
  2. 方法:
  3. skipif(condition, reason=None)
  4. 引數:
  5. condition:跳過的條件,必傳引數
  6. reason:標註原因,必傳引數
  7. 使用方法:
  8. @pytest.mark.skipif(condition, reason="xxx")

示例:

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. def test_a(self):
  8. print("------->test_a")
  9. assert 1
  10. @pytest.mark.skipif(condition=2>1,reason = "跳過該函式") # 跳過測試函式test_b
  11. def test_b(self):
  12. print("------->test_b")
  13. assert 0
  14. 執行結果:
  15. test_abc.py
  16. ------->setup_class
  17. ------->test_a #只執行了函式test_a
  18. .
  19. ------->teardown_class
  20. s # 跳過函式```

6.2 標記為預期失敗函式

  1. 標記測試函式為失敗函式
  2. 方法:
  3. xfail(condition=None, reason=None, raises=None, run=True, strict=False)
  4. 常用引數:
  5. condition:預期失敗的條件,必傳引數
  6. reason:失敗的原因,必傳引數
  7. 使用方法:
  8. @pytest.mark.xfail(condition, reason="xx")

示例:

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. def test_a(self):
  8. print("------->test_a")
  9. assert 1
  10. @pytest.mark.xfail(2 > 1, reason="標註為預期失敗") # 標記為預期失敗函式test_b
  11. def test_b(self):
  12. print("------->test_b")
  13. assert 0
  14. 執行結果:
  15. test_abc.py
  16. ------->setup_class
  17. ------->test_a
  18. .
  19. ------->test_b
  20. ------->teardown_class
  21. x # 失敗標記

6.3 函式資料引數化

  1. 方便測試函式對測試屬於的獲取。
  2. 方法:
  3. parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)
  4. 常用引數:
  5. argnames:引數名
  6. argvalues:引數對應值,型別必須為list
  7. 當引數為一個時格式:[value]
  8. 當引數個數大於一個時,格式為:[(param_value1,param_value2.....),(param_value1,param_value2.....)]
  9. 使用方法:
  10. @pytest.mark.parametrize(argnames,argvalues)
  11. ️ 引數值為N個,測試方法就會執行N次

單個引數示例:

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  1. @pytest.mark.parametrize("a",[3,6]) # a引數被賦予兩個值,函式會執行兩遍
  2. def test_a(self,a): # 引數必須和parametrize裡面的引數一致
  3. print("test data:a=%d"%a)
  4. assert a%3 == 0
  5. 執行結果:
  6. test_abc.py
  7. ------->setup_class
  8. test data:a=3 # 執行第一次取值a=3
  9. .
  10. test data:a=6 # 執行第二次取值a=6
  11. .
  12. ------->teardown_class

多個引數示例:

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  1. @pytest.mark.parametrize("a,b",[(1,2),(0,3)]) # 引數a,b均被賦予兩個值,函式會執行兩遍
  2. def test_a(self,a,b): # 引數必須和parametrize裡面的引數一致
  3. print("test data:a=%d,b=%d"%(a,b))
  4. assert a+b == 3
  5. 執行結果:
  6. test_abc.py
  7. ------->setup_class
  8. test data:a=1,b=2 # 執行第一次取值 a=1,b=2
  9. .
  10. test data:a=0,b=3 # 執行第二次取值 a=0,b=3
  11. .
  12. ------->teardown_class

函式返回值型別示例:

  1. import pytest
  2. def return_test_data():
  3. return [(1,2),(0,3)]
  4. class Test_ABC:
  5. def setup_class(self):
  6. print("------->setup_class")
  7. def teardown_class(self):
  8. print("------->teardown_class")
  1. @pytest.mark.parametrize("a,b",return_test_data()) # 使用函式返回值的形式傳入引數值
  2. def test_a(self,a,b):
  3. print("test data:a=%d,b=%d"%(a,b))
  4. assert a+b == 3
  5. 執行結果:
  6. test_abc.py
  7. ------->setup_class
  8. test data:a=1,b=2 # 執行第一次取值 a=1,b=2
  9. .
  10. test data:a=0,b=3 # 執行第二次取值 a=0,b=3
  11. .
  12. ------->teardown_class

6.4修改 Python traceback 輸出

  1. pytest --showlocals # show local variables in tracebacks
  2. pytest -l # show local variables (shortcut)
  3. pytest --tb=auto # (default) 'long' tracebacks for the first and last
  4. # entry, but 'short' style for the other entries
  5. pytest --tb=long # exhaustive, informative traceback formatting
  6. pytest --tb=short # shorter traceback format
  7. pytest --tb=line # only one line per failure
  8. pytest --tb=native # Python standard library formatting
  9. pytest --tb=no # no traceback at all

--full-trace引數會列印更多的錯誤輸出資訊,比引數 --tb=long 還多,即使是 Ctrl+C 觸發的錯誤,也會打印出來

6.5 執行失敗的時候跳轉到 PDB

執行用例的時候,跟引數 --pdb,這樣失敗的時候,每次遇到失敗,會自動跳轉到 PDB

  1. pytest --pdb # 每次遇到失敗都跳轉到 PDB
  2. pytest -x --pdb # 第一次遇到失敗就跳轉到 PDB,結束測試執行
  3. pytest --pdb --maxfail=3 # 只有前三次失敗跳轉到 PDB

6.6 設定斷點

在用例指令碼中加入如下python程式碼,pytest會自動關閉執行輸出的抓取,這裡,其他test指令碼不會受到影響,帶斷點的test上一個test正常輸出

 import pdb; pdb.set_trace()

6.7 獲取用例執行效能資料

獲取最慢的10個用例的執行耗時

pytest --durations=10

6.8 生成 JUnitXML 格式的結果檔案

這種格式的結果檔案可以被Jenkins或其他CI工具解析

pytest --junitxml=path

6.9禁用外掛

例如,關閉 doctest 外掛

pytest -p no:doctest

6.10 從Python程式碼中呼叫pytest

  1. pytest.main() # 基本用法
  2. pytest.main(['-x', 'mytestdir']) # 傳入配置引數
  3. // 指定自定義的或額外的外掛
  4. # content of myinvoke.py
  5. import pytest
  6. class MyPlugin(object):
  7. def pytest_sessionfinish(self):
  8. print("*** test run reporting finishing")
  9. pytest.main(["-qq"], plugins=[MyPlugin()])

6.11 測試指令碼遷移後快速部署包含pytest的virtualenv

例如你從Gitlab倉庫裡clone了專案組的刀刀同學編寫的測試指令碼到你自己的電腦裡,你想修改些東西,並除錯,咋辦?可以通過下面的操作快速建立 VirtualEnv

  1. cd <repository>
  2. pip install -e .

This will set up a symlink to your code in site-packages, allowing you to edit your code while
your tests run against it as if it were installed.
Setting up your project in development mode lets you avoid having to reinstall every time you want to run your tests,
and is less brittle than mucking about with sys.path to point your tests at local code.
Also consider using tox

遇到的問題:

問題:
pytest可以輸出覆蓋率的html報告

使用命令如下:

  1. pytest -vv --cov=./ --cov-report=html
  2. open htmlcov/index.html

有可能遇到報錯:

  1. (venv) zhangxiaofans-MacBook-Pro:mgap-mendel joe$ pytest --cov-report=html
  2. usage: pytest [options] [file_or_dir] [file_or_dir] [...]
  3. pytest: error: unrecognized arguments: --cov-report=html
  4. inifile: None
  5. rootdir: /Users/joe/workspace/platform/mgap-mendel/mgap-mendel

原因:
缺少pytest cov的包

解決方法

pip install pytest-cov