# coding=utf-8
import json
import requests

class TestApi(object):
    """
    /*
        @param: @session ,@cookies
        the request can be divided into session request and cookie request according to user's own choice
        however,url and header is must ,other parameters are given by user to make it is None or not
    */
    """
    def get(self,url,param,header,cookie=None,session=None,**kwargs):
        if session:
                return session.request("GET",url,param,headers=header,**kwargs)
        elif cookie:
                return requests.get(url,params=param,headers=header,cookies=cookie,**kwargs)
    """
    /*
    @param: @session ,@cookies
        传入的是dict类型 python object 对象
        header is form data: application/x-www-urlencoded
            transfer data to data directly ,finally requests's submit will be like 'aa=dd&bb=ff' formation
        header is json :application/json
            due to the data can be 'str','dict'and tuple and so on  ,so when we choose data and
            data is given by dict,we must transfer it to json str,but when is json type str ,we must must
            transfer python object dict to json str with json.dumps(),
            finally the request submit data format is str like:
            'aa=dd&bb=ff',but when choose json the submit will become like {'a': 'cc' ,'b': 'dd'} ,
            data and json cant not be used in the requests at the same time
    */
    """
    def post_data(self,url,type,data,header,cookie=None,session=None,**kwargs):
            if cookie:
                if type is "data":
                    return requests.post(url,data=data,headers=header,cookies=cookie,**kwargs)
                elif type is "json":
                    return requests.post(url,data=json.dumps(data),headers=header,cookies=cookie,**kwargs)
            elif session:
                if type is "data":
                    return session.request("POST",url,data=data,headers=header,cookies=cookie,**kwargs)
                elif type is "json":
                    return session.request("POST",url,data=json.dumps(data),headers=header,cookies=cookie,**kwargs)
    """
    /*
    @:param:@json object
    json的value为传入的json对象
    请求header默认:ContentType: application/json
    */

    """
    def post_json(self,url,header,json,cookie=None,session=None,**kwargs):
        if cookie:
            return requests.post(url,headers=header,json=json,cookies=cookie,**kwargs)
        elif session:
            return session.request("POST",url,headers=header,json=json,**kwargs)

    """
    /*
    @:param: @url,@data,@**kwargs
    Tip: header you need to according to your api to be given in **kwargs position
    */
    """
    def put(self,url,data,cookie=None,session=None,**kwargs):
        if cookie:
            return requests.put(url,data,cookies=cookie,**kwargs)
        elif session:
            return session.request("PUT",url,data,**kwargs)
    """
    /*
    @:param: @url,@data,@**kwargs
    Tip: header you need to according to your api to given in **kwargs position
    */
    """
    def delete(self,url,data,cookie=None,session=None,**kwargs):
        if cookie:
            return requests.delete(url,data,cookies=cookie,**kwargs)
        elif session:
            return session.request("DELETE",url,data,**kwargs)

# coding=utf-8
from ruamel import yaml
from API.apitest import *
"""
    /*@param: python version 3.7
    第一步制造配置文件yaml或者json都可以保存请求报文接口参数的:
    写入方法很简单见:Jsread.py的Yml,Js类的write()方法
    */
"""
class Yml(object):
    def __init__(self, yml_path):
        self.yml_path = yml_path

    def read(self):
        with open(self.yml_path, 'r', encoding='utf-8')as f:
            data = yaml.load(f,Loader=yaml.Loader)
        return data

class EnvParameter(object):
    def __init__(self, con_path):
        defaults = {"url": None,
                    "header": None,
                    "data": None,
                    "method": None,
                    "param": None,
                    "type": None,
                    "json": None}
        self.cookies = None
        self.session = None
        self.con_path = con_path
        dict = Yml(self.con_path).read()
        defaults.update(dict)
        self.url = defaults["url"]
        self.header = defaults["header"]
        self.method = defaults["method"]
        self.data = defaults["data"]
        self.param = defaults["param"]
        self.json = defaults["json"]
        self.type = defaults["type"]

class TestSend(EnvParameter):
    def __init__(self,config_path,cookie1=None,session1=None):
        # EnvParameter.__init__(self,conpath=None ,url=None,method=None,header=None,type=None,data=None,param=None,json=None,cookies=None,session=None)
        EnvParameter.__init__(self,config_path)
        self.session=session1
        self.cookie1=cookie1
        # print(self.param,self.type) #测试下类继承效果
    def send(self):
        if self.method.upper()=="GET":
            rep=TestApi().get(self.url,self.param,self.header,cookie=self.cookie1,session=self.session)
            return rep
        elif self.method.upper()=="POST":
            rep=TestApi().post_data(self.url,self.type,self.data,self.header,cookie=self.cookie1,session=self.session1)
            return rep
        elif self.method.upper()=="PUT":
            rep=TestApi().put(self.url,self.data,cookie=self.cookie1,session=self.session1)
            return rep
        elif self.method.upper()=="DELETE":
            rep=TestApi().delete(self.url,self.data,cookie=self.cookie1,session=self.session1)
            return rep
# if __name__ == "__main__":
#     TestSend('./conf.yaml')

