日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

Pytest学习笔记2——前后置处理高级函数Fixture(完整篇)

發(fā)布時(shí)間:2024/4/24 综合教程 32 生活家
生活随笔 收集整理的這篇文章主要介紹了 Pytest学习笔记2——前后置处理高级函数Fixture(完整篇) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

  引言

  前面介紹了pytest傳統(tǒng)的前后置處理方法,通過一些實(shí)例,知道了它對(duì)處理前后置的場(chǎng)景是有一定的局限性。所以才引入fixture裝飾器函數(shù),fixture是pytest的核心功能,也是亮點(diǎn)功能,它可以靈活的處理很多特殊的場(chǎng)景,利用pytest做接口測(cè)試,熟練掌握fixture的使用方法,pytest用起來才會(huì)得心應(yīng)手!

  Pytest簡(jiǎn)介

  fixture的目的是提供一個(gè)固定基線,在該基線上測(cè)試可以可靠地和重復(fù)地執(zhí)行。fixture提供了區(qū)別于傳統(tǒng)單元測(cè)試(setup/teardown)有顯著改進(jìn):

  1.有獨(dú)立的命名,并通過聲明它們從測(cè)試函數(shù)、模塊、類或整個(gè)項(xiàng)目中的使用來激活。

  2.按模塊化的方式實(shí)現(xiàn),每個(gè)fixture都可以互相調(diào)用。

  3.fixture的范圍從簡(jiǎn)單的單元擴(kuò)展到復(fù)雜的功能測(cè)試,允許根據(jù)配置和組件選項(xiàng)對(duì)fixture和測(cè)試用例進(jìn)行參數(shù)化,或者跨函數(shù)function、類class、模塊module或整個(gè)測(cè)試會(huì)話sessio范圍。

  Fixture函數(shù)定義

  先看一下fixture的函數(shù)定義:

def fixture(
    callable_or_scope=None,
    *args,
    scope="function",
    params=None,
    autouse=False,
    ids=None,
    name=None
):
    """Decorator to mark a fixture factory function.

    This decorator can be used, with or without parameters, to define a
    fixture function.

    The name of the fixture function can later be referenced to cause its
    invocation ahead of running tests: test
    modules or classes can use the ``pytest.mark.usefixtures(fixturename)``
    marker.

    Test functions can directly use fixture names as input
    arguments in which case the fixture instance returned from the fixture
    function will be injected.

    Fixtures can provide their values to test functions using ``return`` or ``yield``
    statements. When using ``yield`` the code block after the ``yield`` statement is executed
    as teardown code regardless of the test outcome, and must yield exactly once.

    :arg scope: the scope for which this fixture is shared, one of
                ``"function"`` (default), ``"class"``, ``"module"``,
                ``"package"`` or ``"session"`` (``"package"`` is considered **experimental**
                at this time).

                This parameter may also be a callable which receives ``(fixture_name, config)``
                as parameters, and must return a ``str`` with one of the values mentioned above.

                See :ref:`dynamic scope` in the docs for more information.

    :arg params: an optional list of parameters which will cause multiple
                invocations of the fixture function and all of the tests
                using it.
                The current parameter is available in ``request.param``.

    :arg autouse: if True, the fixture func is activated for all tests that
                can see it.  If False (the default) then an explicit
                reference is needed to activate the fixture.

    :arg ids: list of string ids each corresponding to the params
                so that they are part of the test id. If no ids are provided
                they will be generated automatically from the params.

    :arg name: the name of the fixture. This defaults to the name of the
                decorated function. If a fixture is used in the same module in
                which it is defined, the function name of the fixture will be
                shadowed by the function arg that requests the fixture; one way
                to resolve this is to name the decorated function
                ``fixture_<fixturename>`` and then use
                ``@pytest.fixture(name='<fixturename>')``.
    """

  

  大致翻譯了一下:

