天天看点

使用requests开发一个接口测试工具

import requests

import traceback

class Inert(object):

__left_limit, __right_limit = '${', '}'

def __init__(self, base_url: str):
    self.base_url = base_url
    self.session = requests.Session()
    self.response = None
    self.json_resp = None
    self.params_pool = {}

def send_post_request(self, route: str, params=None):
    new_params = self.__format_statement(params)
    data = self.__format_params(params=new_params)
    try:
        self.response = self.session.post(self.base_url + route, data=data).text
    except Exception:
        print('[info] connect host error!')
    if self.response:
        try:
            self.json_resp = eval(self.response)
        except Exception:
            print(traceback.print_exc())

def send_get_request(self, route: str, params=None):
    try:
        self.response = self.session.get(url=self.base_url + route, params=params).text
    except Exception:
        print('[info] connect host error')
    if self.response:
        try:
            self.json_resp = eval(self.response)
        except Exception:
            print(traceback.print_exc())

def __format_params(self, params: str):
    """
    :param params: 需要解析的参数
    :return: 返回一个dict对象
    """
    new_dict = {}
    if not params:
        return
    if isinstance(params, dict):
        return params
    try:
        string_list = params.split("&")
        for string in string_list:
            index = string.find('=')
            key = string[:index]
            value = string[index + 1:]
            new_dict[key] = value
        return new_dict
    except Exception:
        print('[info] 参数有误!')

def save_param(self, key_name):
    """
    将参数添加到参数池中
    :param key_name:新的键名
    :return:
    """
    try:
        self.params_pool[key_name] = self.json_resp[key_name]
    except Exception:
        print("[info]参数不存在")

def add_headers(self, new_key, statement: str):
    """
    将参数添加到请求头中
    :param new_key:添加至请求头中的键名
    :param statement:
    :return:
    """
    value = self.__format_statement(statement=statement)
    try:
        self.session.headers[new_key] = value
    except Exception:
        print('[info]参数不存在!')

def __format_statement(self, statement: str):
    """
    :param statement: 对在参数池中的参数尝试进行格式化
    :return: 若statement存在或格式化失败则返回原语句,否则否会格式化后的语句
    """
    if isinstance(statement, dict):
        return statement
    if statement:
        for key in self.params_pool:
            statement = statement.replace(
                self.__left_limit + key + self.__right_limit,
                self.params_pool[key]
            )
    return statement

def delimiter(self, lift: str, right: str):
    """
    修改边界符
    :param lift: 左边界符
    :param right: 右边界符
    :return:
    """
    self.__left_limit = lift
    self.__right_limit = right
           

继续阅读