pytest 8+.yaml文件详解---实现接口自动化

yaml文件详解---实现接口自动化

  一、作用

  1.用于全局的配置文件  ini   yaml

  2.用于写测试用例(接口测试用例)

  yaml简介:

  yaml是一种数据格式支持注释,换行,多行字符串,裸字符串(整形,字符串)

  安装:pip install PyYAML

 

  二、语法规则:

  1.区分大小写

  2.通过缩进表示层级,不能用tab建缩进,只能用空格(和python一样)

  3.缩进没有数量,只要前面是对其的就行

  4.注释是#

 

  三、数据组成:检查的时候用这个网站:https://www.bejson.com/validators/yaml_editor/     可以直接换成json对象看看对不对

  1.map对象,键值对  键:(空格)值   

  demo:第一张是多行的 写法,第二张是一行的写法,第三张是检查的格式对不对

       

  2.数组(list):用一组横线表示 横线后面有空格

        

  四、读取yaml文件

  yaml文件的反序列化:

#!/usr/bin/python 
# -*- coding: utf-8 -*-
# author:xiaomin pei
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格式转换成字典的格式
        :return:
        """
        with open(self.yaml_file, encoding='utf-8') as f:
            value = yaml.load(f, Loader=yaml.FullLoader)
            print(value, type(value))
       return value if __name__ == '__main__': YamlUtil('test_api.yaml').read_yaml()

  

  五、接口自动化实战:

  首先看一个接口:(比较粗糙)

  这是yaml文件里面的内容。测试用例2条

#用例1
-
  name: 获得token鉴权码的接口
  request:
    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
    valicate:
      - eq: {expires_in: 7200}
#用例2,反例
-
  name: 获得token鉴权码的接口
  request:
    url: https://api.weixin.qq.com/cgi-bin/token
    method: get
    headers:
      Content-Type: application/json
    params:
      appid: wx6b11b3efd1cdc290
      secret: 106a9c6157c4db5f6029918738f9529d
    valicate:
      - eq: {errcode: 40002}

  下面是python文件

#!/usr/bin/python 
# -*- coding: utf-8 -*-
# author:xiaomin pei
import pytest, requests
from testcase.yaml_util import YamlUtil
class TestApi:

    @pytest.mark.parametrize('args', YamlUtil('test_api.yaml').read_yaml())
    def test_01_shuguo(self, args):
        # url = "https://api.weixin.qq.com/cgi-bin/token"
        # params = {
        #     "grant_type": "client_credential",
        #     "appid": "wx6b11b3efd1cdc290",
        #     "secret": "106a9c6157c4db5f6029918738f9529d"
        # }
        #
        url = args['request']['url']
        params = args['request']['params']
        res = requests.get(url=url, params=params)
        print("蜀国:", res.json(), type(res.json()))
        # 断言
        if res.json().get('expires_in'):
            assert args['request']['valicate'][0]['eq']['expires_in'] == res.json()['expires_in']
        else:
            assert args['request']['valicate'][0]['eq']['errcode'] == res.json()['errcode']


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

  

扩展:

1.requests二次封装

2.多重断言

3.多接口的场景串联

4.日志监控(日志文件的生成,控制台调试日志,邮件日志)

posted @ 2021-08-27 17:38  裴敏儿  阅读(748)  评论(0编辑  收藏  举报