def fixture(
    callable_or_scope=None,
    *args,
    scope="function",
    params=None,
    autouse=False,
    ids=None,
    name=None
):
    """
	1、fixture不管有沒有參數(shù),都可以用來標(biāo)記夾具功能;
	2、test模塊或類都可以使用'pytest.mark.usefixture(fixturename)'裝飾器來標(biāo)記,標(biāo)記之后就每個(gè)測(cè)試用例運(yùn)行之前會(huì)調(diào)用fixturename;
	3、測(cè)試函數(shù)可以直接使用fixture名稱作為輸入?yún)?shù),在這種情況下,fixture實(shí)例從fixture返回函數(shù)將被注入。
	4、fixture可以使用' return '或' yield '來提供它們的值來測(cè)試函數(shù)語句。當(dāng)使用'yield'語句后的代碼塊被執(zhí)行無論測(cè)試結(jié)果如何,都必須精確地產(chǎn)生一次。

    :arg scope: scope作用域有4個(gè)級(jí)別,默認(rèn)是function,其次class,然后是module和session.

    :arg params: 一個(gè)可選的形參列表,它將導(dǎo)致多個(gè)參數(shù)對(duì)夾具功能和所有測(cè)試的調(diào)用使用它。

    :arg autouse:如果為真,則對(duì)所有測(cè)試激活fixture func可以看到它。如果為False(默認(rèn)值),則顯式需要引用來激活?yuàn)A具。 

    :arg ids: 每個(gè)參數(shù)對(duì)應(yīng)的字符串id列表因此它們是測(cè)試id的一部分。如果沒有提供id它們將由參數(shù)自動(dòng)生成。

    :arg name:設(shè)備的名稱。方法的默認(rèn)名稱裝飾功能。如果在同一模塊中使用了一個(gè)fixture哪個(gè)定義了,夾具的函數(shù)名會(huì)是被要求夾具的功能參數(shù)所遮蔽;的一種方法要解決這個(gè)問題,可以命名修飾后的函數(shù)'fixture_<fixturename>'然后使用
@pytest.fixture (name = ' < fixturename > ')。
    """
	
	

  

  Scope參數(shù)介紹與使用

  scope參數(shù)主要控制fixture作用范圍,邏輯優(yōu)先級(jí)是:session > module > class > function.
  scope參數(shù)有四種選擇:function(測(cè)試函數(shù)級(jí)別),class(測(cè)試類級(jí)別),module(測(cè)試模塊“.py”級(jí)別),session(多個(gè)文件級(jí)別)。默認(rèn)是function級(jí)別。
  這里需要注意的pytest文檔中講的模塊是針對(duì)".py"文件的叫法。也就是模塊就是py文件的意思。
  

  級(jí)別介紹:
  function級(jí)別(針對(duì)函數(shù)):每個(gè)測(cè)試用例運(yùn)行之前運(yùn)行
  class級(jí)別(針對(duì)測(cè)試類):每個(gè)類執(zhí)行一次(所有測(cè)試用例運(yùn)行之前運(yùn)行,這個(gè)節(jié)點(diǎn)從引入fixture的測(cè)試用例開始算),一個(gè)類可以有多個(gè)測(cè)試方法(用例)。
  module級(jí)別(針對(duì)單模塊):每個(gè)模塊(.py)執(zhí)行一次,不管類中測(cè)試方法還是類外的測(cè)試方法。
  session級(jí)別(針對(duì)多模塊):是多個(gè)文件調(diào)用一次,可以跨.py文件調(diào)用,每個(gè).py文件就是module。

  Fixture作用范圍:scope = 'function'

  @pytest.fixture()函數(shù)使用方式:作為參數(shù)傳入(單個(gè))

  裝飾器@pytest.fixture()如果不寫參數(shù),默認(rèn)就是scope="function",它的作用范圍是每個(gè)測(cè)試用例來之前運(yùn)行一次,銷毀代碼在測(cè)試用例運(yùn)行之后運(yùn)行。

  之前的文章已經(jīng)介紹過了,這里再貼一下代碼:

 ?。▎蝹€(gè)fixture函數(shù),沒有類)

# 創(chuàng)建fixture函數(shù)(無類)——法1,作為參數(shù)傳入,作為范圍:functions
@pytest.fixture()
def login():
	print("輸入賬號(hào)")
	a = "account"
	return a


def test_001(login):
	print("賬號(hào)是: %s"%login)
	assert login == "account"

