pytest精髓__fixture

命令:fixture(scope='function',params=None,autouse=False,ids=None,name=None)

參數說明

scope:有四個級別參數函數"function"(默認),類"class",模組"module",整個測試項目"session"。

params:表示fixture的參數化功能。

 1 import pytest
 2 data = ['老子', '孔子', '孟子']
 3 
 4 @pytest.fixture(params=data,ids=['user=Socrates','user=Platon','user=Aristotle'])
 5 def login(request):
 6     print('哲學興起')
 7     yield request.param
 8     print('哲學消沉')
 9 
10 class Test_01:
11     def test_01(self, login):
12         print('---用例01---')
13         print('思想家:%s' % login)
14 
15 if __name__ == '__main__':
16     pytest.main(['-vs'])

autouse:如果True,自動為用例使用。如果為False則需要設置來激活fixture。

 1 import pytest
 2 @pytest.fixture(autouse=True)
 3 def login():
 4     print('\n早出')
 5     yield
 6     print('\n晚歸!')
 7 class Test_Login():
 8     def test_01(self):
 9         print('---小蘭---')
10     def test_02(self):
11         print('---任正非---')
12 if __name__ == '__main__':
13     pytest.main(['-vs'])

ids:ids表示在fixture對參數化的內容進行加上標識,比如讓別人知道這個傳入的參數是什麼意思。

name:name參數表示對fixture的名稱進行重命名。

 1 import pytest
 2 @pytest.fixture(name='我是冰箱')
 3 def login():
 4     print('\n打開冰箱')
 5     yield
 6     print('\n關上冰箱!')
 7 class Test_Login():
 8     def test_01(self, 我是冰箱):
 9         print('---把大象塞進冰箱---')
10 if __name__ == '__main__':
11     pytest.main(['-vs'])

 

例子1  fixture調用與不調用的區別

 1 import pytest
 2 @pytest.fixture()
 3 def login():
 4     print('登錄操作')
 5     yield
 6     print('退出登錄')
 7 class Test_Login():
 8     def test_01(self, login):
 9         print('需要用到登錄!')
10     def test_02(self):
11         print('不需要登錄!')
12     def test_03(self, login):
13         print('這裡需要用到登錄!')
14 if __name__ == '__main__':
15     pytest.main(['-vs'])

例子2  異常後依然會執行後置操作

 1 import pytest
 2 @pytest.fixture()
 3 def login():
 4     print('登錄操作')
 5     yield
 6     print('退出登錄!')
 7 class Test_Login():
 8     def test_01(self, login):
 9         print('需要用到登錄!')
10         assert 1==1
11     def test_02(self):
12         print('不需要登錄!')
13     def test_03(self, login):
14         print('這裡需要用到登錄!')
15         assert 1==2
16 if __name__ == '__main__':
17     pytest.main(['-vs']

例子2  同時調用兩個fixture

 1 import pytest
 2 @pytest.fixture()
 3 def login():
 4     print('登錄操作')
 5     yield
 6     print('退出登錄!')
 7 @pytest.fixture()
 8 def log():
 9     print('打開日誌功能!')
10     yield 
11     print('關閉日誌功能!')
12     
13 class Test_Login():
14     def test_01(self, login, log):
15         print('需要用到登錄!')
16     def test_02(self):
17         print('不需要登錄!')
18     def test_03(self, log, login):
19         print('這裡需要用到登錄!')
20 if __name__ == '__main__':
21     pytest.main(['-vs'])

 

 

 

月缺不改光,劍折不改剛。有志向的人自信自強;

君子量不極,胸吞百川流。有志向的人心有遠方;

丈夫非無淚,不灑離別間。有志向的人情深意長;

及時當勉勵,歲月不待人。有志向的人不會虛度時光。

人生感意氣,功名誰復論。有志向的人看淡名利。

感時思報國,拔劍起蒿萊。有志向的人是最可靠的力量。

願君學長松,慎勿作桃李。