Python測試框架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運行方式

 # file_name: test_abc.py
 import pytest # 引入pytest包
 def test_a(): # test開頭的測試函數
     print("------->test_a")
     assert 1 # 斷言成功
 def test_b():
     print("------->test_b")
     assert 0 # 斷言失敗
 if __name__ == '__main__':
        pytest.main("-s  test_abc.py") # 調用pytest的main函數執行測試

1.測試類主函數模式

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

2.命令行模式

  pytest 文件路徑/測試文件名
  例如:pytest ./test_abc.py

1.5 Pytest Exit 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個用例失敗後,結束測試執行

pytest -x                    # 第01次失敗,就停止測試
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

import pytest
class Test_ABC:
  # 函數級開始
  def setup(self):
      print("------->setup_method")
  # 函數級結束
  def teardown(self):
      print("------->teardown_method")
  def test_a(self):
      print("------->test_a")
      assert 1
  def test_b(self):
      print("------->test_b")
if __name__ == '__main__':
              pytest.main("-s  test_abc.py")
執行結果:
  test_abc.py 
  ------->setup_method # 第一次 setup()
  ------->test_a
  .
  ------->teardown_method # 第一次 teardown()
  ------->setup_method # 第二次 setup()
  ------->test_b
  .
          ------->teardown_method # 第二次 teardown()

類級別

運行於測試類的始末,即:在一個測試內隻運行一次setup_class和teardown_class,不關心測試類內有多少個測試函數。

代碼示例:

import pytest
class Test_ABC:
   # 測試類級開始
   def setup_class(self):
       print("------->setup_class")
   # 測試類級結束
   def teardown_class(self):
       print("------->teardown_class")
   def test_a(self):
       print("------->test_a")
       assert 1
   def test_b(self):
       print("------->test_b")
          if __name__ == '__main__':
              pytest.main("-s  test_abc.py")
執行結果:
  test_abc.py 
  ------->setup_class # 第一次 setup_class()
  ------->test_a
  .
  ------->test_b
  F 
          ------->teardown_class # 第一次 teardown_class()

3.Pytest配置文件

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

#配置pytest命令行運行參數
   [pytest]
    addopts = -s ... # 空格分隔,可添加多個命令行參數 -所有參數均為插件包的參數配置測試搜索的路徑
    testpaths = ./scripts  # 當前目錄下的scripts文件夾 -可自定義
#配置測試搜索的文件名稱
    python_files = test*.py 
#當前目錄下的scripts文件夾下,以test開頭,以.py結尾的所有文件 -可自定義
配置測試搜索的測試類名
    python_classes = Test_*  
   #當前目錄下的scripts文件夾下,以test開頭,以.py結尾的所有文件中,以Test開頭的類 -可自定義
配置測試搜索的測試函數名
    python_functions = test_*
#當前目錄下的scripts文件夾下,以test開頭,以.py結尾的所有文件中,以Test開頭的類內,以test_開頭的方法 -可自定義
 

4 Pytest常用插件

插件列表網址:https://plugincompat.herokuapp.com

包含很多插件包,大傢可依據工作的需求選擇使用。

4.1 前置條件:

1.文件路徑:

- Test_App
- - test_abc.py
- - pytest.ini

2.pyetst.ini配置文件內容:

  [pytest]
# 命令行參數
 addopts = -s
# 搜索文件名
 python_files = test_*.py
 # 搜索的類名
 python_classes = Test_*
 #搜索的函數名
    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

示例:

import pytest
class Test_ABC:
    def setup_class(self):
        print("------->setup_class")
    def teardown_class(self):
        print("------->teardown_class")
    def test_a(self):
        print("------->test_a")
        assert 1
    def test_b(self):
            print("------->test_b")
            assert 0 # 斷言失敗```
運行方式:
1.修改Test_App/pytest.ini文件,添加報告參數,即:addopts = -s --html=./report.html 
    # -s:輸出程序運行信息
    # --html=./report.html 在當前目錄下生成report.html文件
    ️ 若要生成xml文件,可將--html=./report.html 改成 --html=./report.xml
2.命令行進入Test_App目錄
3.執行命令: pytest
執行結果:
    1.在當前目錄會生成assets文件夾和report.html文件
 

5.pytest的高階用法(一)

前置條件:

1.文件路徑:

Test_App
    - - test_abc.py
    - - pytest.ini