import unittest
import  requests
from API.testyaml import *
class Interface(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        global session
        s = requests.session()
        requests.get(url="http://www.baidu.com")
        session =s
        print("---------------开始测试所有接口--------------")
    @classmethod
    def tearDownClass(cls):
        """清除cookie"""
        session.cookies.clear()  #也可以这样写 session.cookies=None
        print("---------------加载所有接口结束销毁cookie--------------")

    def test_001(self):
        response=TestSend('./conf.yaml',session1=session).send()
        print(response.status_code)

if __name__ =="__main__":
    unittest.main()
详情也可以见我的csdn地址
---------------------
作者:流浪的python
来源:CSDN
原文:https://blog.csdn.net/chen498858336/article/details/86619178
版权声明:本文为博主原创文章,转载请附上博文链接!

python接口自动化读取json,yaml配置文件+封装requests+unittest+HTMLRunner实现全自动化的更多相关文章

  1. MOOC(7)- case依赖、读取json配置文件进行多个接口请求-读取json封装成类(13)

    把读取json数据的函数封装成类 # -*- coding: utf-8 -*- # @Time : 2020/2/12 16:44 # @File : do_json_13.py # @Author ...

  2. python接口测试之读取配置文件

    1.python使用自带的configparser模块用来读取配置文件,配置文件可以为.conf或.ini结尾 在使用前需要先安装该模块,使用pip安装即可 2.新建一个名为a.conf的配置文件 a ...

  3. python写的读取json配置文件

    配置文件默认为conf.json 使用函数set完成追回配置项. 使用load或取配置项. 代码如下: #!/usr/bin/env python3 # -*- coding: utf-8 -*- ' ...

  4. Python Configparser模块读取、写入配置文件

    写代码中需要用到读取配置,最近在写python,记录一下. 如下,假设有这样的配置. [db] db_host=127.0.0.1 db_port=3306 db_user=root db_pass= ...

  5. QuantLib 金融计算——自己动手封装 Python 接口(1)

    目录 QuantLib 金融计算--自己动手封装 Python 接口(1) 概述 QuantLib 如何封装 Python 接口? 自己封装 Python 接口 封装 Array 和 Matrix 类 ...

  6. QuantLib 金融计算——自己动手封装 Python 接口(2)

    目录 QuantLib 金融计算--自己动手封装 Python 接口(2) 概述 如何封装一项复杂功能? 寻找最小功能集合的策略 实践 估计期限结构参数 修改官方接口文件 下一步的计划 QuantLi ...

  7. 当向后台插入或读取JSON数据遇见回车时

    今天在项目中发现.当插入或读取JSON数据时遇见回车符.返回JSON数据格式时会报错(firebug里体现为乱码),百度了一下发现JSON不支持字符串里存在回车! 解决的方法: 在向接口插入带json ...

  8. python - 接口自动化测试 - ReadConfig - 读取配置文件封装

    # -*- coding:utf-8 -*- ''' @project: ApiAutoTest @author: Jimmy @file: read_config.py @ide: PyCharm ...

  9. 接口自动化 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)

    基于python实现的http+json协议接口自动化测试框架(实用改进版)   by:授客 QQ:1033553122 欢迎加入软件性能测试交流QQ群:7156436     目录 1.      ...

随机推荐

  1. python模块之numpy与pandas

    一.numpy numpy是python数据分析和机器学习的基础模块之一.它有两个作用:1.区别于list列表,提供了数组操作.数组运算.以及统计分布和简单的数学模型:2.计算速度快[甚至要由于pyt ...

  2. 设计模式 UML & java code

    A: 创造性模式 1. 工厂方法模式(FactoryMethod) 1.1 类图 1.2 代码1 public interface Pet { public String petSound(); } ...

  3. float失效的情况

    前言:在最近的笔试中,两次碰到类似的问题,什么情况下float会失效?我目前知道的有2种: 1)display:none: 2)position:absolute.fixed. (1)display: ...

  4. 【转载】python实例手册

    今天写爬虫的时候遇到了问题,在网上不停地查找资料,居然碰到两篇好文章: 1.python实例手册   作者:没头脑的土豆 另一篇在这:shell实例手册 python实例手册 #encoding:ut ...

  5. jQuery 滚动条滚动

    1.将div的滚动条滚动到最底端 <div class="container"></div> var $container=$(".contain ...

  6. Python爬虫教程-09-error 模块

    Python爬虫教程-09-error模块 今天的主角是error,爬取的时候,很容易出现错,所以我们要在代码里做一些,常见错误的处,关于urllib.error URLError URLError ...

  7. OFDM正交频分复用---基础入门图示

    @(162 - 信号处理) 整理转载自:给小白图示讲解OFDM 下面以图示为主讲解OFDM,以"易懂"为第一要义. 注:下面的讨论如果不做说明,均假设为理想信道. *** 一张原理 ...

  8. 同步(Synchronous)和异步(Asynchronous)的概念

    web项目中的同步与异步 在我们平时的web项目开发中会经常听到ajax请求这样一个称呼,在web项目中可以通过js或者jquery发送同步请求又或者异步请求,同步请求呢往往代表着你必须等待这次请求结 ...

  9. C#实现字符串相似度算法

    字符串的相似性比较应用场合很多,像拼写纠错.文本去重.上下文相似性等. 评价字符串相似度最常见的办法就是: 把一个字符串通过插入.删除或替换这样的编辑操作,变成另外一个字符串,所需要的最少编辑次数,这 ...

  10. Python问题1:IndentationError:expected an indented block

    Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的python程序员,也可能陷入陷阱当中.最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分 ...