def test_002():
	print("單擊登陸")

if __name__ == '__main__':
    pytest.main()

  運(yùn)行結(jié)果:

plugins: allure-pytest-2.8.6, rerunfailures-5.0
collected 2 items                                                                                                                                                                       

fixtrue_001.py 輸入賬號(hào)
賬號(hào)是: account
.單擊登陸
.

================================================================================== 2 passed in 0.02s ===================================================================================

 ?。▎蝹€(gè)fixture函數(shù),有類)

# 創(chuàng)建fixture函數(shù)(類中)——法2,作為參數(shù)傳入,作為范圍:functions

@pytest.fixture(scope="function")
def login():
	print("輸入賬號(hào)")
	a = "account"
	return a


class TestLogin:
	def test_001(self,login):
		print("輸入的賬號(hào): %s"%login)
		assert login == "account"
	def test_002(self):
		print("")


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

  運(yùn)行結(jié)果:

plugins: allure-pytest-2.8.6, rerunfailures-5.0
collected 2 items                                                                                                                                                                       

fixtrue_001.py 輸入賬號(hào)
輸入的賬號(hào): account
.用例2
.

================================================================================== 2 passed in 0.02s ===================================================================================

  

  @pytest.fixture()函數(shù)使用方式:作為參數(shù)傳入(多個(gè)fixture使用)

  一些場(chǎng)景,比如登陸之后有退出,這樣的話需要兩個(gè)fixture函數(shù)處理,示例如下:

# fixture函數(shù)(類中) 作為多個(gè)參數(shù)傳入
@pytest.fixture()
def login():
	print("輸入賬號(hào)")
	a = "account"
	return a

@pytest.fixture()
def logout():
	print("退出")

class TestLogin:
	def test_001(self,login):
		print("輸入的賬號(hào): %s"%login)
		assert login == "account"
	def test_002(self,logout):
		print("退出")
	def test_003(self,login,logout):
		print("步驟1:%s"%login)
		print("步驟2:%s"%logout)


if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

plugins: allure-pytest-2.8.6, rerunfailures-5.0
collected 3 items                                                                                                                                                                       

fixtrue_001.py 輸入賬號(hào)
輸入的賬號(hào): account
.退出
退出
.輸入賬號(hào)
退出
步驟1:account
步驟2:None
.

================================================================================== 3 passed in 0.03s ===================================================================================

  

  @pytest.fixture()函數(shù)使用方式:作為參數(shù)傳入(互相調(diào)用)

  fixture固件可以被測(cè)試方法調(diào)用,也可以被固件自己調(diào)用。

  舉個(gè)例子:

# fixtrue作為參數(shù),互相調(diào)用傳入
@pytest.fixture()
def account():
	a = "account"
	print("輸入賬號(hào):%s"%a)

@pytest.fixture()
def login(account):
	print("單擊登陸")

class TestLogin:
	def test_1(self,login):
		print("操作結(jié)果:%s"%login)
	def test_2(self,account):
		print("賬號(hào): %s"%account)
	def test_3(self):
		print("測(cè)試用例3")

if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

plugins: allure-pytest-2.8.6, rerunfailures-5.0
collected 3 items                                                                                                                                                                       

fixtrue_001.py 輸入賬號(hào):account
單擊登陸
操作結(jié)果:None
.輸入賬號(hào):account
賬號(hào): None
.測(cè)試用例3
.

================================================================================== 3 passed in 0.02s ===================================================================================

  Fixture作用范圍:scope = 'class'

  fixture是class級(jí)別的時(shí)候,分為兩種情況:

  第一種,測(cè)試類下面所有測(cè)試方法(用例),都使用了fixture函數(shù)名,這樣的話,fixture只在該class下所有測(cè)試用例執(zhí)行前執(zhí)行一次。

  示例演示:

# fixture作用域 scope = 'class'
@pytest.fixture(scope='class')
def login():
	a = '123'
	print("輸入賬號(hào)密碼登陸")



class TestLogin:
	def test_1(self,login):
		print("用例1")
	def test_2(self,login):
		print("用例2")
	def test_3(self,login):
		print("用例3")
if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

collected 3 items                                                                                                                                                                       