2.pyetst.ini配置文件內容:

 [pytest]
  命令行參數
 addopts = -s
 搜索文件名
 python_files = test*.py
  搜索的類名
 python_classes = Test*
搜索的函數名
 python_functions = test_*

5.1pytest之fixture

fixture修飾器來標記固定的工廠函數,在其他函數,模塊,類或整個工程調用它時會被激活並優先執行,通常會被用於完成預置處理和重復操作。

方法:

fixture(scope="function", params=None, autouse=False, ids=None, name=None)

常用參數:

 scope:被標記方法的作用域

 function(default):作用於每個測試方法,每個test都運行一次

class:作用於整個類,每個class的所有test隻運行一次

module:作用於整個模塊,每個module的所有test隻運行一次

 session:作用於整個session(慎用),每個session隻運行一次

 params:(list類型)提供參數數據,供調用標記方法的函數使用

 autouse:是否自動運行,默認為False不運行,設置為True自動運行

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

示例:

class Test_ABC:
    @pytest.fixture()
    def before(self):
        print("------->before")
    def test_a(self,before): # ️ test_a方法傳入瞭被fixture標識的函數,已變量的形式
        print("------->test_a")
        assert 1
if __name__ == '__main__':
    pytest.main("-s  test_abc.py")
執行結果:
    test_abc.py 
        ------->before # 發現before會優先於測試函數運行
        ------->test_a
         .

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

示例:

import pytest
@pytest.fixture() # fixture標記的函數可以應用於測試類外部
def before():
    print("------->before")
@pytest.mark.usefixtures("before")
class Test_ABC:
    def setup(self):
        print("------->setup")
    def test_a(self):
        print("------->test_a")
        assert 1
if __name__ == '__main__':
          pytest.main("-s  test_abc.py")
  執行結果:
      test_abc.py 
      ------->before # 發現before會優先於測試類運行
      ------->setup
      ------->test_a
      .

5.4.fixture第三個例子(默認設置為運行)

示例:

 import pytest
 @pytest.fixture(autouse=True) # 設置為默認運行
 def before():
     print("------->before")
 class Test_ABC:
     def setup(self):
         print("------->setup")
     def test_a(self):
         print("------->test_a")
         assert 1
 if __name__ == '__main__':
     pytest.main("-s  test_abc.py")
執行結果:
    test_abc.py 
    ------->before # 發現before自動優先於測試類運行
    ------->setup
    ------->test_a
        .

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

示例:

    import pytest
    @pytest.fixture(scope='function',autouse=True) # 作用域設置為function,自動運行
    def before():
        print("------->before")
    class Test_ABC:
        def setup(self):
            print("------->setup")
        def test_a(self):
            print("------->test_a")
            assert 1
        def test_b(self):
            print("------->test_b")
            assert 1
    if __name__ == '__main__':
        pytest.main("-s  test_abc.py")
執行結果:
    test_abc.py
        ------->before # 運行第一次
        ------->setup
        ------->test_a
        .------->before # 運行第二次
        ------->setup
        ------->test_b
        .

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

示例:

    import pytest
    @pytest.fixture(scope='class',autouse=True) # 作用域設置為class,自動運行
    def before():
        print("------->before")
    class Test_ABC:
        def setup(self):
            print("------->setup")
        def test_a(self):
            print("------->test_a")
            assert 1
        def test_b(self):
            print("------->test_b")
            assert 1
    if __name__ == '__main__':
        pytest.main("-s  test_abc.py")
執行結果:
    test_abc.py
    ------->before # 發現隻運行一次
    ------->setup
        ------->test_a
        .
        ------->setup
        ------->test_b
        .

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

示例一:

     import pytest
    @pytest.fixture()
    def need_data():
        return 2 # 返回數字2
    class Test_ABC:
        def test_a(self,need_data):
            print("------->test_a")
            assert need_data != 3 # 拿到返回值做一次斷言
    if __name__ == '__main__':
        pytest.main("-s  test_abc.py")
執行結果:
    test_abc.py 
    ------->test_a
    .
``
 

示例二:

import pytest
@pytest.fixture(params=[1, 2, 3])
def need_data(request): # 傳入參數request 系統封裝參數
    return request.param # 取列表中單個值,默認的取值方式
class Test_ABC:
    def test_a(self,need_data):
        print("------->test_a")
        assert need_data != 3 # 斷言need_data不等於3
