Pytest學習(四) - fixture的使用


前言

寫這篇文章,整體還是比較坎坷的,我發現有知識斷層,理解再整理寫出來,還真的有些難。

作為java黨硬磕Python,雖然對我而言是常事了(因為我比較愛折騰,哈哈),但這並不能影響我的熱情。

執念這東西,有時真的很強大,回想下,你有多久沒有特別想堅持學一樣技能或者看一本書了呢

之前就有很多粉絲和我說,六哥pytest很簡單,都是入門的東西不愛看,網上有很多教程,能不能寫點干貨呀,但我為什么還是要堅持寫呢?

簡單呀,因為我想學,我之前都是拿來改改直接用,“哪里不會點哪里”,個中細節處理不是很懂,想好好消化下,再整理寫出來。

fixture功能

  • 傳入測試中的數據集
  • 配置測試前系統的數據准備,即初始化數據
  • 為批量測試提供數據源

fixture可以當做參數傳入

如何使用

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

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 18:23
# @Author  : longrong.lang
# @FileName: test_fixture_AsParam.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
@pytest.fixture()
def param():
    return "fixture當做參數"
def test_Asparam(param):
    print('param : '+param)

輸出結果:

多個fixture的使用

示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 18:43
# @Author  : longrong.lang
# @FileName: test_Multiplefixture.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
多個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參數成功')

輸出結果:

fixture的參數使用

示例代碼如下:

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

參數說明:

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

scope參數作用范圍

控制fixture的作用范圍:session>module>class>function

  • function:每一個函數或方法都會調用
  • class:每一個類調用一次,一個類中可以有多個方法
  • module:每一個.py文件調用一次,該文件內又有多個function和class
  • session:是多個文件調用一次,可以跨.py文件調用,每個.py文件就是module

scope四個參數的范圍

1、scope="function"

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

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 19:05
# @Author  : longrong.lang
# @FileName: test_fixture_scopeFunction.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
scope="function"示例
'''
import pytest
# 默認不填寫
@pytest.fixture()
def test1():
    print('\n默認不填寫參數')
# 寫入默認參數
@pytest.fixture(scope='function')
def test2():
    print('\n寫入默認參數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"])

輸出結果:

2、scope="class"

fixture為class級別的時候,如果一個class里面有多個用例,都調用了此fixture,那么此fixture只在此class里所有用例開始前執行一次。
示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 19:15
# @Author  : longrong.lang
# @FileName: test_fixture_scopeClass.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
scope="class"示例
'''
import pytest
@pytest.fixture(scope='class')
def data():
    # 這是測試數據
    print('這是我的數據源,優先准備着哈')
    return [1, 2, 3, 4, 5]
class TestClass(object):
    def test1(self, data):
        # self可以理解為它自己的,英譯漢我就是這么學的哈哈
        print('\n輸出我的數據源:' + str(data))
if __name__ == '__main__':
    pytest.main(["-q", "test_fixture_scopeClass.py"])

輸出結果:

3、scope="module"

fixture為module時,在當前.py腳本里面所有用例開始前只執行一次。
示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 19:27
# @Author  : longrong.lang
# @FileName: test_scopeModule.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
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"])

輸出結果:

4、scope="session"

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

創建公共數據,命名為conftest.py,示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 19:37
# @Author  : longrong.lang
# @FileName: conftest.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
@pytest.fixture(scope='session')
def commonData():
    str = ' 通過conftest.py 共享fixture'
    print('獲取到%s' % str)
    return str

創建測試腳本test_scope1.py,示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 19:45
# @Author  : longrong.lang
# @FileName: test_scope1.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
def testScope1(commonData):
    print(commonData)
    assert commonData == ' 通過conftest.py 共享fixture'
if __name__ == '__main__':
    pytest.main(["-q", "test_scope1.py"])

創建測試腳本test_scope2.py,示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 19:45
# @Author  : longrong.lang
# @FileName: test_scope1.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
def testScope2(commonData):
    print(commonData)
    assert commonData == ' 通過conftest.py 共享fixture'
if __name__ == '__main__':
    pytest.main(["-q", "test_scope2.py"])

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

pytest -s test_scope2.py test_scope1.py

輸出結果:

知識點:

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

fixture的調用

  • 將fixture名作為測試用例函數的輸入參數
  • 測試用例加上裝飾器:@pytest.mark.usefixtures(fixture_name)
  • fixture設置autouse=True

示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 20:10
# @Author  : longrong.lang
# @FileName: test_fixtureCall.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture調用示例
'''
import pytest
# 調用方式一
@pytest.fixture
def login1():
    print('第一種調用')
# 傳login
def test_case1(login1):
    print("\n測試用例1")
# 不傳login
def test_case2():
    print("\n測試用例2")
# 調用方式二
@pytest.fixture
def login2():
    print("第二種調用")
@pytest.mark.usefixtures("login2", "login1")
def test_case3():
    print("\n測試用例3")
# 調用方式三
@pytest.fixture(autouse=True)
def login3():
    print("\n第三種調用")
# 不是test開頭,加了裝飾器也不會執行fixture
@pytest.mark.usefixtures("login2")
def loginss():
    print(123)
if __name__ == '__main__':
    pytest.main(["-q", "test_fixtureCall.py"])

輸出結果:

小結:

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

fixture依賴其他fixture的調用

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

示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 20:23
# @Author  : longrong.lang
# @FileName: test_fixtureRelyCall.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang

'''
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點擊登錄進入系統')


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

輸出結果:

fixture的params

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

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 20:30
# @Author  : longrong.lang
# @FileName: test_fixtureParams.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture的params示例
'''
import pytest

seq=[1,2]


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



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

輸出結果:

fixture之yield實現teardown

fixture里面的teardown,可以用yield來喚醒teardown的執行,示例代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 20:44
# @Author  : longrong.lang
# @FileName: test_fixtrueYield.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture之yield示例
'''

# !/usr/bin/env python
# -*- 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"])

輸出結果:

yield遇到異常

還在剛才的代碼中修改,將test01函數中添加異常,具體代碼如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/10/24 20:44
# @Author  : longrong.lang
# @FileName: test_fixtrueYield.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture之yield示例
'''

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

import pytest


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


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


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


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

輸出結果:

小結

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

addfinalizer終結函數(不太熟悉)

@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部分已經拋出異常了,則不會執行 request.addfinalizer() 的teardown內容(和yield相似,應該是最近新版本改成一致了)
  • 可以聲明多個終結函數並調用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM