Pytest學習4 -fixture的詳細使用

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

優(yōu)勢

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

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

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

# @FileName: test_Multiplefixture.py

'''
多個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('登錄成功,傳入多個fixture參數(shù)成功')

輸出結果

圖片.png

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

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

參數(shù)說明:

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

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

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

# @FileName: test_fixture_scopeFunction.py

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

輸出結果


圖片.png

2、scope="class"
fixture為class級別的時候,如果一個class里面有多個用例,都調用了此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)先準備著哈')
    return [1, 2, 3, 4, 5]
class TestClass(object):
    def test1(self, data):
        # self可以理解為它自己的,英譯漢我就是這么學的哈哈
        print('\n輸出我的數(shù)據(jù)源:' + str(data))
if __name__ == '__main__':
    pytest.main(["-q", "test_fixture_scopeClass.py"])

輸出結果


圖片.png

3、scope="module"
fixture為module時,在當前.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"])

輸出結果


圖片.png

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


圖片.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"])

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

pytest -s test_scope2.py test_scope1.py

輸出結果


圖片.png

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

fixture的調用

將fixture名作為測試用例函數(shù)的輸入?yún)?shù)
測試用例加上裝飾器:@pytest.mark.usefixtures(fixture_name)
fixture設置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

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


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


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


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


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


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


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

輸出結果


圖片.png

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

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

#!/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):
    # 先實例化f3, 再實例化a1, 最后實例化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后,但因為scope范圍大,所以會優(yōu)先實例化
    assert order == ["s1", "m1", "f3", "a1", "f1", "f2"]

圖片.png

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

示例代碼如下:

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

# @FileName: test_fixtureRelyCall.py

'''
fixture依賴其他fixture的調用示例
'''
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點擊登錄進入系統(tǒng)')


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


fixture的params
@pytest.fixture有一個params參數(shù),接受一個列表,列表中每個數(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實現(xiàn)teardown
fixture里面的teardown,可以用yield來喚醒teardown的執(zhí)行,示例代碼如下:

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

import pytest

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


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


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


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('關閉瀏覽器?。?!')


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


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


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

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

圖片.png

addfinalizer終結函數(shù)

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

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

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


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

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

圖片.png


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

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容