if __name__ == '__main__':
    pytest.main("-s  test_abc.py")
 執行結果:
      # 可以發現結果運行瞭三次
      test_abc.py 
      1
      ------->test_a
      .
      2
      ------->test_a
      .
      3
      ------->test_a
      F

6.Pytest高階用法(二)

前置條件:

1.文件路徑:

- Test_App
- - test_abc.py
- - pytest.ini

2.pyetst.ini配置文件內容:

[pytest]
命令行參數
addopts = -s
搜索文件名
python_files = test_*.py
 搜索的類名
python_classes = Test_*
 搜索的函數名
python_functions = test_*

6.1.跳過測試函數

根據特定的條件,不執行標識的測試函數.

 方法:

 skipif(condition, reason=None)

 參數:

condition:跳過的條件,必傳參數

reason:標註原因,必傳參數

 使用方法:

 @pytest.mark.skipif(condition, reason="xxx") 

示例:

import pytest
class Test_ABC:
    def setup_class(self):
        print("------->setup_class")
    def teardown_class(self):
        print("------->teardown_class")
    def test_a(self):
        print("------->test_a")
        assert 1
    @pytest.mark.skipif(condition=2>1,reason = "跳過該函數") # 跳過測試函數test_b
    def test_b(self):
        print("------->test_b")
            assert 0
執行結果:
   test_abc.py 
   ------->setup_class
   ------->test_a #隻執行瞭函數test_a
   .
   ------->teardown_class
       s # 跳過函數```
 

6.2 標記為預期失敗函數

標記測試函數為失敗函數

 方法:

 xfail(condition=None, reason=None, raises=None, run=True, strict=False)

 常用參數:

condition:預期失敗的條件,必傳參數

reason:失敗的原因,必傳參數

 使用方法:

     @pytest.mark.xfail(condition, reason="xx")

示例:

import pytest
class Test_ABC:
    def setup_class(self):
        print("------->setup_class")
    def teardown_class(self):
        print("------->teardown_class")
    def test_a(self):
        print("------->test_a")
        assert 1
    @pytest.mark.xfail(2 > 1, reason="標註為預期失敗") # 標記為預期失敗函數test_b
       def test_b(self):
           print("------->test_b")
          assert 0
   執行結果:
       test_abc.py 
       ------->setup_class
       ------->test_a
       .
       ------->test_b
       ------->teardown_class
       x  # 失敗標記

6.3 函數數據參數化

方便測試函數對測試屬於的獲取。

 方法:

     parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)

 常用參數:

argnames:參數名

argvalues:參數對應值,類型必須為list

當參數為一個時格式:[value]

當參數個數大於一個時,格式為:

[(param_value1,param_value2…..),(param_value1,param_value2…..)]

 使用方法:

     @pytest.mark.parametrize(argnames,argvalues)

參數值為N個,測試方法就會運行N次

單個參數示例:

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

多個參數示例:

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

函數返回值類型示例:

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

6.4 修改 Python traceback 輸出

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

–full-trace參數會打印更多的錯誤輸出信息,比參數 –tb=long 還多,即使是 Ctrl+C 觸發的錯誤,也會打印出來

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

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

pytest --pdb              # 每次遇到失敗都跳轉到 PDB
pytest -x --pdb           # 第一次遇到失敗就跳轉到 PDB,結束測試執行
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

pytest.main()                      # 基本用法
pytest.main(['-x', 'mytestdir'])   # 傳入配置參數
// 指定自定義的或額外的插件
# content of myinvoke.py
import pytest
class MyPlugin(object):
    def pytest_sessionfinish(self):
        print("*** test run reporting finishing")
pytest.main(["-qq"], plugins=[MyPlugin()])

6.11 測試腳本遷移後快速部署包含pytest的virtualenv

例如你從Gitlab倉庫裡clone瞭項目組的刀刀同學編寫的測試腳本到你自己的電腦裡,你想修改些東西,並調試,咋辦?可以通過下面的操作快速創建 VirtualEnv

cd <repository>
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報告

使用命令如下:

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

有可能遇到報錯:

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

原因:

缺少pytest cov的包

解決方法

pip install pytest-cov

以上就是Python測試框架pytest高階用法全面詳解的詳細內容,更多關於Python測試框架pytest的資料請關註WalkonNet其它相關文章!

推薦閱讀: