颠覆你的Python实践软件测试之路

《颠覆你的Python接口自动化测试》05-Python操作HT

2017-09-02  本文已影响120人  捡个七

调试遇到的问题与解决方法

课程内容备忘

完整源码:

# coding:utf-8
import requests
import http.client
import os
import logging
import json
import config
import mysql


class RequestInterface(object):

    # 判断接口地址HTTP状态是否200
    def __http_code(self, url):  ##  __该方法被隐藏不能被py文件外的其他方法调用
        try:
            if url != '':
                r = requests.get(url)
                code = r.status_code
            else:
                code = '1000'  # 请求参数错误
        except Exception as error:  # 记录日志到log.txt文件
            code = '9999'  # http请求异常
            logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                                level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
            logger = logging.getLogger(__name__)
            logger.exception(error)
        return code

    # POST请求,参数在body中
    def __http_post(self, interface_url, headerdata, param, environ):
        '''参数有:接口地址,头文件,接口入参,执行环境(测试,生产)'''
        try:
            if interface_url != '' and environ == u'test':
                http_client = http.client.HTTPConnection(config.envoron_test['ip'],
                              config.environ_test['port'], timeout=config.environ_test['timeout'])  # 创建HTTP连接
                http_client.request("POST", interface_url, body=param, headers=headerdata)
                response = http_client.getresponse()
                if response.status == 200:
                    return response.read()
                else:
                    return "2004"  # 接口返回状态错误
            elif interface_url != '' and environ == u'product':
                http_client = http.client.HTTPConnection(config.envoron_product['ip'],
                            config.environ_product['port'], timeout=config.environ_product['timeout'])
                http_client.request("POST", interface_url, body=param, headers=headerdata)
                response = http_client.getresponse()
                if response.status == 200:
                    return response.read()
                else:
                    return "2004"  # 接口返回状态错误
            elif interface_url == '':
                return '2002'  # 接口地址参数为空
            elif self.__http_code(interface_url) != 200: ##调用同个类里的方法
                return '2003'  # 接口http访问错误
        except Exception as error:
            logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                                level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
            logger = logging.getLogger(__name__)
            logger.exception(error)
            return '9999'  # http请求异常

    # GET请求,参数在接口地址后面
    def __http_get(self, interface_url, headerdata, param, environ):
        '''参数有:接口地址,头文件,接口入参,执行环境(测试,生产)'''
        try:
            if interface_url != '' and environ == u'test':
                requrl = interface_url + param
                http_client = http.client.HTTPConnection(config.environ_test['ip'],
                             config.environ_test['port'], timeout=config.environ_test['timeout'] )
                http_client.request(method="GET", url=requrl, body=None, headers=headerdata)
                response = http_client.getresponse()
                print(response)
                if response.status == 200:
                    return response.read()
                else:
                    return "3004"  # 接口返回状态错误
            elif interface_url != '' and environ == u'product':
                requrl = interface_url + param
                http_client = http.client.HTTPConnection(config.environ_product['ip'],
                                                         config.environ_product['port'],
                                                         timeout=config.environ_product['timeout'])
                http_client.request(method="GET", url=requrl, body=None, headers=headerdata)
                response = http_client.getresponse()
                print(response)
                if response.status == 200:
                    return response.read()
                else:
                    return "3004"  # 接口返回状态错误
            elif interface_url == '':
                return '3002'  # 接口地址参数为空

            elif self.__http_code(interface_url) != 200:
                return '3003'  # 接口http访问错误
        except Exception as error:
            logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                                level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
            logger = logging.getLogger(__name__)
            logger.exception(error)
            return '9999'  # http请求异常

    # 统一处理http请求
    def http_request(self, interface_url, headerdata, param, type, environ=u'test', default_param=None):
        '''参数有:接口地址,头文件,接口入参,请求方式,执行环境(测试,生产,默认是测试),默认参数'''
        try:
            if type == 'get' or type == 'GET':
                result = self.__http_get(interface_url, headerdata, param, environ)
            elif type == 'post' or type == 'POST':
                result = self.__http_post(interface_url, headerdata, param, environ)
            else:
                result = "1000:请求参数错误"  # 请求参数类型错误
        except Exception as error:  # 记录日志到log.txt文件
            result = "9999"  # 系统异常返回码
            logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                                level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
            logger = logging.getLogger(__name__)
            logger.exception(error)
        return result


if __name__ == "__main__":
    test_interface = RequestInterface()  # 实例化HTTP请求类
    test_db = mysql.OperationDbInterface()  # 实例化mysql处理类
    sen_sql =('select exe_mode,url_interface, header_interface, params_interface from case_weatherreport where id=1')
    interface_params = test_db.select_one(sen_sql)  # 获取数据
    interface_url = interface_params['url_interface']
    headerdata = json.loads(interface_params['header_interface'])
    param = interface_params['params_interface']
    result = test_interface.http_request(interface_url=interface_url,
                                         headerdata=headerdata,
                                         param=param, type=type,
                                         environ=u'test', default_param=None)
    print(result)

感谢

超感谢大婶和川叔提供的学习接口自动化的测试课程,确实颠覆了我的很多想法,也在以结果为导向反推的课程教学模式下,能够更多地去自查自学自我总结和分享反馈。


上一篇下一篇

猜你喜欢

热点阅读