我也是第一次知道,正流行的接口测试工具requests库原来这么好用!
Posted 51Testing软件测试网
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我也是第一次知道,正流行的接口测试工具requests库原来这么好用!相关的知识,希望对你有一定的参考价值。
前言
说到python发送HTTP请求进行接口自动化测试,脑子里第一个闪过的可能就是requests库了,当然python有很多模块可以发送HTTP请求,包括原生的模块http.client,urllib2等,但由于原生的模块过于复杂,使用繁琐,那么requests库就诞生了,它也是现阶段比较流行的接口自动化测试工具之一
requests是个第三方库,封装了HTTP请求的所有方法,使用方便简单,只需要根据不同的请求方式调用相对应的方法就可以完成发送网络请求的整个过程,那么今天我们就来说说requests库是如何使用的,那么在开始之前我们大致说一下今天的主要内容:
1. requets如何发送get请求
2. requests如何发送post请求
3. params参数和data参数的区别
4. requests库中Session类的的妙用
5. 针对get请求和post请求,对requests进行简单封装
发送get请求
1 def get(url, params=None, **kwargs):
2 r"""Sends a GET request.
3
4 :param url: URL for the new :class:`Request` object.
5 :param params: (optional) Dictionary, list of tuples or bytes to send
6 in the body of the :class:`Request`.
7 :param \*\*kwargs: Optional arguments that ``request`` takes.
8 :return: :class:`Response <Response>` object
9 :rtype: requests.Response
10 """
11
12 kwargs.setdefault('allow_redirects', True)
13 return request('get', url, params=params, **kwargs)
"""
------------------------------------
@Time : 2019/7/11 20:34
@Auth : linux超
@File : requests_blog.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import requests # 导入requests模块
response = requests.get('https://www.cnblogs.com/') # 发送get请求
print(response.text) # 获取响应数据
响应数据
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="referrer" content="always" />
<title>博客园 - 代码改变世界</title>
<meta name="keywords" content="开发者,博客园,开发者,程序猿,程序媛,极客,编程,代码,开源,IT网站,Developer,Programmer,Coder,Geek,技术社区" />
<meta name="description" content="博客园是一个面向开发者的知识分享社区。自创建以来,博客园一直致力并专注于为开发者打造一个纯净的技术交流社区,推动并帮助开发者通过互联网分享知识,从而让更多开发者从中受益。博客园的使命是帮助开发者用代码改变世界。" />
<link rel="shortcut icon" href="//common.cnblogs.com/favicon.ico" type="image/x-icon" />
<link rel="Stylesheet" type="text/css" href="/bundles/aggsite.css?v=IlEZk4Ic2eCzcO6r0s4bGm62FAo8VZI-US_0EqUe2Bk1" />
<link id="RSSLink" title="RSS" type="application/rss+xml" rel="alternate" href="http://feed.cnblogs.com/blog/sitehome/rss" />
<script type="text/javascript"></script>
<script type="text/javascript"></script>
<script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script>
<script>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
</script>
response.headers # 获取响应头信息
response.cookies # 获取返回的cookie
response.status_code # 获取状态码
发送带params参数的get请求
"""
------------------------------------
@Time : 2019/7/11 20:34
@Auth : linux超
@File : requests_blog.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import requests
login_data = {"mobilephone": "13691579841", "pwd": 123456} # 接口所需参数
response = requests.get(url=login_url, params=login_data) # 发送get请求
print(response.text) # 获取响应数据
print(response.url)
{"status":1,"code":"10001","data":null,"msg":"登录成功"}
http://***:8080/futureloan/mvc/api/member/login?mobilephone=13691579841&pwd=123456
Process finished with exit code 0
发送post请求
1 def post(url, data=None, json=None, **kwargs):
2 r"""Sends a POST request.
3
4 :param url: URL for the new :class:`Request` object.
5 :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
6 :param json: (optional) json data to send in the body of the :class:`Request`.
7 :param \*\*kwargs: Optional arguments that ``request`` takes.
8 :return: :class:`Response <Response>` object
9 :rtype: requests.Response
10 """
11
12 return request('post', url, data=data, json=json, **kwargs)
"""
------------------------------------
@Time : 2019/7/12 10:22
@Auth : linux超
@File : requests_blog.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import requests
login_data = {"mobilephone": "13691579841", "pwd": 123456} # 接口所需参数
response = requests.post(url=login_url, data=login_data) # 发送post请求
print(response.text) # 获取响应数据
print(response.url)
print(response.status_code)
响应数据
{"status":1,"code":"10001","data":null,"msg":"登录成功"}
http://***:8080/futureloan/mvc/api/member/login
200
Process finished with exit code 0
使用json参数实例
"""
------------------------------------
@Time : 2019/7/12 10:22
@Auth : linux超
@File : requests_blog.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import requests
login_data = {"mobilephone": "13691579841", "pwd": 123456} # 接口所需参数
response = requests.post(url=login_url, json=login_data) # 发送post请求
print(response.text) # 获取响应数据
print(response.url)
print(response.status_code)
响应数据
{"status":0,"code":"20103","data":null,"msg":"手机号不能为空"}
http://***/futureloan/mvc/api/member/login
200
Process finished with exit code 0
Session类的妙用
"""
------------------------------------
@Time : 2019/7/12 10:22
@Auth : linux超
@File : requests_blog.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import requests
login_data = {"mobilephone": "13691579841", "pwd": 123456} # 接口所需参数
response_login = requests.post(url=login_url, data=login_data) # 发送post请求 登录
print(response_login.text)
recharge_data = {"mobilephone": "13691579841", "amount": 10000.00} # 接口所需参数
response_recharge = requests.post(url=recharge_url, data=recharge_data) # 发送请求,开始充值
print(response_recharge.text)
{"status":1,"code":"10001","data":null,"msg":"登录成功"}
{"status":0,"code":null,"data":null,"msg":"抱歉,请先登录。"}
Process finished with exit code 0
"""
------------------------------------
@Time : 2019/7/12 10:22
@Auth : linux超
@File : requests_blog.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import requests
request = requests.Session() # 初始化Session
login_data = {"mobilephone": "13691579841", "pwd": 123456} # 接口所需参数
response_login = request.request(method='post', url=login_url, data=login_data) # 发送post请求 登录
print(response_login.text)
recharge_data = {"mobilephone": "13691579841", "amount": 10000.00} # 接口所需参数
response_recharge = request.request(method='post', url=recharge_url, data=recharge_data) # 发送请求,开始充值
print(response_recharge.text)
{"status":1,"code":"10001","data":null,"msg":"登录成功"}
{"status":1,"code":"10001","data":
{"id":5451,"regname":"test","pwd":"E10ADC3949BA59ABBE56E057F20F883E","mobilephone":"13691579841","leaveamount":"15000.00","type":"1","regtime":"2019-05-26 19:08:44.0"},
"msg":"充值成功"}
Process finished with exit code 0
reqests简单封装
1 """
2 ------------------------------------
3 @Time : 2019/7/12 16:14
4 @Auth : linux超
5 @File : sendrequests.py
6 @IDE : PyCharm
7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
10 ------------------------------------
11 """
12 import json
13 import requests
14
15
16 class HttpRequests(object):
17 """
18 eg: request = HttpRequests()
19 response = request(method, url, data)
20 or
21 response = request.send_request(method, url, data)
22 print(response.text)
23 """
24 def __init__(self):
25 self.session = requests.Session()
26
27 def send_request(self, method, url, params_type='form', data=None, **kwargs):
28 method = method.upper()
29 params_type = params_type.upper()
30 if isinstance(data, str):
31 try:
32 data = json.loads(data)
33 except Exception:
34 data = eval(data)
35 if 'GET' == method:
36 response = self.session.request(method=method, url=url, params=data, **kwargs)
37 elif 'POST' == method:
38 if params_type == 'FORM': # 发送表单数据,使用data参数传递
39 response = self.session.request(method=method, url=url, data=data, **kwargs)
40 elif params_type == 'JSON': # 如果接口支持application/json类型,则使用json参数传递
41 response = self.session.request(method=method, url=url, json=data, **kwargs)
42 else: # 如果接口需要传递其他类型的数据比如 上传文件,调用下面的请求方法
43 response = self.session.request(method=method, url=url, **kwargs)
44 # 如果请求方式非 get 和post 会报错,当然你也可以继续添加其他的请求方法
45 else:
46 raise ValueError('request method "{}" error ! please check'.format(method))
47 return response
48
49 def __call__(self, method, url, params_type='form', data=None, **kwargs):
50 return self.send_request(method, url,
51 params_type=params_type,
52 data=data,
53 **kwargs)
54
55 def close_session(self):
56 self.session.close()
57 try:
58 del self.session.cookies['JSESSIONID']
59 except:
60 pass
61
62
63 request = HttpRequests()
64
65
66 if __name__ == '__main__':
67 pass
封装测试
"""
------------------------------------
@Time : 2019/7/12 16:16
@Auth : linux超
@File : test_requests.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
from sendrequests import request
import unittest
class TestRequests(unittest.TestCase):
login_url = r'http://***:8080/futureloan/mvc/api/member/login'
# 登录接口测试数据
login_test_value = '{"mobilephone": "13691579841", "pwd": 123456}'
recharge_url = r'http://***:8080/futureloan/mvc/api/member/recharge'
# 充值接口测试数据
recharge_test_value = {"mobilephone": "13691579841", "amount": 10000.00}
def test_login_api(self):
"""登录接口测试用例"""
response = request('get', url=self.login_url, data=self.login_test_value)
self.assertTrue(response.json()["code"] == "10001")
print("登录接口测试通过")
def test_recharge_api(self):
"""充值接口测试用例"""
response = request('get', url=self.login_url, data=self.login_test_value)
try:
# 充值接口需要先登录,才能充值
self.assertTrue(response.json()["code"] == '10001')
except AssertionError as e:
print('登录失败!')
raise e
else:
response = request('post', url=self.recharge_url, data=self.recharge_test_value)
self.assertTrue(response.json()["code"] == "10001")
print("充值接口测试通过")
if __name__ == '__main__':
unittest.main()
总结
get(url, params=None, **kwargs)
post(url, data=None, json=None, **kwargs)
点击阅读☞
点击阅读☞
点击阅读☞
点击阅读☞
点击阅读☞
以上是关于我也是第一次知道,正流行的接口测试工具requests库原来这么好用!的主要内容,如果未能解决你的问题,请参考以下文章
python_reques接口测试框架,Excel作为案例数据源