- 前面一篇講了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é)果
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é)果
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é)果
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é)果
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)有效。
創(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é)果
知識點(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é)果
小結(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"]
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
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"])
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í)行
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)用
參考鏈接
https://www.cnblogs.com/longronglang/p/13869445.html
https://www.cnblogs.com/poloyy/category/1690628.html?page=2