pytest.fixture实现数据驱动详解

一.为什么要做数据驱动:

数据驱动本质上是为了减少重复代码,增加代码重用率。

而自动化测试可以总结为如下步骤:

1.测试执行前的准备工作

2.执行测试

3.测试后的清理工作

如果直接通过pytest提供的前置和后置方法实现,存在着一个明显的弊端,就是在同一个测试类中,如果存在多个测试方法,每个测试方法需要不同的前置或者后置方法该如何处理。这个时候pytest.fixture()方法就派上用场了。

二.pytest.fixture()方法讲解:

pytest.fixture()方法可用作初始化测试服务,数据和状态,也可以用来测试执行前,后,进行测试的前置、后置操作。

pytest.fixture()语法如下:

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

pytest.fixture()5个参数的详解:

1.scope:(决定pytest.fixture作用范围)

用于控制fixture的作用范围,这个参数有一下4个级别:

1)funciton:在每个函数或者类方法中都会调用(默认)

2)class:在每一个类中只调用一次

3)module:每一个.py文件调用一次,该文件内可以有多个函数和类

4)session:一个会话调用一次

下面演示pytest.fixture的用法:

import pytest


#首先,在fixture函数上加@pytest.fixture装饰器
@pytest.fixture()
def my_method():
    print('This is pytest.fixture')

#然后,把fixture函数的函数名作为参数,传入测试用例
def test_use_fixtures(my_method):
    print('success')

   还可以通过usefixtures装饰器调用fixture

import pytest


@pytest.fixture()
def my_method():
    print('This is pytest.fixture')


# 函数直接调用fixture
@pytest.mark.usefixtures('my_method')
def test_use_fixtures():
    print('success')


class TestClass:
    # 类方法直接调用fixture
    @pytest.mark.usefixtures('my_method')
    def test_class_use_fixtures(self):
        print('success')


# 类直接调用fixture
class TestClass1:
    def test_method_use(self):
        pass

    def test_method_usage(self):
        pass

2.params:(pytest.fixture带参数调用)

params以可选的参数列表形式存在,在测试函数中使用时,可通过request.param接收设置的返回值(即params列表里的值)。params有多少个元素,在测试时,引用此fixture的函数就会被调用几次

fixture带参数调用

@pytest.fixture(params=['hello', 'pytest'])
def my_method(request):
    return request.param


def test_use_fixtures_01(my_method):
    print('\n this is the first test')


@pytest.mark.usefixtures('my_method')
def test_use_fixtures_02(my_method):
    print('\n this is the second test')

3.autouse(pytest.fixture参数隐式调用)

是否自动执行设置好的fixtures,当autouse为True时,测试函数即使不调用fixture装饰器,定义的fixture函数也会被执行

4.ids

指定每个字符串id,当有多个param时,针对每一个param,可以指定id,这个id将变为测试用例名字的一部分,如果没有提供id,则自动生成一个id

5.name

name是fixture的名称,默认为你装饰的fixture函数的名称。可以通过name参数更改这个fixture的名称,更改后,如果这个fixture被调用,则使用更改过的名称即可。

fixture通过autouse参数隐式调用(我这里的文件名为test_demo.py)

import pytest


@pytest.fixture(params=['hello', 'pytest'], autouse=True, ids=['test1', 'test2'], name='test')
def my_method(request):
    return request.param


def test_use_fixtures_01(my_method):
    print('\n this is the first test')


@pytest.mark.usefixtures('my_method')
def test_use_fixtures_02(my_method):
    print('\n this is the second test')


# 通过在控制台运行 pytest - v tests/test_demo.py

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值