fixtrue_001.py 輸入賬號(hào)密碼登陸
用例1
.用例2
.用例3
.

================================================================================== 3 passed in 0.02s ===================================================================================

  

  第二種,測(cè)試類下面只有一些測(cè)試方法使用了fixture函數(shù)名,這樣的話,fixture只在該class下第一個(gè)使用fixture函數(shù)的測(cè)試用例位置開始算,后面所有的測(cè)試用例執(zhí)行前只執(zhí)行一次。而該位置之前的測(cè)試用例就不管。

# fixture作用域 scope = 'class'
@pytest.fixture(scope='class')
def login():
	a = '123'
	print("輸入賬號(hào)密碼登陸")



class TestLogin:
	def test_1(self):
		print("用例1")
	def test_2(self,login):
		print("用例2")
	def test_3(self,login):
		print("用例3")
	def test_4(self):
		print("用例4")
if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

collected 4 items                                                                                                                                                                       

fixtrue_001.py 用例1
.輸入賬號(hào)密碼登陸
用例2
.用例3
.用例4
.

================================================================================== 4 passed in 0.03s ===================================================================================

  Fixture作用范圍:scope = 'module'

  fixture為module時(shí),對(duì)當(dāng)前模塊(.py)文件下所有測(cè)試用例開始前執(zhí)行一次,示例如下:

# fixture scope = 'module'
@pytest.fixture(scope='module')
def login():
	print("登陸")

def test_01(login):
	print("用例01")
def test_02(login):
	print("用例02")

class TestLogin():
	def test_1(self,login):
		print("用例1")
	def test_2(self,login):
		print("用例2")
	def test_3(self,login):
		print("用例3")

if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

collected 5 items                                                                                                                                                                       

fixtrue_001.py 登陸
用例01
.用例02
.用例1
.用例2
.用例3
.

================================================================================== 5 passed in 0.03s ===================================================================================

  

  Fixture作用范圍:scope = 'session'

  設(shè)置方式和module級(jí)別的設(shè)置方式一樣,需要注意的是session級(jí)別一般都是多個(gè).py文件共用,所以要前置函數(shù)的聲明一般在conftest.py中。

  其作用在多個(gè)測(cè)試模塊(.py文件)中只執(zhí)行一次,并且是在傳入函數(shù)名的測(cè)試用例中的第一個(gè)執(zhí)行的測(cè)試用例之前執(zhí)行。

  如果在同一個(gè)模塊下(.py文件里),session與module特性一致,示例如下:

