Pytest學(xué)習(xí)4 -fixture的詳細(xì)使用

  • 前面一篇講了setup、teardown可以實(shí)現(xiàn)在執(zhí)行用例前或結(jié)束后加入一些操作,但這種都是針對整個(gè)腳本全局生效的
  • 如果有以下場景:用例 1 需要先登錄,用例 2 不需要登錄,用例 3 需要先登錄。很顯然無法用 setup 和 teardown 來實(shí)現(xiàn)了
  • fixture可以讓我們自定義測試用例的前置條件
fixture功能
傳入測試中的數(shù)據(jù)集
配置測試前系統(tǒng)的數(shù)據(jù)準(zhǔn)備,即初始化數(shù)據(jù)
為批量測試提供數(shù)據(jù)源
fixture可以當(dāng)做參數(shù)傳入

優(yōu)勢

命名方式靈活,不局限于 setup 和teardown 這幾個(gè)命名
conftest.py 配置里可以實(shí)現(xiàn)數(shù)據(jù)共享,不需要 import 就能自動找到fixture
scope="module" 可以實(shí)現(xiàn)多個(gè).py 跨文件共享前置
scope="session" 以實(shí)現(xiàn)多個(gè).py 跨文件使用一個(gè) session 來完成多個(gè)用例    

如何使用
在函數(shù)上加個(gè)裝飾器@pytest.fixture(),個(gè)人理解為,就是java的注解在方法上標(biāo)記下,依賴注入就能用了。
fixture是有返回值,沒有返回值默認(rèn)為None。用例調(diào)用fixture返回值時(shí),把fixture的函數(shù)名當(dāng)做變量用就可以了,示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_Multiplefixture.py

'''
多個(gè)fixture使用情況
'''
import pytest
@pytest.fixture()
def username():
    return '軟件測試君'
@pytest.fixture()
def password():
    return '123456'
def test_login(username, password):
    print('\n輸入用戶名:'+username)
    print('輸入密碼:'+password)
    print('登錄成功,傳入多個(gè)fixture參數(shù)成功')

輸出結(jié)果

圖片.png

fixture的參數(shù)使用
示例代碼如下:

@pytest.fixture(scope="function", params=None, autouse=False, ids=None, name=None)
def test():
    print("fixture初始化參數(shù)列表")

參數(shù)說明:

  • scope:即作用域,function"(默認(rèn)),"class","module","session"四個(gè)
  • params:可選參數(shù)列表,它將導(dǎo)致多個(gè)參數(shù)調(diào)用fixture函數(shù)和所有測試使用它。
  • autouse:默認(rèn):False,需要用例手動調(diào)用該fixture;如果是True,所有作用域內(nèi)的測試用例都會自動調(diào)用該fixture
  • ids:params測試ID的一部分。如果沒有將從params自動生成.
  • name:默認(rèn):裝飾器的名稱,同一模塊的fixture相互調(diào)用建議寫個(gè)不同的name。
  • session的作用域:是整個(gè)測試會話,即開始執(zhí)行pytest到結(jié)束測試
    scope參數(shù)作用范圍
    控制fixture的作用范圍:session>module>class>function
function:每一個(gè)函數(shù)或方法都會調(diào)用
class:每一個(gè)類調(diào)用一次,一個(gè)類中可以有多個(gè)方法
module:每一個(gè).py文件調(diào)用一次,該文件內(nèi)又有多個(gè)function和class
session:是多個(gè)文件調(diào)用一次,可以跨.py文件調(diào)用,每個(gè).py文件就是module
scope四個(gè)參數(shù)的范圍

1、scope="function
@pytest.fixture()如果不寫參數(shù),參數(shù)就是scope="function",它的作用范圍是每個(gè)測試用例執(zhí)行之前運(yùn)行一次,銷毀代碼在測試用例之后運(yùn)行。在類中的調(diào)用也是一樣的。
示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_fixture_scopeFunction.py

