python写后台接口请求出错_Python接口自动化实战 ( 第一阶段) - 封装接口请求类和异常处理...

1.封装http接口请求

已经实现了一个简单的接口请求,接下来就要考虑封装这个请求,在后面的用例中,只需要传递参数(URL ,Params,cookie,heade,method 等)每次去调用这个请求类,

然后根据接口的请求类型来调用相应的处理,如果是get方式就调用get方法,如果是post方式就调用post方法,经过这样的设计后,测试方法中的代码结构会更加清晰有层次,也更容易维护。

代码实现:

# 导入requests包

import requests

class HttpRequest:

def http_request(self, url, params, http_method):

res = ''

if http_method.upper()=='POST':

try:

res=requests.post(url,params)

print("正在进行post请求")

except Exception as e:

print("post请求出现了异常:{0}".format(e))

elif http_method.upper()=='GET':

try:

res=requests.post(url,params)

print("正在进行get请求")

except Exception as e:

print("get请求出现了异常:{0}".format(e))

return res

if __name__ == '__main__':

url = 'http://27.154.55.14:8180/api/fcb2bcrm/webRegister'

datas = {'LoginAccount': 'testapi01@emai.com', 'Password': '123456', 'Type': 'Pro'}

res=HttpRequest().http_request(url, datas, 'post')

print(res.json())

执行结果:

4.TestCase调用封装好的http请求,并添加异常处理。

在运行用例的时候,发现无论断言成功与否,测试报告都是全部通过,后面发现是在处理异常的时候,没有将异常抛出。

以下是test_register.py 修改后的代码:

# 导入

import unittest

import requests

from Common.http_request import HttpRequest

class TestRegister (unittest.TestCase): # 类必须以Test开头,继承TestCase

url = 'http://27.154.55.14:8180/api/fcb2bcrm/webRegister'

def setUp(self):

print("======开始执行测试用例======")

def tearDown(self):

print("======测试用例执行完毕======")

# 测试用例 - 正常注册

def test_register_normal(self): # 每一条测试用例以test_开头

# 发送请求

params = {'LoginAccount': 'apitest09@emai.com', 'Password': '123456', 'Type': 'Pro'}

# res = requests.post(self.url,params)

res = HttpRequest().http_request(self.url,params,'post')

# 断言:根据实际测试场景,可以查询数据库是否有新注册的用户、对比接口的返回信息、对比状态码等等

try:

self.assertEqual(200, res.status_code)

print('成功测试用户:{}'.format(params['LoginAccount']))

except AssertionError as e:

print('Failed')

raise e # 注意一定要抛出异常

# 测试用例 - 重复注册

def test_register_existing(self):

# 发送请求

params = {'LoginAccount': 'apitest05@emai.com', 'Password': '123456', 'Type': 'Pro'}

# res = requests.post(self.url,params)

res = HttpRequest().http_request(self.url, params, 'post')

# 断言

try:

self.assertIn("The email has been registered", res.json()['Message'])

print("执行结果:pass:", res.json()['Message'])

except AssertionError as e:

print('执行结果:Failed')

raise e

# 测试用例 - 无效的邮箱格式去注册

def test_register_invalid_email(self):

# 发送请求

params = {'LoginAccount': 'testapi@emai', 'Password': '123456', 'Type': 'Pro'}

# res = requests.post(self.url,params)

res = HttpRequest().http_request(self.url, params, 'post')

# 断言

try:

self.assertIn("valid email", res.json()['Message'])

print("执行结果:pass:", res.json()['Message'])

except AssertionError as e:

print('执行结果:Failed')

raise e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值