python單元測試pytest


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 + 1

def 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 dir
py.test test_mod.py   # run tests in module
py.test somepath      # run all tests below somepath
py.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_simple
py.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-html
py.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的值。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM