调试遇到的问题与解决方法
-
httplib模块的导入
也是百度了才知道python3.x不用httplib这个名字改用http.client这个名字了。 -
接口用例表的设计
这一块也是百度查找了Navicat 如何用sql脚本创建表的相关知识后,创建完成了接口用例表,并添加了数据进去。 -
报错:TypeError:string indices must be intergers(字符串索引必须是整数)
看了 @倔强的潇洒小姐 的发送http问题汇总的文章,也有类似的报错。 看了下她的解决方法,发现我在mysql.py文件里已经设置过了
cur = conn.cursor(cursorclass=pymysql.cursors.DictCursor)
,所以只能从其他地方下手查找错误。接着看到了红字下面的数据库的报错才发现代码里把params_interface写成了param_interface了,修改完成后,就不报错了。
课程内容备忘
- config.py的作用:
这个py文件是配置文件,用来存储固定的数据 - __http_code前面两个下划线的作用:
前面添加两个下划线是说明该方法是静态的,被隐藏的,不能被除它所在的py文件外的任何方法调用。而它自身所在py文件下的方法调用它的话,得在前面加个self,如:self.__http_code
完整源码:
# 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)
感谢
超感谢大婶和川叔提供的学习接口自动化的测试课程,确实颠覆了我的很多想法,也在以结果为导向反推的课程教学模式下,能够更多地去自查自学自我总结和分享反馈。
网友评论