'''
scope="function"示例
'''
import pytest
# 默認(rèn)不填寫
@pytest.fixture()
def test1():
    print('\n默認(rèn)不填寫參數(shù)')
# 寫入默認(rèn)參數(shù)
@pytest.fixture(scope='function')
def test2():
    print('\n寫入默認(rèn)參數(shù)function')
def test_defaultScope1(test1):
    print('test1被調(diào)用')
def test_defaultScope2(test2):
    print('test2被調(diào)用')
class Testclass(object):
    def test_defaultScope2(self, test2):
        print('\ntest2,被調(diào)用,無返回值時(shí),默認(rèn)為None')
        assert test2 == None
if __name__ == '__main__':
    pytest.main(["-q", "test_fixture_scopeFunction.py"])

輸出結(jié)果


圖片.png

2、scope="class"
fixture為class級別的時(shí)候,如果一個(gè)class里面有多個(gè)用例,都調(diào)用了此fixture,那么此fixture只在此class里所有用例開始前執(zhí)行一次。
示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_fixture_scopeClass.py

'''
scope="class"示例
'''
import pytest
@pytest.fixture(scope='class')
def data():
    # 這是測試數(shù)據(jù)
    print('這是我的數(shù)據(jù)源,優(yōu)先準(zhǔn)備著哈')
    return [1, 2, 3, 4, 5]
class TestClass(object):
    def test1(self, data):
        # self可以理解為它自己的,英譯漢我就是這么學(xué)的哈哈
        print('\n輸出我的數(shù)據(jù)源:' + str(data))
if __name__ == '__main__':
    pytest.main(["-q", "test_fixture_scopeClass.py"])

輸出結(jié)果


圖片.png

3、scope="module"
fixture為module時(shí),在當(dāng)前.py腳本里面所有用例開始前只執(zhí)行一次。
示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_scopeModule.py

'''
fixture為module示例
'''
import pytest
@pytest.fixture(scope='module')
def data():
    return '\nscope為module'
    
def test1(data):
    print(data)
class TestClass(object):
    def test2(self, data):
        print('我在類中了哦,' + data)
if __name__ == '__main__':
    pytest.main(["-q", "test_scopeModule.py"])

輸出結(jié)果


圖片.png

4、scope="session"
fixture為session,允許跨.py模塊調(diào)用,通過conftest.py 共享fixture。
也就是當(dāng)我們有多個(gè).py文件的用例的時(shí)候,如果多個(gè)用例只需調(diào)用一次fixture也是可以實(shí)現(xiàn)的。
必須以conftest.py命名,才會被pytest自動識別該文件。放到項(xiàng)目的根目錄下就可以全局調(diào)用了,如果放到某個(gè)package下,那就在該package內(nèi)有效。


圖片.png

創(chuàng)建公共數(shù)據(jù),命名為conftest.py,示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: conftest.py

import pytest
@pytest.fixture(scope='session')
def commonData():
    str = ' 通過conftest.py 共享fixture'
    print('獲取到%s' % str)
    return str

創(chuàng)建測試腳本test_scope1.py,示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_scope1.py

import pytest
def testScope1(commonData):
    print(commonData)
    assert commonData == ' 通過conftest.py 共享fixture'
if __name__ == '__main__':
    pytest.main(["-q", "test_scope1.py"])

創(chuàng)建測試腳本test_scope2.py,示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_scope2.py

import pytest
def testScope2(commonData):
    print(commonData)
    assert commonData == ' 通過conftest.py 共享fixture'
if __name__ == '__main__':
    pytest.main(["-q", "test_scope2.py"])

然后同時(shí)執(zhí)行兩個(gè)文件,cmd到腳本所在目錄,輸入命令

pytest -s test_scope2.py test_scope1.py

輸出結(jié)果


圖片.png

