天天看點

python——pytest基礎

一、pytest簡介

pytest是第三方提供的單元測試架構,提供了更多的擴充,友善使用。

下載下傳:pip install pytest

與unittest差別:unittest在定義測試用例時需在測試類中進行定義,而pytest可以直接定義測試用例函數,但為了代碼規範,建議還是在特定測試類内集中定義測試用例。

二、檔案命名規則

測試檔案和測試函數必須以“test”開頭,測試類必須以“Test”開頭,python對大小寫敏感。

三、基本使用方法

1.斷言

pytest都是使用assert進行斷言,而unittest是用assertEqual()、assertIn()、assertTrue()、assertIs()等方法斷言。下方列舉幾個pytest斷言方法:

assert b in a :測試包含

assert b not in a:測試不包含

assert b is True:判斷是否為True

assert b :判斷是否為True

assert not b:判斷是否不為True

assert b is not True:判斷是否不為True

assert b is False:判斷是否為False

2.Fixtrue

對測試方法、測試函數、測試類、測試子產品、整個測試檔案進行初始化和還原環境。

(1)子產品級别和函數級别

setup_module/teardown_module:在目前檔案中,在所有測試用例執行之前與之後執行。

setup_function/teardown_function:在每個測試函數之前與之後執行。

setup()/teardown():在每個測試函數之前與之後執行,執行在setup_function()之後、teardown_function()之前。

(2)類級别和方法級别

setup_class/teardown_class:在目前測試類的開始與結束時執行

setup_method/teardown_method:在每個測試方法開始與結束執行。

setup()/teardown():在每個測試方法開始與結束執行,執行在setup_method()之後、teardown_method()之前。

3.參數化

pytest通過pytest.mark.parametrize()方法設定參數,示例代碼:

import pytest
import math

#python 參數化
@pytest.mark.parametrize(
    "base,exponent,expexted",
    [(2,2,4),
     (2,3,8),
     (1,9,1),
     (0,9,0)],
    ids=["case1","case2","case3","case4"]
)
def test_pow(base,exponent,expected):
    assert math.pow(base,exponent) == expected
           

先定義參數名稱,即“base,exponent,expexted”,接着就是測試用例清單,清單内包含一個個的測試用例資料元祖,

ids

是用以定義測試用例的名稱,預設為None。注意:參數化定義的參數名稱,必須和測試函數的參數名字相同,否則無法正常擷取資料。

運作截圖:

python——pytest基礎

4.運作測試

(1)Mark機制:在每一個測試用例前加一個marker,在運作時可以隻運作帶有該marker的測試用例,相當于用marker實作分類,運作時就能隻跑某一類的測試用例。

注:支援一個測試用例有多個marker

示例:

import pytest
class TestA(object):
    def inc(self,x):
        return x+2
    @pytest.mark.webtest
    def test_anser(self):
        assert self.inc(3) == 5
    def test_bnser(self):
        assert self.inc(4) == 7
           

在測試用例前方加上:@pytest.mark.webtest, webtest即标注該測試用例的marker;

指令行執行:

pytest -v -m "webtest" test2.py

python——pytest基礎

(2)選擇運作特定的測試用例

指令行執行:

pytest -v test.py::TestClass::test_method
           

(3)選擇運作特定的某個類,即某個類所有的測試用例

pytest -v test.py::TestClass
           

(4)用-k進行關鍵字比對來運作測試用例名字子串

pytest -v -k http test.py
           

表示運作test子產品中,名稱含“http”子串的測試用例集合

(5)運作某個目錄下的測試用例

pytest +路徑(絕對路徑/相對路徑)

5.參數

s:關閉捕捉,進而輸出列印資訊。

-v:增加測試用例冗長,即 将每個測試用例的運作情況展示出來。

-q:減少測試用例冗長,隻展示運作結果情況。

-k:運作名稱包含某字元串的用例。

-x:如果出現一條測試用例失敗,則退出測試。

四、測試報告生成

1.生成JUnit XML檔案:主要用于存放測試結果

例:

pytest ./test_dir --junit-xml=./report/log.xml

2.生成線上測試報告:即生成一個連結,浏覽器打開連結檢視報告。

例:

pytest ./test_dir --pastebin=all

3.生成HTML格式的測試報告

~需按照pytest-html擴充:pip install pytest-html

例:

pytest ./ --html=./report/result.html

五、擴充

pytest-rerunfailures:在測試用例失敗時進行重試,通過“–reruns”參數設定測試用例運作失敗後的重試次數。

pytest-parallel:實作測試用例的并行運作,在每個測試用例中分别設定sleep()模拟運作時間較長的測試用例。

運作時通過“–test-per-worker”指定線程數,“auto”表示自動配置設定

例:

pytest -q test.py --test-per-worker auto