读写清空yaml(python) 接口自动化测试

import os
import yaml

extract_dict = {'name': 'Silenthand Olleander',
                'pswd': '112aa洋',
                }


def get_project_path():
    """获取项目路径"""
    realpath = os.path.abspath(os.path.join(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), '.'))
    return realpath


def read_config_yaml(path):
    """读取全局配置Yaml文件"""
    # path = str(get_project_path()) + '/config/configtest.yaml'
    with open(path, 'r', encoding='utf-8') as f:
        cfg = yaml.load(f.read(), Loader=yaml.FullLoader)return cfg

def write_extract_yaml(path):
    """向提取变量aml文件写入数据"""
    with open(path, 'w', encoding='utf-8') as f:
        yaml.dump(extract_dict, f, default_flow_style=False, encoding='utf-8', allow_unicode=True)


def clear_extract_yaml(path):
    """清空yaml文件所有数据"""
    with open(path, 'w', encoding='utf-8') as f:
        f.truncate()

写文件时,如果原来有数据,那么会覆盖原来的数据

以上是写一组数据读写
读取一组数据:yaml.load()
写一组数据:yaml.dump()

 

如果是多组数据的读写:

读取多组数据:yaml.load_all()
返回结果为一个生成器,需要使用for循环语句获取每组数据
写多组数据:yaml.dump_all()

user1={
   'name'='may'
   'age'=18
}
user2={
  'name'='y'
  'age'=16
}
#
with open(path, 'w', encoding='utf-8')as f1:
    yaml.dump_all([user1, user2], f1, default_flow_style=False, encoding='utf-8', allow_unicode=True)
 
#
with open(path, 'r', encoding='utf-8')as f2:
    result = yaml.load_all(f2.read(), Loader=yaml.FullLoader)
for i in result:
print(i)

 

例子:原接口测试用例

import pytest
import requests


class TestApi:

    def test_01_huahua(self):
        url = 'https//api.weixin.qq.com/cgi-bin/token'
        params = {
            "grant_type": "client_credential",
            "appid": "wx6b11b3efd1cdc290",
            "secret": "106a9c6157c4db5f6029918738f9529d"
        }
        res = requests.get(url, params=params)
        print(res.text)


if __name__ == '__main__':
    pytest.main(['-vs'])

上面的代码改为yaml格式数据驱动

test_api.yaml

-
  name: 获得token鉴权码的接口
  requests:
    url: https//api.weixin.qq.com/cgi-bin/token
    method: get
    headers:
      Content-Type: application/json
    params:
      grant_type: client_credential
      appid: wx6b11b3efd1cdc290
      secret: 106a9c6157c4db5f6029918738f9529d
  validate:
    - eq: {expires_in: 7200}

yaml_util.py

import yaml


class YamlUtil:
    def __init__(self, yaml_file):
        """
        通过init方法把Yaml文件传入到这个类
        :param yaml_file:
        """
        self.yaml_file = yaml_file

    # 读取Yaml文件
    def read_yaml(self):
        """
        读取Yaml,对yaml反序列化,就是把我们的yaml格式转换成dict格式
        :return:
        """
        with open(self.yaml_file, encoding='utf-8')as f:
            value = yaml.load(f, Loader=yaml.FullLoader)
            return value

if __name__ == '__main__': YamlUtil('test_api.yaml').read_yaml()

 

测试用例改为如下

import pytest
import requests
from test_cases.yaml_util import YamlUtil
from config.allpath_parameter import test_case_path


class TestApi:

    @pytest.mark.parametrize('args', YamlUtil(test_case_path+'test_api.yaml').read_yaml())
    def test_01_huahua(self, args):
        print(args)
        url = args['request']['url']
        params = args['request']['params']
        res = requests.get(url, params=params)
        print(res.text)


if __name__ == '__main__':
    pytest.main(['-vs'])

 

posted @ 2023-09-15 11:17  yimu-yimu  阅读(49)  评论(0编辑  收藏  举报