import pytest
@pytest.fixture(scope="session")
def login():
    print("
輸入用戶名密碼登陸! configtest")
    yield
    print("退出登陸")


def test_cart(login):
    print('用例1,登陸后執(zhí)行添加購(gòu)物車功能操作')

def test_search():
    print('用例2,不登陸查詢功能操作')

def test_pay(login):
    print('用例3,登陸后執(zhí)行支付功能操作')

if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

plugins: allure-pytest-2.8.6, rerunfailures-5.0
collected 3 items                                                                                                                                                                       

fixtrue_003.py
輸入用戶名密碼登陸! configtest
用例1,登陸后執(zhí)行添加購(gòu)物車功能操作
.用例2,不登陸查詢功能操作
.用例3,登陸后執(zhí)行支付功能操作
.退出登陸


================================================================================== 3 passed in 0.02s ===================================================================================

  

  @pytest.fixture()函數(shù)使用方式:作為conftest.py文件傳入

  如果在不同模塊下(.py文件里),session是給多個(gè).py文件使用,并且寫到conftest.py文件里,conftest.py文件名稱是固定的,pytest會(huì)自動(dòng)識(shí)別該文件。

  放到工程的根目錄下,就可以全局調(diào)用了,如果放到某個(gè)package包下,那就只在該package內(nèi)有效,示例如下:

  在文件夾fixture_exp下新建conftest.py文件:

# fixture 固定裝飾器,作用域:scope = 'session'
import pytest
@pytest.fixture(scope='session')
def login():
    print("輸入賬號(hào)密碼")
    yield
    print("清理數(shù)據(jù)完成")

  

  新建兩個(gè)測(cè)試文件:

# fixture scope = 'session',fixtrue_001.py
class TestLogin1():
	def test_1(self,login):
		print("用例1")
	def test_2(self):
		print("用例2")
	def test_3(self,login):
		print("用例3")


if __name__ == '__main__':
    pytest.main()

  

# fixture scope = 'session',fixtrue_002.py
import pytest

class TestLogin2():
	def test_4(self):
		print("用例4")
	def test_5(self):
		print("用例5")
	def test_6(self):
		print("用例6")


if __name__ == '__main__':
    pytest.main()

  同時(shí)運(yùn)行兩個(gè)測(cè)試文件,可以在控制臺(tái)中輸入:

pytest -s fixtrue_001.py fixtrue_002.py

  

  運(yùn)行結(jié)果:

plugins: allure-pytest-2.8.6, rerunfailures-5.0
collected 6 items                                                                                                                                                                       

fixtrue_001.py 輸入賬號(hào)密碼
用例1
.用例2
.用例3
.
fixtrue_002.py 用例4
.用例5
.用例6
.清理數(shù)據(jù)完成


================================================================================== 6 passed in 0.04s ===================================================================================

  上面的例子,如果test_1測(cè)試用例沒有傳fixture函數(shù)名login的話,fixture裝置將在執(zhí)行test_3測(cè)試用例開始前執(zhí)行一次,我去掉之后,再運(yùn)行結(jié)果如下:

  作為conftest.py文件傳入(擴(kuò)展)

  上面講的fixture作用域是session,一般結(jié)合conftest.py來使用,也就是作為conftest.py文件傳入。

  使用背景:如果我們有很多個(gè)前置函數(shù),寫在各個(gè)py文件中是不很亂?再或者說,我們很多個(gè)py文件想要使用同一個(gè)前置函數(shù)該怎么辦?這也就是conftest.py的作用。

  使用conftest.py的規(guī)則:

  conftest.py這個(gè)文件名是固定的,不可以更改。
  conftest.py與運(yùn)行用例在同一個(gè)包下,并且該包中有__init__.py文件
  使用的時(shí)候不需要導(dǎo)入conftest.py,會(huì)自動(dòng)尋找。
  來看個(gè)小栗子:我們新建了一個(gè)conftest.py文件,將前置函數(shù)的聲明寫在里面;在同一包下又新建了一個(gè)測(cè)試模塊,在測(cè)試方法中傳入了conftest.py中聲明的前置函數(shù)名。

# fixture 固定裝飾器,作用域:scope = 'session'
import pytest
@pytest.fixture()
def login():
    print("輸入賬號(hào)密碼")
    yield
    print("清理數(shù)據(jù)完成")

  

import pytest
# fixture scope = 'session',fixtrue_001.py
class TestLogin1():
	def test_1(self,login):
		print("用例1")
	def test_2(self):
		print("用例2")
	def test_3(self,login):
		print("用例3")


if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

fixtrue_001.py 輸入賬號(hào)密碼
用例1
.清理數(shù)據(jù)完成
用例2
.輸入賬號(hào)密碼
用例3
.清理數(shù)據(jù)完成


================================================================================== 3 passed in 0.02s ===================================================================================

  

  上面的栗子可以換一種寫法,但需要利用另外一個(gè)裝飾器。

  我們?cè)赾onftest.py中聲明完前置函數(shù)后,在測(cè)試模塊中除了使用傳入函數(shù)名的方式,還可以使用@pytest.mark.userfixtures()裝飾器。

  舉個(gè)小栗子:聲明前置函數(shù)的過程和上面一樣;我們?cè)诿總€(gè)測(cè)試方法上都加了@pytest.mark.userfixtures()裝飾器,傳入了前置函數(shù)名作為參數(shù);運(yùn)行結(jié)果和上圖一樣便不再展示。

import pytest
# fixture scope = 'session',fixtrue_001.py
class TestLogin1():
	@pytest.mark.usefixtures('login')
	def test_1(self):
		print("用例1")
	@pytest.mark.usefixtures('login')
	def test_2(self):
		print("用例2")
	def test_3(self):
		print("用例3")


