pytest框架之fixture詳細(xì)使用詳解
本人之前寫(xiě)了一套基于unnitest框架的UI自動(dòng)化框架,但是發(fā)現(xiàn)了pytest框架之后覺(jué)得unnitest太low,現(xiàn)在重頭開(kāi)始學(xué)pytest框架,一邊學(xué)習(xí)一邊記錄,和大家分享,話不多說(shuō),那就先從pytest框架的精髓fixture說(shuō)起吧!
簡(jiǎn)介:
fixture區(qū)別于unnitest的傳統(tǒng)單元測(cè)試(setup/teardown)有顯著改進(jìn):
1.有獨(dú)立的命名,并通過(guò)聲明它們從測(cè)試函數(shù)、模塊、類或整個(gè)項(xiàng)目中的使用來(lái)激活。
2.按模塊化的方式實(shí)現(xiàn),每個(gè)fixture都可以互相調(diào)用。
3.fixture的范圍從簡(jiǎn)單的單元測(cè)試到復(fù)雜的功能測(cè)試,可以對(duì)fixture配置參數(shù),或者跨函數(shù)function,類class,模塊module或整個(gè)測(cè)試session范圍。
(很重要!?。。ê苤匾。。。ê苤匾。。。?/p>
謹(jǐn)記:當(dāng)我們使用pytest框架寫(xiě)case的時(shí)候,一定要拿它的命令規(guī)范去case,這樣框架才能識(shí)別到哪些case需要執(zhí)行,哪些不需要執(zhí)行。
用例設(shè)計(jì)原則
文件名以test_*.py文件和*_test.py
以test_開(kāi)頭的函數(shù)
以Test開(kāi)頭的類
以test_開(kāi)頭的方法
fixture可以當(dāng)做參數(shù)傳入
定義fixture跟定義普通函數(shù)差不多,唯一區(qū)別就是在函數(shù)上加個(gè)裝飾器@pytest.fixture(),fixture命名不要以test開(kāi)頭,跟用例區(qū)分開(kāi)。fixture是有返回值得,沒(méi)有返回值默認(rèn)為None。用例調(diào)用fixture的返回值,直接就是把fixture的函數(shù)名稱當(dāng)做變量名稱。
ex:
import pytest @pytest.fixture() def test1(): a = 'leo' return a def test2(test1): assert test1 == 'leo' if __name__ == '__main__': pytest.main('-q test_fixture.py')
輸出:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 itemtest_fixture.py . [100%]
========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0
使用多個(gè)fixture
如果用例需要用到多個(gè)fixture的返回?cái)?shù)據(jù),fixture也可以返回一個(gè)元祖,list或字典,然后從里面取出對(duì)應(yīng)數(shù)據(jù)。
ex:
import pytest @pytest.fixture() def test1(): a = 'leo' b = '123456' print('傳出a,b') return (a, b) def test2(test1): u = test1[0] p = test1[1] assert u == 'leo' assert p == '123456' print('元祖形式正確') if __name__ == '__main__': pytest.main('-q test_fixture.py') 輸出結(jié)果: platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item test_fixture.py 傳出a,b .元祖形式正確 [100%] ========================== 1 passed in 0.02 seconds =========================== Process finished with exit code 0
當(dāng)然也可以分成多個(gè)fixture,然后在用例中傳多個(gè)fixture參數(shù)
import pytest @pytest.fixture() def test1(): a = 'leo' print('\n傳出a') return a @pytest.fixture() def test2(): b = '123456' print('傳出b') return b def test3(test1, test2): u = test1 p = test2 assert u == 'leo' assert p == '123456' print('傳入多個(gè)fixture參數(shù)正確') if __name__ == '__main__': pytest.main('-q test_fixture.py') 輸出結(jié)果: ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item test_fixture.py 傳出a 傳出b .傳入多個(gè)fixture參數(shù)正確
fixture互相調(diào)用
import pytest @pytest.fixture() def test1(): a = 'leo' print('\n傳出a') return a def test2(test1): assert test1 == 'leo' print('fixture傳參成功') if __name__ == '__main__': pytest.main('-q test_fixture.py') 輸出結(jié)果: platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item test_fixture.py 傳出a .fixture傳參成功 [100%] ========================== 1 passed in 0.03 seconds =========================== Process finished with exit code 0
介紹完了fixture的使用方式,現(xiàn)在介紹一下fixture的作用范圍(scope)
fixture的作用范圍
fixture里面有個(gè)scope參數(shù)可以控制fixture的作用范圍:session>module>class>function
-function:每一個(gè)函數(shù)或方法都會(huì)調(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
fixture源碼詳解
fixture(scope='function',params=None,autouse=False,ids=None,name=None):
scope:有四個(gè)級(jí)別參數(shù)"function"(默認(rèn)),"class","module","session"
params:一個(gè)可選的參數(shù)列表,它將導(dǎo)致多個(gè)參數(shù)調(diào)用fixture功能和所有測(cè)試使用它。
autouse:如果True,則為所有測(cè)試激活fixture func可以看到它。如果為False則顯示需要參考來(lái)激活fixture
ids:每個(gè)字符串id的列表,每個(gè)字符串對(duì)應(yīng)于params這樣他們就是測(cè)試ID的一部分。如果沒(méi)有提供ID它們將從params自動(dòng)生成
name:fixture的名稱。這默認(rèn)為裝飾函數(shù)的名稱。如果fixture在定義它的統(tǒng)一模塊中使用,夾具的功能名稱將被請(qǐng)求夾具的功能arg遮蔽,解決這個(gè)問(wèn)題的一種方法時(shí)將裝飾函數(shù)命令"fixture_<fixturename>"然后使用"@pytest.fixture(name='<fixturename>')"。
具體闡述一下scope四個(gè)參數(shù)的范圍
scope="function"
@pytest.fixture()如果不寫(xiě)參數(shù),參數(shù)就是scope="function",它的作用范圍是每個(gè)測(cè)試用例來(lái)之前運(yùn)行一次,銷毀代碼在測(cè)試用例之后運(yùn)行。
import pytest @pytest.fixture() def test1(): a = 'leo' print('\n傳出a') return a @pytest.fixture(scope='function') def test2(): b = '男' print('\n傳出b') return b def test3(test1): name = 'leo' print('找到name') assert test1 == name def test4(test2): sex = '男' print('找到sex') assert test2 == sex if __name__ == '__main__': pytest.main('-q test_fixture.py') 輸出結(jié)果: platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items test_fixture.py 傳出a .找到name 傳出b .找到sex [100%] ========================== 2 passed in 0.04 seconds ===========================
放在類中實(shí)現(xiàn)結(jié)果也是一樣的
import pytest @pytest.fixture() def test1(): a = 'leo' print('\n傳出a') return a @pytest.fixture(scope='function') def test2(): b = '男' print('\n傳出b') return b class TestCase: def test3(self, test1): name = 'leo' print('找到name') assert test1 == name def test4(self, test2): sex = '男' print('找到sex') assert test2 == sex if __name__ == '__main__': pytest.main(['-s', 'test_fixture.py']) 輸出結(jié)果: platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items test_fixture.py 傳出a .找到name 傳出b .找到sex [100%] ========================== 2 passed in 0.03 seconds =========================== Process finished with exit code 0
scope="class"
fixture為class級(jí)別的時(shí)候,如果一個(gè)class里面有多個(gè)用例,都調(diào)用了次fixture,那么此fixture只在此class里所有用例開(kāi)始前執(zhí)行一次。
import pytest @pytest.fixture(scope='class') def test1(): b = '男' print('傳出了%s, 且只在class里所有用例開(kāi)始前執(zhí)行一次?。?!' % b) return b class TestCase: def test3(self, test1): name = '男' print('找到name') assert test1 == name def test4(self, test1): sex = '男' print('找到sex') assert test1 == sex if __name__ == '__main__': pytest.main(['-s', 'test_fixture.py']) 輸出結(jié)果: platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items test_fixture.py 傳出了男, 且只在class里所有用例開(kāi)始前執(zhí)行一次?。。? .找到name .找到sex [100%] ========================== 2 passed in 0.05 seconds =========================== Process finished with exit code 0
scope="module"
fixture為module時(shí),在當(dāng)前.py腳本里面所有用例開(kāi)始前只執(zhí)行一次。
import pytest ##test_fixture.py @pytest.fixture(scope='module') def test1(): b = '男' print('傳出了%s, 且在當(dāng)前py文件下執(zhí)行一次?。。? % b) return b def test3(test1): name = '男' print('找到name') assert test1 == name class TestCase: def test4(self, test1): sex = '男' print('找到sex') assert test1 == sex if __name__ == '__main__': pytest.main(['-s', 'test_fixture.py']) 輸出結(jié)果: ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items test_fixture.py 傳出了男, 且在當(dāng)前py文件下執(zhí)行一次?。?! .找到sex .找到name [100%] ========================== 2 passed in 0.03 seconds =========================== Process finished with exit code 0
scope="session"
fixture為session級(jí)別是可以跨.py模塊調(diào)用的,也就是當(dāng)我們有多個(gè).py文件的用例的時(shí)候,如果多個(gè)用例只需調(diào)用一次fixture,那就可以設(shè)置為scope="session",并且寫(xiě)到conftest.py文件里。
conftest.py文件名稱時(shí)固定的,pytest會(huì)自動(dòng)識(shí)別該文件。放到項(xiàng)目的根目錄下就可以全局調(diào)用了,如果放到某個(gè)package下,那就在改package內(nèi)有效。
文件目錄為
import pytest # conftest.py @pytest.fixture(scope='session') def test1(): sex = '男' print('獲取到%s' % sex) return sex
import pytest # test_fixture.py def test3(test1): name = '男' print('找到name') assert test1 == name if __name__ == '__main__': pytest.main(['-s', 'test_fixture.py'])
import pytest # test_fixture1.py class TestCase: def test4(self, test1): sex = '男' print('找到sex') assert test1 == sex if __name__ == '__main__': pytest.main(['-s', 'test_fixture1.py'])
如果需要同時(shí)執(zhí)行兩個(gè)py文件,可以在cmd中在文件py文件所在目錄下執(zhí)行命令:pytest -s test_fixture.py test_fixture1.py
執(zhí)行結(jié)果為:
================================================= test session starts =================================================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:
collected 2 itemstest_fixture.py 獲取到男
找到name
.
test_fixture1.py 找到sex
.============================================== 2 passed in 0.05 seconds ===============================================
調(diào)用fixture的三種方法
1.函數(shù)或類里面方法直接傳fixture的函數(shù)參數(shù)名稱
import pytest # test_fixture1.py @pytest.fixture() def test1(): print('\n開(kāi)始執(zhí)行function') def test_a(test1): print('---用例a執(zhí)行---') class TestCase: def test_b(self, test1): print('---用例b執(zhí)行') 輸出結(jié)果: test_fixture1.py 開(kāi)始執(zhí)行function .---用例a執(zhí)行--- 開(kāi)始執(zhí)行function .---用例b執(zhí)行 [100%] ========================== 2 passed in 0.05 seconds =========================== Process finished with exit code 0
2.使用裝飾器@pytest.mark.usefixtures()修飾需要運(yùn)行的用例
import pytest # test_fixture1.py @pytest.fixture() def test1(): print('\n開(kāi)始執(zhí)行function') @pytest.mark.usefixtures('test1') def test_a(): print('---用例a執(zhí)行---') @pytest.mark.usefixtures('test1') class TestCase: def test_b(self): print('---用例b執(zhí)行---') def test_c(self): print('---用例c執(zhí)行---') if __name__ == '__main__': pytest.main(['-s', 'test_fixture1.py']) 輸出結(jié)果: platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 3 items test_fixture1.py 開(kāi)始執(zhí)行function .---用例a執(zhí)行--- 開(kāi)始執(zhí)行function .---用例b執(zhí)行--- 開(kāi)始執(zhí)行function .---用例c執(zhí)行--- [100%] ========================== 3 passed in 0.06 seconds =========================== Process finished with exit code 0
疊加usefixtures
如果一個(gè)方法或者一個(gè)class用例想要同時(shí)調(diào)用多個(gè)fixture,可以使用@pytest.mark.usefixture()進(jìn)行疊加。注意疊加順序,先執(zhí)行的放底層,后執(zhí)行的放上層。
import pytest # test_fixture1.py @pytest.fixture() def test1(): print('\n開(kāi)始執(zhí)行function1') @pytest.fixture() def test2(): print('\n開(kāi)始執(zhí)行function2') @pytest.mark.usefixtures('test1') @pytest.mark.usefixtures('test2') def test_a(): print('---用例a執(zhí)行---') @pytest.mark.usefixtures('test2') @pytest.mark.usefixtures('test1') class TestCase: def test_b(self): print('---用例b執(zhí)行---') def test_c(self): print('---用例c執(zhí)行---') if __name__ == '__main__': pytest.main(['-s', 'test_fixture1.py']) 輸出結(jié)果: ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 3 items test_fixture1.py 開(kāi)始執(zhí)行function2 開(kāi)始執(zhí)行function1 .---用例a執(zhí)行--- 開(kāi)始執(zhí)行function1 開(kāi)始執(zhí)行function2 .---用例b執(zhí)行--- 開(kāi)始執(zhí)行function1 開(kāi)始執(zhí)行function2 .---用例c執(zhí)行--- [100%] ========================== 3 passed in 0.03 seconds =========================== Process finished with exit code 0
usefixtures與傳fixture區(qū)別
如果fixture有返回值,那么usefixture就無(wú)法獲取到返回值,這個(gè)是裝飾器usefixture與用例直接傳fixture參數(shù)的區(qū)別。
當(dāng)fixture需要用到return出來(lái)的參數(shù)時(shí),只能講參數(shù)名稱直接當(dāng)參數(shù)傳入,不需要用到return出來(lái)的參數(shù)時(shí),兩種方式都可以。
fixture自動(dòng)使用autouse=True
當(dāng)用例很多的時(shí)候,每次都傳這個(gè)參數(shù),會(huì)很麻煩。fixture里面有個(gè)參數(shù)autouse,默認(rèn)是False沒(méi)開(kāi)啟的,可以設(shè)置為T(mén)rue開(kāi)啟自動(dòng)使用fixture功能,這樣用例就不用每次都去傳參了
autouse設(shè)置為T(mén)rue,自動(dòng)調(diào)用fixture功能
import pytest # test_fixture1.py @pytest.fixture(scope='module', autouse=True) def test1(): print('\n開(kāi)始執(zhí)行module') @pytest.fixture(scope='class', autouse=True) def test2(): print('\n開(kāi)始執(zhí)行class') @pytest.fixture(scope='function', autouse=True) def test3(): print('\n開(kāi)始執(zhí)行function') def test_a(): print('---用例a執(zhí)行---') def test_d(): print('---用例d執(zhí)行---') class TestCase: def test_b(self): print('---用例b執(zhí)行---') def test_c(self): print('---用例c執(zhí)行---') if __name__ == '__main__': pytest.main(['-s', 'test_fixture1.py']) 輸出結(jié)果: ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 4 items test_fixture1.py 開(kāi)始執(zhí)行module 開(kāi)始執(zhí)行class 開(kāi)始執(zhí)行function .---用例a執(zhí)行--- 開(kāi)始執(zhí)行class 開(kāi)始執(zhí)行function .---用例d執(zhí)行--- 開(kāi)始執(zhí)行class 開(kāi)始執(zhí)行function .---用例b執(zhí)行--- 開(kāi)始執(zhí)行function .---用例c執(zhí)行--- [100%]
conftest.py的作用范圍
一個(gè)工程下可以建多個(gè)conftest.py的文件,一般在工程根目錄下設(shè)置的conftest文件起到全局作用。在不同子目錄下也可以放conftest.py的文件,作用范圍只能在改層級(jí)以及以下目錄生效。
項(xiàng)目實(shí)例:
目錄結(jié)構(gòu):
1.conftest在不同的層級(jí)間的作用域不一樣
# conftest層級(jí)展示/conftest.py import pytest @pytest.fixture(scope='session', autouse=True) def login(): print('----準(zhǔn)備登錄----') # conftest層級(jí)展示/sougou_login/conftest import pytest @pytest.fixture(scope='session', autouse=True) def bai_du(): print('-----登錄百度頁(yè)面-----') # conftest層級(jí)展示/sougou_login/login_website import pytest class TestCase: def test_login(self): print('hhh,成功登錄百度') if __name__ == '__main__': pytest.main(['-s', 'login_website.py']) 輸出結(jié)果: ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\conftest層級(jí)演示\sougou_login, inifile:collected 1 item login_website.py ----準(zhǔn)備登錄---- -----登錄百度頁(yè)面----- .hhh,成功登錄百度 [100%] ========================== 1 passed in 0.03 seconds =========================== Process finished with exit code 0
2.conftest是不能跨模塊調(diào)用的(這里沒(méi)有使用模塊調(diào)用)
# conftest層級(jí)演示/log/contfest.py import pytest @pytest.fixture(scope='function', autouse=True) def log_web(): print('打印頁(yè)面日志成功') # conftest層級(jí)演示/log/log_website.py import pytest def test_web(): print('hhh,成功一次打印日志') def test_web1(): print('hhh,成功兩次打印日志') if __name__ == '__main__': pytest.main(['-s', 'log_website.py']) 輸出結(jié)果: ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 rootdir: C:\Program Files\PycharmProjects\conftest層級(jí)演示\log, inifile: collected 2 items log_website.py ----準(zhǔn)備登錄---- 打印頁(yè)面日志成功 hhh,成功一次打印日志 .打印頁(yè)面日志成功 hhh,成功兩次打印日志 . ========================== 2 passed in 0.02 seconds ===========================
到此這篇關(guān)于pytest框架之fixture詳細(xì)使用詳解的文章就介紹到這了,更多相關(guān)pytest fixture內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python利用緩存流實(shí)現(xiàn)壓縮PDF文件
在Python中,有許多庫(kù)可以用來(lái)壓縮PDF文件,其中最常用的是PyPDF2和PDFMiner,本文將為大家介紹一個(gè)新的方法,即使用緩存流壓縮PDF文件,感興趣的可以了解下2023-08-08使用Python處理Excel文件并將數(shù)據(jù)存儲(chǔ)到PostgreSQL的方法
在日常工作中,我們經(jīng)常會(huì)遇到需要處理大量文件并將數(shù)據(jù)存儲(chǔ)至數(shù)據(jù)庫(kù)或整合到一個(gè)文件的需求,本文將向大家展示如何使用Python處理Excel文件并將數(shù)據(jù)存儲(chǔ)到PostgreSQL數(shù)據(jù)庫(kù)中,需要的朋友可以參考下2024-01-01Python接口測(cè)試環(huán)境搭建過(guò)程詳解
這篇文章主要介紹了Python接口測(cè)試環(huán)境搭建過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06解決Python調(diào)用df.to_csv()出現(xiàn)中文亂碼的問(wèn)題
在Python使用df.to_csv()時(shí),若出現(xiàn)中文亂碼,可通過(guò)加入?yún)?shù)encoding="utf_8_sig"解決,"utf-8"編碼不包含BOM,直接處理文件時(shí)會(huì)將BOM誤讀為內(nèi)容;而"utf_8_sig"會(huì)識(shí)別并處理BOM,避免亂碼,此方法為實(shí)踐經(jīng)驗(yàn),供參考2024-09-09快速解決cv2.imread()讀取圖像為BGR的問(wèn)題
這篇文章主要介紹了快速解決cv2.imread()讀取圖像為BGR的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03python實(shí)現(xiàn)解數(shù)獨(dú)程序代碼
最近在帶孩子學(xué)習(xí)數(shù)獨(dú),職業(yè)使然,就上網(wǎng)搜了下相關(guān)程序的解法,這里分享給大家,希望對(duì)大家學(xué)習(xí)python有所幫助2017-04-04