python單元測試pytest

來源:互聯網
上載者:User

標籤:三方   failed   安裝   代碼   set   argument   div   過程   html   

1、pytest簡介

pytest是Python的一種單元測試架構,與python內建的unittest測試架構類似,但是比unittest架構使用起來更簡潔,效率更高。

  • 執行測試過程中可以將某些測試跳過,或者對某些預期失敗的case標記成失敗
  • 能夠支援簡單的單元測試和複雜的功能測試
  • 支援重複執行失敗的case
  • 支援運行由nose, unittest編寫的測試case
  • 具有很多第三方外掛程式,並且可以自訂擴充
  • 方便的和持續整合工具整合
  • 支援參數化

 

2、安裝pytest

pip install pytest

 

3、舉例

(1)單測試case

執行測試的時候,我們只需要在測試檔案test_sample所在的目錄下,運行py.test即可。pytest會在目前的目錄及其子目錄下尋找以test開頭的py檔案或者以test結尾的py檔案(即測試檔案),找到測試檔案之後,進入到測試檔案中尋找test_開頭的測試函數並執行。

在目前的目錄下建立檔案 test_champ.py

def func(x):    return x + 1def test_answer():    assert func(3)==5

在命令列輸入py.test [-q],加上-q(quiet)輸出結果會省去pytest版本資訊,便可以看到執行的成功與失敗的原因了

(2)多測試case

當需要編寫多個測試範例的時候,我們可以將其放到一個測試類別當中,如:

class TestClass:        def test_one(self):                assert "h" in "this"        def test_two(self):                x = "hello"                assert hasattr(x,"check")

我們可以通過執行測試檔案的方法,執行上面的測試:py.test -q test_class.py

 

4、pytest測試範例編寫規則

通過上面2個執行個體,我們發現編寫pytest測試範例非常簡單,只需要按照下面的規則:
  • 測試檔案以test_開頭(以_test結尾也可以)
  • 測試類別以Test開頭,並且不能帶有 __init__ 方法
  • 測試函數以test_開頭
  • 斷言使用基本的assert即可

 

5、如何執行pytest測試範例

執行測試範例的方法很多種,上面第一個執行個體是直接執行py.test,第二個執行個體是傳遞了測試檔案給py.test。其實py.test有好多種方法執行測試:
py.test               # run all tests below current dirpy.test test_mod.py   # run tests in modulepy.test somepath      # run all tests below somepathpy.test -k stringexpr # only run tests with names that match the                      # the "string expression", e.g. "MyClass and not method"                      # will select TestMyClass.test_something                      # but not TestMyClass.test_method_simplepy.test test_mod.py::test_func # only run tests that match the "node ID",                   # e.g "test_mod.py::test_func" will select                               # only test_func in test_mod.py

 

6、測試報告

pytest可以方便的產生測試報告,即可以產生HTML的測試報告,也可以產生XML格式的測試報告用來與持續整合工具整合。

產生txt格式報告:

py.test --resultlog=path/log.txt 

產生XML格式的報告:

py.test --junitxml=path/log.xml  

將測試報告發送到pastebin伺服器,執行下面的命令會產生報告的網址

py.test test_report.py --pastebin=all 

只發送失敗的報告

py.test test_report.py --pastebin=failed 

產生Html格式報告

這個需要安裝pytest的第三方外掛程式pytest-html:
pip install pytest-htmlpy.test test_report.py --html=path/log.html 

 

7、如何擷取協助資訊

py.test --version # shows where pytest was imported from  py.test --fixtures # show available builtin function arguments  py.test -h | --help # show help on command line and config file options  

與Python內建的unitest測試架構中的setup、teardown類似,pytest提供了fixture函數用以在測試執行前和執行後進行必要的準備和清理工作。但是fixture函數對setup和teardown進行了很大的改進。

  • fixture函數可以使用在測試函數中,測試類別中,測試檔案中以及整個測試工程中。
  • fixture支援模組化,fixture可以相互嵌套
  • fixture支援參數化
  • fixture支援unittest類型的setup和teardown
setup完成測試前的初始化工作,teardown實現測試完成後的垃圾回首工作。如果測試的程式使用jdbc串連資料庫,那麼setUpBeforeClass()方法中就可以寫上初始化資料庫連接的一些代碼,tearDownAfterClass()方法中就可以寫上關閉資料庫連接的一些代碼。
 

8、最佳實務

其實對於測試而言,特別是在持續整合環境中,我們的所有測試最好是在虛擬環境中。這樣不同的虛擬環境中的測試不會相互幹擾的。由於我們的實際工作中,在同一個Jekins中,運行了好多種不同項目冊的測試,因此,各個測試專案運行在各自的虛擬環境中。將pytest安裝在虛擬環境中:1、將目前的目錄建立為虛擬環境
virtualenv .        # create a virtualenv directory in the current directory  source bin/activate # on unix 

2、在虛擬環境中安裝pytest:

pip install pytest  

 

9、斷言的使用

  ①正常斷言

# 子簽名類,忽略中間列印的過程,直接表示出錯的原因# assert value == 0, "value was odd, should be even"  # 等於、不等、小於、大於assert func(2)==3

  ②異常斷言

使用pytest.raise方法(需import pytest)

斷言1除以0,將產生一個ZeroDivisionError類型的異常。

import pytest  def test_zero_division():      with pytest.raises(ZeroDivisionError):          1 / 0 

有的時候,我們可能需要在測試中用到產生的異常中的某些資訊,比如異常的類型type,異常的值value等等。下面我們修改下上面的測試

import pytest  def test_recursion_depth():      with pytest.raises(ZeroDivisionError) as excinfo:      1/0      assert excinfo.type == ‘RuntimeError‘  

因為該測試斷言產生的異常類型是RuntimeError,而實際上產生的異常類型是ZeroDivisionError,所以測試失敗了。在測試結果中,可以看到assert子運算式excinfo.type的值。

 

python單元測試pytest

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.