1. 程式人生 > >python文檔22-fixture詳細介紹-作為參數傳入,error和failed區別

python文檔22-fixture詳細介紹-作為參數傳入,error和failed區別

3.6 獨立 配置 組件 實現 win ssi html-1 int

前言

fixture是pytest的核心功能,也是亮點功能,熟練掌握fixture的使用方法,pytest用起來才會得心應手!

fixture簡介

fixture的目的是提供一個固定基線,在該基線上測試可以可靠地和重復地執行。fixture提供了區別於傳統單元測試(setup/teardown)有顯著改進:

  • 有獨立的命名,並通過聲明它們從測試函數、模塊、類或整個項目中的使用來激活。
  • 按模塊化的方式實現,每個fixture都可以互相調用。
  • fixture的範圍從簡單的單元擴展到復雜的功能測試,允許根據配置和組件選項對fixture和測試用例進行參數化,或者跨函數 function、類class、模塊module或整個測試會話sessio範圍。

fixture作為參數傳入

定義fixture跟定義普通函數差不多,唯一區別就是在函數上加個裝飾器@pytest.fixture(),fixture命名不要用test_開頭,跟用例區分開。用例才是test_開頭的命名。

fixture是可以有返回值的,如果沒return默認返回None。用例調用fixture的返回值,直接就是把fixture的函數名稱當成變量名稱,如下案例

# test_fixture1.py
import pytest

@pytest.fixture()
def user():
    print("獲取用戶名")
    a = "yoyo"
    return a

def test_1(user):
    assert user == "yoyo"

if __name__ == "__main__":
    pytest.main(["-s", "test_fixture1.py"])

運行結果

============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO\fixt, inifile:
plugins: rerunfailures-4.1, metadata-1.7.0, html-1.19.0, allure-adaptor-1.7.10
collected 1 item

test_fixture1.py 獲取用戶名
.

========================== 1 passed in 0.20 seconds ===========================

error和failed區別

測試結果一般有三種:passed、failed、error。(skip的用例除外)

如果在test_用例裏面斷言失敗,那就是failed

# test_fixture2.py
import pytest

@pytest.fixture()
def user():
    print("獲取用戶名")
    a = "yoyo"
    return a

def test_1(user):
    assert user == "yoyo111"  # 用例失敗就是failed

if __name__ == "__main__":
    pytest.main(["-s", "test_fixture2.py"])

如果在fixture裏面斷言失敗了,那就是error

test_fixture3.py
import pytest

@pytest.fixture()
def user():
    print("獲取用戶名")
    a = "yoyo"
    assert a == "yoyo123"  # fixture失敗就是error
    return a

def test_1(user):
    assert user == "yoyo"

if __name__ == "__main__":
    pytest.main(["-s", "test_fixture3.py"])

還有一種情況也會出現error,那就是自己代碼寫的有問題,自己本身代碼報錯,那就是error了。
作者:上海-悠悠,QQ交流群:874033608

python文檔22-fixture詳細介紹-作為參數傳入,error和failed區別