Pytest学习(四) - fixture的使用 (3)

Pytest学习(四) - fixture的使用

小结:

在类声明上面加 @pytest.mark.usefixtures() ,代表这个类里面所有测试用例都会调用该fixture

可以叠加多个 @pytest.mark.usefixtures() ,先执行的放底层,后执行的放上层

可以传多个fixture参数,先执行的放前面,后执行的放后面

如果fixture有返回值,用 @pytest.mark.usefixtures() 是无法获取到返回值的,必须用传参的方式(参考方式一)

不是test开头,加了装饰器也不会执行fixture

fixture依赖其他fixture的调用

添加了 @pytest.fixture ,如果fixture还想依赖其他fixture,需要用函数传参的方式,不能用 @pytest.mark.usefixtures() 的方式,否则会不生效

示例代码如下:

# -*- coding: utf-8 -*- # @Time : 2020/10/24 20:23 # @Author : longrong.lang # @FileName: test_fixtureRelyCall.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang ''' fixture依赖其他fixture的调用示例 ''' import pytest @pytest.fixture(scope='session') # 打开浏览器 def openBrowser(): print('\n打开Chrome浏览器') # @pytest.mark.usefixtures('openBrowser')这么写是不行的哦,肯定不好使 @pytest.fixture() # 输入账号密码 def loginAction(openBrowser): print('\n输入账号密码') # 登录过程 def test_login(loginAction): print('\n点击登录进入系统') if __name__ == '__main__': pytest.main(["-q", "test_fixtureRelyCall.py"]) 输出结果:

Pytest学习(四) - fixture的使用

fixture的params

@pytest.fixture有一个params参数,接受一个列表,列表中每个数据都可以作为用例的输入。也就说有多少数据,就会形成多少用例,具体示例代码如下:

# -*- coding: utf-8 -*- # @Time : 2020/10/24 20:30 # @Author : longrong.lang # @FileName: test_fixtureParams.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang ''' fixture的params示例 ''' import pytest seq=[1,2] @pytest.fixture(params=seq) def params(request): # request用来接收param列表数据 return request.param def test_params(params): print(params) assert 1 == params 输出结果:

Pytest学习(四) - fixture的使用

fixture之yield实现teardown

fixture里面的teardown,可以用yield来唤醒teardown的执行,示例代码如下:

# -*- coding: utf-8 -*- # @Time : 2020/10/24 20:44 # @Author : longrong.lang # @FileName: test_fixtrueYield.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang ''' fixture之yield示例 ''' # !/usr/bin/env python # -*- coding: utf-8 -*- import pytest @pytest.fixture(scope='module') def open(): print("打开浏览器!!!") yield print('关闭浏览器!!!') def test01(): print("\n我是第一个用例") def test02(open): print("\n我是第二个用例") if __name__ == '__main__': pytest.main(["-q", "test_fixtrueYield.py"]) 输出结果:

Pytest学习(四) - fixture的使用

yield遇到异常

还在刚才的代码中修改,将test01函数中添加异常,具体代码如下:

# -*- coding: utf-8 -*- # @Time : 2020/10/24 20:44 # @Author : longrong.lang # @FileName: test_fixtrueYield.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang ''' fixture之yield示例 ''' # !/usr/bin/env python # -*- coding: utf-8 -*- import pytest @pytest.fixture(scope='module') def open(): print("打开浏览器!!!") yield print('关闭浏览器!!!') def test01(): print("\n我是第一个用例") # 如果第一个用例异常了,不影响其他的用例执行 raise Exception #此处异常 def test02(open): print("\n我是第二个用例") if __name__ == '__main__': pytest.main(["-q", "test_fixtrueYield.py"]) 输出结果:

Pytest学习(四) - fixture的使用

小结

如果yield前面的代码,即setup部分已经抛出异常了,则不会执行yield后面的teardown内容

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zygyfj.html