Pytest系列(二)
阿新 • • 發佈:2022-03-13
一、Fixture韌體
部分用例之前或之後執行,部分類之前或之後執行。模組或會話之前或之後的操
作。
Fixture完整的方法如下:
@pytest.fixture(scope="作用域",params="資料驅動",autouse="是否自動執
行",ids=“引數別名”,name="Fixture別名")
scope:可選值:
function(函式,預設),class(類),module(模組)
,package/session(會
話)
1.基礎應用:scope是function
1 import pytest
2
3 @pytest.fixture(scope="function")
4 def execute_sql():
5 print("執行SQL語句")
6 yield "張三"
7 print("關閉資料庫連線")
8
9 class TestApi:
10
11 def test_01_mashang(self):
12 print("土撥鼠1")
13
14 def test_02_jiaoyu(self,execute_sql):
15 print("土撥鼠2"+execute_sql)
在函式中的引數中通過execute_sql名稱呼叫。
return:返回函式的結果,return之後的程式碼不會執行。yield:帶有yield函式叫生成器。yield之後的程式碼會執行。
2.scope為class
1 import pytest
2
3 @pytest.fixture(scope="class")
4 def execute_sql():
5 print("執行SQL語句")
6 yield "張三"
7 print("關閉資料庫連線")
8
9 @pytest.mark.usefixtures("execute_sql")
10 class TestApi:
11
12 def test_01_mashang(self):
13 print("土撥鼠a1")
14
15 def test_02_jiaoyu(self):
16 print("土撥鼠b2")
17
18 class TestMashang:
19 def test_baili(self):
20 print("土撥鼠哈哈哈")
通過裝飾器@pytest.mark.usefixtures("execute_sql")呼叫。
3.scope作用域是module或package/session,那麼需要結合conftest.py使
用。
(1)conftest.py專門用於存放韌體fixtue的配置檔案,名稱是固定的,不能更改。
(2)在conftest.py檔案中的fixtue在呼叫時都不需要導包。
(3)conftest.py檔案可以有多個,並且多個conftest.py檔案的多個fixture之間沒有衝突。
(4)模組級別和session模組一般都是自動執行。