fixture的目的是提供一個固定的基線測試可以可靠的重復執行;
相當於我們上一篇文章寫到的setup和teardown。但是使用起來它不在限於固定的名稱,會更加的方便靈活;
fixture從簡單的單元擴展到復雜的功能測試,允許根據配置和組件選項進行參數化,或者跨函數、類、模塊或整個測試范圍重用。
本篇文章主要寫fixture函數中的scope參數scope參數的值有:function(默認)class session module
1.如何創建一個fixture函數
import pytest #通過裝飾器的方式編寫一個fixture函數,提供安裝和拆卸功能 @pytest.fixture(scope='function') def fix_test(): print('----- 我是fixture函數 -----') # 通過參數的形式將fixture函數傳入到測試函數中,用來實現fixture函數 def test1(fix_test): print('我是第一個測試用例') print('我需要依賴fixture函數') def test2(): print('我是第二個測試用例') print('我不需要依賴fixture函數') def test3(fix_test): print('我是第三個測試用例') print('我需要依賴fixture函數')
執行結果可以清楚的看到三個測試用例執行其中第一個和第三個是執行了fixture函數。第二個測試用例沒有執行fixture函數
2.上面例子只看到了fixture實現了安裝功能,並沒有實現拆卸功能。如果想要fixture函數中實現拆卸功能或者測試用例中需要將fixture函數提供一個值,則需要用到yield關鍵字。
import pytest #通過裝飾器的方式編寫一個fixture函數,提供安裝和拆卸功能 @pytest.fixture(scope='function') def fix_test(): print('----- 創建瀏覽器驅動器對象 -----') # 在我們的自動化測試中都需要用到瀏覽器驅動器對象。 # 在fixture函數中更多的使用的是yield關鍵字來返回 driver = 'Chrome' yield driver # 在yield關鍵字后則是我們的拆卸功能 print('銷毀瀏覽器驅動器對象') # 通過參數的形式將fixture函數傳入到測試函數中,用來實現fixture函數 def test1(fix_test): print('打開百度') def test2(): print('我是第二個測試用例') print('我不需要依賴fixture函數') def test3(fix_test): print('打開淘寶')
3.conftest.py文件的編寫
在整個測試過程中如果想要實現fixture函數跨類或模塊使用,則可以將fixture函數寫到conftest.py文件中,在測試模塊中不需要導入conftest.py文件,pytest會自動發現它;
注意:1.conftest.py文件名不可修改;2.conftest.py文件必須和測試模塊在同一個package內,且這個package有__init__.py文件;
conftest.py文件 # scope參數的值為class則是類級別的fixture函數,和setup_class teardown_class 執行相同
# scope參數的值為session和module的區別
# 為session時fixture函數作用域整個測試,為module時fixture作用於測試的每個模塊 @pytest.fixture(scope='session') def fix_test(): print('----- 創建瀏覽器驅動器對象 -----') driver = 'Chrome' yield driver print('銷毀瀏覽器驅動器對象')
第一個測試模塊 class Test_web(): def test1(self,fix_test): print('%s-----打開京東'%fix_test) def test2(self,fix_test): print('%s-----打開唯品會' % fix_test)
第二個測試模塊 def test1(fix_test): print('%s-----打開百度'%fix_test) def test2(): print('我是第二個測試用例') print('我不需要依賴fixture函數') def test3(fix_test): print('%s-----打開淘寶'%fix_test)