if __name__ == '__main__':
    pytest.main()

  

fixtrue_001.py 輸入賬號(hào)密碼
用例1
.清理數(shù)據(jù)完成
輸入賬號(hào)密碼
用例2
.清理數(shù)據(jù)完成
用例3
.

================================================================================== 3 passed in 0.02s ===================================================================================

  

  如果有100個(gè)測(cè)試方法,這樣就要寫100個(gè)裝飾器,是不是不方便?

  這個(gè)時(shí)候如果你想要模塊中的每個(gè)測(cè)試用例都調(diào)用該固件,你也可以使用pytestmark標(biāo)記:如下代碼(注意pytestmark變量名不可更改),示例如下:

import pytest
# fixture scope = 'session',fixtrue_001.py
pytestmark = pytest.mark.usefixtures('login')
class TestLogin1():
	def test_1(self):
		print("用例1")
	def test_2(self):
		print("用例2")
	def test_3(self):
		print("用例3")


if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

fixtrue_001.py 輸入賬號(hào)密碼
用例1
.清理數(shù)據(jù)完成
輸入賬號(hào)密碼
用例2
.清理數(shù)據(jù)完成
輸入賬號(hào)密碼
用例3
.清理數(shù)據(jù)完成


================================================================================== 3 passed in 0.02s ===================================================================================

  

  注意:可以在測(cè)試函數(shù)前使用 @pytest.mark.usefixtures("fixture1","fixture2")標(biāo)記測(cè)試函數(shù)或者測(cè)試類。與在測(cè)試方法中添加 fixture 參數(shù)差不多,但是使用 usefixtures 不能使用 fixture 的返回值。

  補(bǔ)充說明一下conftest.py文件的作用域是當(dāng)前包內(nèi)(包括子包);如果函數(shù)調(diào)用固件優(yōu)先從當(dāng)前測(cè)試類中尋找,然后是模塊(.py文件)中,接著是當(dāng)前包中尋找(conftest.py中),如果沒有再找父包直至根目錄;如果我們要聲明全局的conftest.py文件,我們可以將其放在根目錄下。

  conftest.py作用范圍:測(cè)試類 > .py文件 > package

  Autouse參數(shù)介紹與使用

  調(diào)用fixture四種方法

  1.函數(shù)或類里面方法直接傳fixture的函數(shù)參數(shù)名稱

  2.使用裝飾器@pytest.mark.usefixtures()修飾

  3.使用pytestmark = pytest.mark.usefixtures('login')

  4.autouse=True自動(dòng)使用

  前面三種已經(jīng)講過,現(xiàn)在就是講第四種。

  我們?cè)谧鲎詣?dòng)化測(cè)試的時(shí)候,用例是非常多,如果每條用例都要去傳入前置函數(shù)名或裝飾器,很不方便。

  這時(shí)我們可以使用@pytest.fixture()中的參數(shù)autouse(自動(dòng)使用),將其設(shè)為true(默認(rèn)為false),這樣每個(gè)測(cè)試函數(shù)都會(huì)自動(dòng)調(diào)用該前置函數(shù)了。

  舉個(gè)小栗子:

import pytest

@pytest.fixture(autouse="true")
def login():
    print("輸入賬號(hào)密碼")


class TestLogin:
    def test_1(self):
        print("用例1")
    def test_2(self):
        print("用例2")

if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

============================== 2 passed in 0.05s ==============================

Process finished with exit code 0
輸入賬號(hào)密碼
PASSED                              [ 50%]用例1
輸入賬號(hào)密碼
PASSED                              [100%]用例2

  

  注意:

  對(duì)于那些不依賴于任何系統(tǒng)狀態(tài)或者外部數(shù)據(jù),又需要多次運(yùn)行的代碼,可以在 fixture 中添加 autouse=True選項(xiàng),例如 @pytest.fixture(autouse=True, scope="session")。

  但是,如果可以的話,盡量應(yīng)當(dāng)選擇參數(shù)傳遞或者 usefixtures 的方法而不是 autouse。autouse 會(huì)讓測(cè)試函數(shù)邏輯看上去沒有那么清晰,更像是一個(gè)特例。

  Params參數(shù)介紹與使用

  前面介紹Fixture定義的時(shí)候講了params,:arg params: 一個(gè)可選的形參列表,它將導(dǎo)致多個(gè)參數(shù)對(duì)夾具功能和所有測(cè)試的調(diào)用使用它。

  1.fixture可以帶參數(shù),params支持列表;

  2.默認(rèn)是None;

  3.對(duì)于param里面的每個(gè)值,fixture都會(huì)去調(diào)用執(zhí)行一次,就像執(zhí)行for循環(huán)一樣把params里的值遍歷一次。

  

  舉個(gè)例子:

