【Pytest】python單元測試框架pytest簡介

最新更新請看 《基於Pytest框架的自動化測試開發實踐(萬字長文入門篇)》

1、Pytest介紹

pytest是python的一種單元測試框架,與python自帶的unittest測試框架類似,但是比unittest框架使用起來更簡潔,效率更高。根據pytest的官方網站介紹,它具有如下特點:

 

  • 非常容易上手,入門簡單,文檔豐富,文檔中有很多實例可以參考
  • 能夠支持簡單的單元測試和複雜的功能測試
  • 支持參數化
  • 執行測試過程中可以將某些測試跳過,或者對某些預期失敗的case標記成失敗
  • 支持重複執行失敗的case
  • 支持運行由nose, unittest編寫的測試case
  • 具有很多第三方插件,並且可以自定義擴展
  • 方便的和持續集成工具集成
由於網上pytest的中文文檔比較少,自己學習過程中,基本上看的就是英文的官方文檔,對於不想看英文的同學們,本系列文章希望能夠幫大家一馬。
 

2、安裝pytest

與安裝其他的python軟件無異,直接使用pip安裝。
pip install -U pytest
安裝完成後,可以驗證安裝的版本:
py.test --version
 

3、一個實例

我們可以通過下面的實例,看看使用py.test進行測試是多麼簡單。
# content of test_sample.py

def func(x):
    return x+1

def test_func():
    assert func(3) == 5
這裏我們定義了一個被測試函數func,該函數將傳遞進來的參數加1後返回。我們還定義了一個測試函數test_func用來對func進行測試。test_func中我們使用基本的斷言語句assert來對結果進行驗證。
下面來運行這個測試:
$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1
rootdir: /tmp/doc-exec-101, inifile:
collected 1 items
test_sample.py F
================================= FAILURES =================================
_______________________________ test_answer ________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:5: AssertionError
========================= 1 failed in 0.01 seconds =========================
執行測試的時候,我們只需要在測試文件test_sample所在的目錄下,運行py.test即可。pytest會在當前的目錄下,尋找以test開頭的文件(即測試文件),找到測試文件之後,進入到測試文件中尋找test_開頭的測試函數並執行。
通過上面的測試輸出,我們可以看到該測試過程中,一個收集到了一個測試函數,測試結果是失敗的(標記爲F),並且在FAILURES部分輸出了詳細的錯誤信息,幫助我們分析測試原因,我們可以看到"assert func(3) == 5"這條語句出錯了,錯誤的原因是func(3)=4,然後我們斷言func(3) 等於 5。
 

4、再一個實例

當需要編寫多個測試樣例的時候,我們可以將其放到一個測試類當中,如:
# content of test_class.py

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')
我們可以通過執行測試文件的方法,執行上面的測試:
$ py.test -q test_class.py
.F
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________
self = <test_class.TestClass object at 0x7fbf54cf5668>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E assert hasattr('hello', 'check')
test_class.py:8: AssertionError
1 failed, 1 passed in 0.01 seconds
從測試結果中可以看到,該測試共執行了兩個測試樣例,一個失敗一個成功。同樣,我們也看到失敗樣例的詳細信息,和執行過程中的中間結果。
 

5、如何編寫pytest測試樣例

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

6、如何執行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

7、測試報告

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

生成HTML格式報告:

 

py.test --resultlog=path
生成XML格式的報告:

 

 

py.test --junitxml=path

 

8、如何獲取幫助信息

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

9、最佳實踐

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


 
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章