栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

接口自动化框架之python pytest fixture (二)

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

接口自动化框架之python pytest fixture (二)

一、fixture简介:

fixture 是在函数前边添加了注解:@pytest.fixture 的函数,是pytest特有的功能,在编写测试函数的时候,可以将此函数名称作为参数传递进去,pytest将会以依赖注入方式将该函数的返回值作为测试函数的传入参数

二、fixture作用:

1.可以把fixture看成一种资源,测试用例执行的时候需要配置这些资源,执行后需要释放掉

2.同时fixture提供参数化功能,根据配置和不同组件选择不同的参数

3.主要目的还是为了提供一种可靠和重复性的手段去运行一些基本的测试内容,比如在测试网站的功能时候,每个用例都需要登入和登出,利用fixture做一次就可,否则每个测试用例都来做这两步也挺冗余的

三、fixture的作用域

fixture 里边有个scope参数可以控制fixture的作用域,session>module>class>function

  • function:每一个方法和函数都会被调用
  • class:每一个类都会被调用,类下边可以有好多方法
  • module:每一个.py文件调用一次,该文件内又有多个function 和class
  • session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是一个module
四、fixture的三种调用方法

1.函数直接里边传入:

@pytest.fixture(scope='session')
def before():
    return ('wdew')

2.使用装饰器@pytest.mark.usefixtures('before'),括号里是fixture的自定义函数名

@pytest.fixture(scope='session')
def before():
    return ('wdew')

@pytest.mark.usefixtures('before')
def test_01(before):
    print('hua')

3.使用autouse=True

@pytest.fixture(autouse=True)
def before():
    return ('wdew')

 附录代码(无参数)

import pytest

# @pytest.fixture(scope='session')
@pytest.fixture(autouse=True)
def before():
    return ('wdew')

@pytest.mark.usefixtures('before')
def test_01(before):
    print('hua')

class TestCase():
    def test_01(self,before):
        print('test01')
    def test_02(self,before):
        print('test02')

if __name__ == '__main__':
    pytest.main(['-s','-v','test_fixture.py'])

五、fixture 参数

fixture有一个params参数,接受一个列表,列表中的每一个数据都可以作为用例的输入,也就是说列表中有多少数据就会形成多少个测试用例

代码如下:

import pytest
import random

res = [1,'tom',3,'tender',4]

@pytest.fixture(params=res)
def before():
    return ('wdew')

def test_liebiao(before):
    print('第{}条数据'.format(random.randint(1,6)))

if __name__ == '__main__':
    pytest.main(['-s','-v','test_fixture.py'])

运行结果:

以上是pytest框架中fixture的介绍和使用,如有问题,随时沟通~下一篇pytest-mark的使用介绍 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913857.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号