首页 > 其他分享 >关键字 开发-04 yaml文件定义变量与引用变量

关键字 开发-04 yaml文件定义变量与引用变量

时间:2023-11-25 14:55:06浏览次数:53  
标签:变量 04 data self yaml dict print config

前言:上篇使用jinja2模板渲染数据是在读取yaml文件的时候,进行渲染。这种肯定不是关键字框架的渲染的方式。正常我们想要的而是在yaml文件中写入我们想要渲染的数据,然后读取之后渲染到测试yaml用例中。

1. 在yaml文件中引入变量

由于变量在yaml中先声明,后引用,所以不能直接渲染整个yaml。

解决的方法是:先读取yaml,转dict , 再获取config的数据并对其进行收集,最后再进行jinja2对测试用例的数据的渲染。

import yaml
from jinja2 import Template
from pathlib import Path

def read_yaml(file_path: Path):
    """
    读取 yaml 数据,转 python 类型
    :param file_path:
    :return: dict
    """
    with open(file_path, 'r', encoding='utf-8') as fp:
        read_yml_data = yaml.safe_load(fp) # 读到的是dict

    return {
        'config': read_yml_data.get('config') if read_yml_data.get('config') else {},
        'data': [[key, value] for key, value in read_yml_data.items() if key != 'config']
    }

if __name__ == '__main__':
    file_path = Path(__file__).parent.parent.joinpath('data', 'login.yml')
    res = read_yaml(file_path)
    print(res)
    print(res['config'])
    print(res['data'])
    print(dict(res['data']))
    print(type(res))  # -->dict
"""利用反射运行关键字"""
import jinja2
import json
from requests import Response
class RunByKey:
    def __init__(self, session, config: dict = None):
        self.session = session
        self.config = config # 获取yaml config 配置
        self.context = {}  # 变量容器
        self.yaml_variables = {}  # 用例变量

    @staticmethod
    def name(value):
        print(f'用例名称:{value}')

    def request(self, request_data: dict):
        print(f"执行request: {request_data}")
        res = self.session.send_request(**request_data)
        return res

    def run(self, data: dict):
        # 1.先获取到config中的变量variables
        config_variables = self.config.get('variables', {}) if self.config else {}
        print('获取到的config中的变量:', config_variables)
        # 2.更新到变量容器中
        self.context.update(config_variables)
        for key, value in data.items():
            if hasattr(self, key):
                # 执行的request前,需要替换的数据
                print(f'渲染之前的数据:{value}')
                t2 = jinja2.Template(json.dumps(value), # dict-->str
                                     variable_start_string='${',
                                     variable_end_string='}')
                value = json.loads(t2.render(**self.context))  # str-->dict
                print(f'渲染之后的数据:{value}')
                res = getattr(self, key)(value)  # 按关键字执行
                print(f"=========当前的key:{key}")
                if key == "request":
                    print(f"执行结果:{res.text}")
            else:
                print(f"关键字未定义: {key}")

标签:变量,04,data,self,yaml,dict,print,config
From: https://www.cnblogs.com/dack-zt-deng/p/17855522.html

相关文章

  • ubuntu黑屏(解决,但又没完全解决)关于双系统 ubuntu22.04 LST+win11 及 双显卡 AMD-6650X
    今天一开机,ubuntu系统就黑屏左上角光标一直闪,并且报了bluetooth的问题和v2raya的问题。alt+f2-f7都无法切换到命令界面或图形界面。但是反复重启后,有个别几次能进入图形界面。排查了几个原因1、内核的问题。参考:https://www.mail-archive.com/[email protected]......
  • C++11 多线程并发 互斥量、条件变量和信号量
    互斥量Classesmutex(C++11)providesbasicmutualexclusionfacility(class)timed_mutex(C++11)providesmutualexclusionfacilitywhichimplementslockingwithatimeout(class)recursive_mutex(C++11)providesmutualexclusionfacili......
  • AST 变量 enter 和 exit 的区别 退出区别
    1.enter方式进行遍历(不写默认是enter方式)假设我们需要处理的代码如下:vara='a'+'b'+'c'+d+'e'+'f';想要对上面的代码进行字符串的合并操作,遍历BinaryExpression类型,代码如下:constvisitor={"BinaryExpression"(path){c......
  • Ubuntu20.04 美化教程
    之前写的Ubuntu18.04美化方法的文章已经不太适用,所以重新写一份关于Ubuntu20.04的美化方法,当然如下方法也适用于Ubuntu18.04。安装需要的软件安装gnome-tweak-tool:sudoaptinstallgnome-tweak-tool安装相应的插件:sudoapt-getinstallgnome-shell-extensions更......
  • day03-3变量与常量
    【变量与常量】【一】注释语法【1】什么是注释注释就是对代码的解释,注释内容不会被当成代码参与运行【2】为什么要注释增强代码的可读性(更容易理解代码)【3】如何使用注释代码注释分单行和多行注释单行注释用‘#’,注释内容加在'#'后,可以跟在代码的正上方或者......
  • [Deeplearning] 活动选择F604
    那个F604是干啥的我似乎也不知道思路依旧很简单,右端点排序,这个活动结束得越早留给后面的时间就越多代码:#include<bits/stdc++.h>usingnamespacestd;structnode{ intstart,end;}a[1010];intn,back,ans;boolcmp(nodex,nodey){ returnx.end<y.end;}intmain()......
  • Java Learning Day1 关键字、标识符、注释、变量
    其实之前也学习过两个月的JAVA,跟着淘宝上买的王道Java课,每天看了1day,整个过程下来感觉什么都没有掌握,所以现在就打算重新学一次,从最开始的关键字开始,也就开通了博客,希望这次学习可以多多掌握一些吧。  关键字:小写、含有特殊含义的单词 标识符:方法名、类名、参数名、变量名......
  • Ubuntu20.04 Grub 更换主题方法
    安装grub-customizer终端输入:sudoadd-apt-repositoryppa:danielrichter2007/grub-customizersudoapt-getupdatesudoapt-getinstallgrub-customizer下载自己喜欢的主题文件本文以Tela主题为例:主题网站:https://www.gnome-look.org/browse?cat=109&ord=rating选......
  • 关键字 开发-03 渲染yaml文件中的变量
    前言:引用渲染变量的模板有2个,一个是字符串模板,另一个是Jinja2模板1.字符串模板1.1.1通过字符串格式化方法进行渲染需要渲染的变量:name="dack"age=23x='mynameis%s,myageis%d'%(name,age)print(x)y="mynameis{},myageis{}".format(name,age)......
  • Ubuntu20.04 安装后部分问题解决方案
    安装搜狗输入法搜狗官方有教程:https://shurufa.sogou.com/linux/guideUbuntu与Windows时间不一致的问题安装ntpdate:sudoapt-getinstallntpdate校准时间:sudontpdatetime.windows.com将时间更新到硬件上:sudohwclock--localtime--systohc单击任务栏图标使窗......