pytest精髓__fixture

2022-10-29,

命令: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'])

月缺不改光,剑折不改刚。有志向的人自信自强;

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

丈夫非无泪,不洒离别间。有志向的人情深意长;

及时当勉励,岁月不待人。有志向的人不会虚度时光。

人生感意气,功名谁复论。有志向的人看淡名利。

感时思报国,拔剑起蒿莱。有志向的人是最可靠的力量。

愿君学长松,慎勿作桃李。

pytest精髓__fixture的相关教程结束。

《pytest精髓__fixture.doc》

下载本文的Word格式文档,以方便收藏与打印。