import pytest
seq = [1,2,3]

@pytest.fixture(params=seq)
def test_data(request):
    print("參數(shù)")
    return request.param


class TestData:
    def test_1(self,test_data):
        print("用例",test_data)

if __name__ == '__main__':
    pytest.main()

  

運(yùn)行結(jié)果:

  原理:

  在 pytest 中有一個(gè)內(nèi)建的 fixture 叫做 request,代表 fixture 的調(diào)用狀態(tài)。request 有一個(gè)字段 param,可以使用類似@pytest.fixture(param=tasks_list)的方式,在 fixture 中使用 request.param的方式作為返回值供測(cè)試函數(shù)調(diào)用。其中 tasks_list 包含多少元素,該 fixture 就會(huì)被調(diào)用幾次,分別作用在每個(gè)用到的測(cè)試函數(shù)上。

  Ids參數(shù)介紹與使用

  ids通常可以與params一起使用,由于沒有指定 id,所以在輸出時(shí) pytest 會(huì)以 fixture 名加上數(shù)字作為標(biāo)識(shí),fixture 也可以指定 id,例如@pytest.fixture(param=tasks_list,ids=task_ids) ids可以是列表,也可以是函數(shù)供 pytest 生成 task 標(biāo)識(shí)。

  數(shù)字、字符串、布爾值和None將在測(cè)試ID中使用其通常的字符串表示形式,對(duì)于其他對(duì)象,pytest會(huì)根據(jù)參數(shù)名稱創(chuàng)建一個(gè)字符串,可以通過使用ids關(guān)鍵字參數(shù)來自定義用于測(cè)試ID的字符串。

 舉個(gè)例子:
import pytest
seq = [1,2,3]

@pytest.fixture(params=seq,ids=["a","b","c"])
def test_data(request):
    print("參數(shù)")
    # print(request)
    return request.param


class TestData:
    def test_1(self,test_data):
        print("用例",test_data)

if __name__ == '__main__':
    pytest.main()

  

  運(yùn)行結(jié)果:

  Name參數(shù)介紹與使用

  通常來說使用 fixture 的測(cè)試函數(shù)會(huì)將 fixture 的函數(shù)名作為參數(shù)傳遞,但是 pytest 也允許將 fixture 重命名。只需要使用@pytest.fixture(name="new")即可,在測(cè)試函數(shù)中使用該 fixture 時(shí)只需要傳入 new 即可。

import pytest


@pytest.fixture(name="new_fixture")
def test_name():
    pass

def test_1(new_fixture):
    print("測(cè)試用例1")

  

  運(yùn)行結(jié)果:

collecting ... collected 1 item

fixture_test03.py::test_1 PASSED                                         [100%]測(cè)試用例1


============================== 1 passed in 0.03s ==============================

  總結(jié):默認(rèn)使用fixture函數(shù)名稱作為參數(shù),也就是test_name作為參數(shù)傳入,如果使用name,就需要將name的值作為新的參數(shù)名稱傳遞給測(cè)試函數(shù)使用。

  總結(jié)

  以上就是pytest框架中fixture函數(shù)的介紹與使用,每種參數(shù)都介紹了一遍,原理和方法了解好,以便在實(shí)踐中得心應(yīng)手。如果對(duì)你有幫助或喜歡自動(dòng)化測(cè)試開發(fā)的朋友,可以加入右下方QQ交流群學(xué)習(xí)與探索,更多干貨與你分

享。

總結(jié)

以上是生活随笔為你收集整理的Pytest学习笔记2——前后置处理高级函数Fixture(完整篇)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。