知識點(diǎn):
一個(gè)工程下可以有多個(gè)conftest.py的文件,在工程根目錄下設(shè)置的conftest文件起到全局作用。在不同子目錄下也可以放conftest.py的文件,作用范圍只能在改層級以及以下目錄生效,另conftest是不能跨模塊調(diào)用的。

fixture的調(diào)用

將fixture名作為測試用例函數(shù)的輸入?yún)?shù)
測試用例加上裝飾器:@pytest.mark.usefixtures(fixture_name)
fixture設(shè)置autouse=True

示例代碼如下:

# -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
__title__  =
__Time__   = 2020-04-06 15:50
__Author__ = 小菠蘿測試筆記
__Blog__   = https://www.cnblogs.com/poloyy/
"""
import pytest

# 調(diào)用方式一
@pytest.fixture
def login():
    print("輸入賬號,密碼先登錄")


def test_s1(login):
    print("用例 1:登錄之后其它動作 111")


def test_s2():  # 不傳 login
    print("用例 2:不需要登錄,操作 222")


# 調(diào)用方式二
@pytest.fixture
def login2():
    print("please輸入賬號,密碼先登錄")


@pytest.mark.usefixtures("login2", "login")
def test_s11():
    print("用例 11:登錄之后其它動作 111")


# 調(diào)用方式三
@pytest.fixture(autouse=True)
def login3():
    print("====auto===")


# 不是test開頭,加了裝飾器也不會執(zhí)行fixture
@pytest.mark.usefixtures("login2")
def loginss():
    print(123)

輸出結(jié)果


圖片.png

小結(jié):
在類聲明上面加 @pytest.mark.usefixtures() ,代表這個(gè)類里面所有測試用例都會調(diào)用該fixture
可以疊加多個(gè) @pytest.mark.usefixtures() ,先執(zhí)行的放底層,后執(zhí)行的放上層
可以傳多個(gè)fixture參數(shù),先執(zhí)行的放前面,后執(zhí)行的放后面
如果fixture有返回值,用 @pytest.mark.usefixtures() 是無法獲取到返回值的,必須用傳參的方式(方式一)
不是test開頭,加了裝飾器也不會執(zhí)行fixture

實(shí)例化順序:
較高 scope 范圍的fixture(session)在較低 scope 范圍的fixture( function 、 class )之前實(shí)例化【session > package > module > class > function】
具有相同作用域的fixture遵循測試函數(shù)中聲明的順序,并遵循fixture之間的依賴關(guān)系【在fixture_A里面依賴的fixture_B優(yōu)先實(shí)例化,然后到fixture_A實(shí)例化】
自動使用(autouse=True)的fixture將在顯式使用(傳參或裝飾器)的fixture之前實(shí)例化

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest

order = []

@pytest.fixture(scope="session")
def s1():
    order.append("s1")

@pytest.fixture(scope="module")
def m1():
    order.append("m1")

@pytest.fixture
def f1(f3, a1):
    # 先實(shí)例化f3, 再實(shí)例化a1, 最后實(shí)例化f1
    order.append("f1")
    assert f3 == 123

@pytest.fixture
def f3():
    order.append("f3")
    a = 123
    yield a

@pytest.fixture
def a1():
    order.append("a1")

@pytest.fixture
def f2():
    order.append("f2")

def test_order(f1, m1, f2, s1):
    print(order)
    # m1、s1在f1后,但因?yàn)閟cope范圍大,所以會優(yōu)先實(shí)例化
    assert order == ["s1", "m1", "f3", "a1", "f1", "f2"]

圖片.png

fixture依賴其他fixture的調(diào)用
添加了 @pytest.fixture ,如果fixture還想依賴其他fixture,需要用函數(shù)傳參的方式,不能用 @pytest.mark.usefixtures() 的方式,否則會不生效

示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_fixtureRelyCall.py

'''
fixture依賴其他fixture的調(diào)用示例
'''
import pytest


@pytest.fixture(scope='session')
# 打開瀏覽器
def openBrowser():
    print('\n打開Chrome瀏覽器')


# @pytest.mark.usefixtures('openBrowser')這么寫是不行的哦,肯定不好使
@pytest.fixture()
# 輸入賬號密碼
def loginAction(openBrowser):
    print('\n輸入賬號密碼')


#  登錄過程
def test_login(loginAction):
    print('\n點(diǎn)擊登錄進(jìn)入系統(tǒng)')


if __name__ == '__main__':
    pytest.main(["-q", "test_fixtureRelyCall.py"])


fixture的params
@pytest.fixture有一個(gè)params參數(shù),接受一個(gè)列表,列表中每個(gè)數(shù)據(jù)都可以作為用例的輸入。也就說有多少數(shù)據(jù),就會形成多少用例,具體示例代碼如下:

# -*- coding: utf-8 -*-

# @FileName: test_fixtureParams.py

'''
fixture的params示例
'''
import pytest

seq=[1,2]

@pytest.fixture(params=seq)
def params(request):
    # request用來接收param列表數(shù)據(jù)
    return request.param


def test_params(params):
    print(params)
    assert 1 == params

圖片.png

fixture之yield實(shí)現(xiàn)teardown
fixture里面的teardown,可以用yield來喚醒teardown的執(zhí)行,示例代碼如下:

# -*- coding: utf-8 -*-

import pytest

@pytest.fixture(scope='module')
def open():
    print("打開瀏覽器!??!")
    yield
    print('關(guān)閉瀏覽器!??!')


def test01():
    print("\n我是第一個(gè)用例")


def test02(open):
    print("\n我是第二個(gè)用例")


if __name__ == '__main__':
    pytest.main(["-q", "test_fixtrueYield.py"])

圖片.png

yield遇到異常
還在剛才的代碼中修改,將test01函數(shù)中添加異常,具體代碼如下:

# -*- coding: utf-8 -*-

import pytest

@pytest.fixture(scope='module')
def open():
    print("打開瀏覽器?。?!")
    yield
    print('關(guān)閉瀏覽器!??!')


def test01():
    print("\n我是第一個(gè)用例")
    # 如果第一個(gè)用例異常了,不影響其他的用例執(zhí)行
    raise Exception #此處異常


def test02(open):
    print("\n我是第二個(gè)用例")


if __name__ == '__main__':
    pytest.main(["-q", "test_fixtrueYield.py"])

小結(jié)
如果yield前面的代碼,即setup部分已經(jīng)拋出異常了,則不會執(zhí)行yield后面的teardown內(nèi)容
如果測試用例拋出異常,yield后面的teardown內(nèi)容還是會正常執(zhí)行

圖片.png

addfinalizer終結(jié)函數(shù)

@pytest.fixture(scope="module")
def test_addfinalizer(request):
    # 前置操作setup
    print("==再次打開瀏覽器==")
    test = "test_addfinalizer"

    def fin():
        # 后置操作teardown
        print("==再次關(guān)閉瀏覽器==")

    request.addfinalizer(fin)
    # 返回前置操作的變量
    return test


def test_anthor(test_addfinalizer):
    print("==最新用例==", test_addfinalizer)

小結(jié):
如果 request.addfinalizer() 前面的代碼,即setup部分已經(jīng)拋出異常了,則不會執(zhí)行 request.addfinalizer() 的teardown內(nèi)容(和yield相似,應(yīng)該是最近新版本改成一致了)
可以聲明多個(gè)終結(jié)函數(shù)并調(diào)用

圖片.png


參考鏈接
https://www.cnblogs.com/longronglang/p/13869445.html
https://www.cnblogs.com/poloyy/category/1690628.html?page=2

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,517評論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,087評論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 177,521評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,493評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,207評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,603評論 1 325
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,624評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,813評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,364評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,110評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,305評論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,874評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,532評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,953評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,209評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,033評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,268評論 2 375