pytest之fixtrue实现setup、teardown

1.前言概述

pytest.fixtrue()是把setUp()、setUpClass()、tearDown()、tearDownClass()整合到了一起。灵活度增加了,可以自定义函数名字放进方法里面去执行。对于用习惯了testNg的来说,难免有些不适应。不过存在就有道理,fixtrue也是有它的优势的。
各属性含义:

  • scope 作用范围

    • @pytest.fixture() 默认是scope='function'
    • @pytest.fixture(scope='function') 在测试用例之前执行一次(def aaa)
    • @pytest.fixture(scope='class') 每个测试类之前执行一次(class A)
    • @pytest.fixture(scope='module') 每个测试模块执行一次(*.py)
    • @pytest.fixture(scope='session') 多个测试模块执行一次
  • autouse 自动调用

    • @pytest.fixture(scope=‘function’,autouse=“true”) 默认是false,不想再每个方法中添加设置的函数名,可以把该值设置为true。带来的问题就是每个用例执行的时候都会调用该方法。根据实际场景使用。
  • params传入参数

    • 暂未考虑到使用场景
  • ids

    • 待完善

2.fixtrue实现setUp()

  • setUp() 每个用例执行前,执行一次。场景:UI自动化的登陆,每个用例执行前都需要去登陆
# contest.py

@pytest.fixture(scope='function')
def login(self):
	print('++++++++++++++++++++++++++this is a fixture+++++++++++++++++++++++++++++')

把login放到测试类的上面。保证每个测试方法执行前都会调用。

# test_cgi,py

@pytest.mark.usefixtures('login')
class TestMyClass:

    def test_one(self):
        x = "this"
        assert "" in x

    def test_two(self):
        x = "hello"
        assert x in 'hello'

如果只想某个方法使用,把login以入参的形式传入。或者@pytest.mark.usefixtures('login')放到某个方法的上面

# 方法一:
def test_two(self,login):
    x = "hello"
    assert x in 'hello'
    
# 方法二
@pytest.mark.usefixtures('login')
def test_two(self,login):
    x = "hello"
    assert x in 'hello'

3.fixtrue实现tearDown()

  • **tearDown()**每个用例执行完,执行一次。

@pytest.fixture(scope="function",autouse=True)
def open():
    print("打开浏览器,并且打开百度首页")
    yield
    print("执行teardown!")

想如上操作,把open传入类的上面、方法上面、入参形式传入。可实现yield之前是setUp操作,之后是teardown操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值