pytest(11): 全局变量使用之fixtures与cache

需求场景:

 

测试用例间,测试文件间需要共享一些变量,前面用例生成数据供后面用例使用:例如登录后的token;或自定义测试框架中需要用到的一些全局变量

解决:

1.利用fixture特性解决

利用pytest的fixture来解决,例如定义一个session级别的fixture,返回一些数据,在多个用例文件中引用fixture即可。注:对于可变数据类型,在用例中改变其值是即可全局生效

定义:

@pytest.fixture(scope='session')
def run_variables(cmdopt):
    """
    初始化脚本运行全局参数
    """
    cmdopts = cmdopt
    plugin = cmdopts['cmdplugin']
    if str(plugin) == str(None):
        client_module = None
        handler_module = None
        plugin_config = None
    else:
        client_file = "compare.plugin.{}.src.client".format(plugin)
        client_module = importlib.import_module(client_file)
        handler_file = "compare.plugin.{}.src.handler".format(plugin)
        handler_module = importlib.import_module(handler_file)
        ypath = os.path.join(COMPARE_PATH, 'plugin/{}/conf/conf.yml'.format(plugin))
        plugin_config = YamlHelper(ypath).data
    all_variables = {}
    all_variables['cmdopts'] = cmdopts #命令参数字典
    all_variables['client_module'] = client_module #客户端模块
    all_variables['handler_module'] = handler_module #客户端操作模块
    all_variables['plugin_config'] = plugin_config #插件配置
    all_variables['current_result'] = {}  #当前执行用例行结果
    all_variables['run_statistics'] = {'pass': 0, 'fail': 0, 'norun': 0}  #当前执行用例数据统计
    return all_variables

使用 

@pytest.mark.parametrize("test_case_id, cust_id,business_type,exec_flag,desc,data", datas)
def test_access_01(client, run_variables, access_variables, access_output_cr,  access_output_func,
                test_case_id, cust_id, business_type, exec_flag, desc, data):

    handler_module = run_variables['handler_module']
    print('=====>data.data_dict:',data.data_dict)
    row_result = init_result(access_output_cr.columns, data.data_dict)
    run_variables['current_result'] = row_result
    if exec_flag:
        row_result['result'] = '不执行'
        row_result['rerun'] = exec_flag
        return

2.cash方法解决

cache 是一个可以在测试会话之间保持状态的缓存对象。

@pytest.fixture
def cache(request):
    """
    Return a cache object that can persist state between testing sessions.
    cache.get(key, default)
    cache.set(key, value)
    Keys must be a ``/`` separated value, where the first part is usually the
    name of your plugin or application to avoid clashes with other cache users.
    Values can be any object handled by the json stdlib module.
    """
    return request.config.cache

cache是Cache类的一个实例对象

  • mkdir 创建一个文件夹

  • set(key: str, value: object)  设置一个cache值

  • get(key: str, default)   得到key对应的值

例1:当前置操作生成一个id值,在用例中获取这个id

import pytest

@pytest.fixture()
def create_token(cache):
    """取值生成一个id"""
    token = 'Dfgczsxghbvljzxghlvzhdvhlxckvuhbxchb'
    cache.set("token ", token )
    yield token 

def test_1(cache, create_token):
    # 方式1:cache获取
    token= cache.get("id", None)
    print("获取到的id: {}".format(token))


    # 方式2:直接通过create_token获取返回值
    print("create_id fixture return: {}".format(create_token))

例2:执行用例后生成一个user_data,后置操作需要清理数据

import pytest

@pytest.fixture()
def delete_user_data(cache):
    """后置处理"""
    yield
    # 先获取用例执行后得到的user_data
    user_data= cache.set("user_data", None)
    print("后置处理得到值: {}".format(user_data))

def test_2(cache, delete_user_data):
    # 执行用例后生成user_data
    user_data= "token5d4vz5vz"
    cache.set("user_data", user_data)

.pytest_cache 缓存文件

在pycharm中右键执行,不会生成.pytest_cache 缓存文件。
使用 pytest 命令行执行,会在项目目录生成.pytest_cache 缓存文件

@pytest.fixture
def cache(request):
    return request.config.cache
@pytest.fixture(scope='function')
@pytest.mark.parametrize('data1', datas)
def eee(data1,cache):
    cache.set('user_data', 'izusdygfuoysagdyufgau')

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值