接口自动化测试——Requests库

接口自动化测试

1.概念

接口自动化测试,让程序或者工具代替人工自动的完成对接口进行测试的一种过程。

接口测试:对系统或组件之间的接口进行测试,主要是校验数据的交换、传递和控制管理过程,以及相互逻辑依赖关系。
自动化测试:把以人为驱动的测试行为转化为机器执行的一种过程。

2.方法

  • 接口测试工具,如:Jmeter、postman
  • 编写代码

3.接口测试工具的不足

  • 测试数据不好控制(无法直接读取或者储存json格式数据)
  • 不方便测试加密接口
  • 扩展能力不足
  • 断言能力不足

Requests库

1.介绍

Requests库是python实现的HTTP库

2.安装验证

  • 安装:pip install requests
  • 验证:pip show requests

3.Requests发送请求

  • GET: 请求指定的页面信息,并返回实体主体。提交的数据放置在HTTP请求协议头中。
  • HEAD: 只请求页面的首部。
  • POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。提交的数据则放在实体数据中。
  • PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
  • DELETE: 请求服务器删除指定的页面。

(1)get请求

# 导包
import requests

# 调用get
url = "http://httpbin.org/get"
r = requests.get(url)     # r为响应数据对象

# 获取响应状态码
print("状态码:", r.status_code)

# 获取响应信息,文本格式
print("响应文本内容:", r.text)

返回值

状态码: 200
响应文本内容: {
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.24.0", 
    "X-Amzn-Trace-Id": "Root=1-5f237fd0-ef7535aadcd73bb4236c112f"
  }, 
  "origin": "112.32.48.129", 
  "url": "http://httpbin.org/get"
}

补充:带参数的get请求

import requests
url = "http://httpbin.org/get"
params = {"id":"1001","address":"beijing"}
r = requests.get(url,params=params) 
print("响应文本内容:", r.text)

返回值

响应文本内容: {
  "args": {
    "address": "beijing", 
    "id": "1001"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.24.0", 
    "X-Amzn-Trace-Id": "Root=1-5f2382c9-de2f675ea754a77aab48f218"
  }, 
  "origin": "112.32.48.129", 
  "url": "http://httpbin.org/get?id=1001&address=beijing"
}

(2)post请求

案例:post发送请求完成登录豆瓣网

# 导包
import requests

# 请求headers
headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ 83.0.4103.116 Safari/537.36"
}

# 请求json
data = {
    'name': "XXXXX",  # 账号
    "password": "XXXX",  # 密码
    "remember": "false"
}
# 调用post
r = requests.post(url,json=data,headers=headers)

# 获取响应对象
print(r.json())

# 获取响应状态码
print(r.status_code)

# 获取响应信息
print(r.text)

补充:

  1. 参数json和data的区别:
  • 如果参数为JSON数据,可以直接传入json参数,它将自动编码并将Content-Type的置为application/json
payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post("https://httpbin.org/post", json=payload)
print(r.text)
  • 如果data传递的参数为字符串,例如【json.dumps(payload)】,则request对参数进行url编码,Content-Type的值为None,所以data传字符串时,一定要在header中指定Content-Type
payload = {'key1': 'value1', 'key2': 'value2'}
headers={"Content-Type": "application/json"}
r = requests.post("https://httpbin.org/post", headers=headers,data=json.dumps(payload))
print(r.text)
  • 如果data传递的是字典、元组组成的列表或列表作为值的字典,则request对参数进行url编码,Content-Type的值为application/x-www-form-urlencoded
# 字典
payload1 = {'key1': 'value1', 'key2': 'value2'}  
r = requests.post("https://httpbin.org/post", data=payload1)
# 元组组成的列表
payload2 = [('key1', 'value1'), ('key1', 'value2')]  
r = requests.post("https://httpbin.org/post", data=payload2)
# 列表作为值的字典
payload3 = {'key1': ['value1', 'value2']}  
r = requests.post("https://httpbin.org/post", data=payload3)
  1. 响应数据.text和响应数据.json的区别:
    .text返回类型为str
    .json()返回类型为dict

4.Response对象可以用的方法

import requests

url = "https://www.csdn.net/"

response = requests.get(url)

print(type(response.status_code), response.status_code)

print(type(response.headers), response.headers)

print(type(response.cookies), response.cookies)

print(type(response.url), response.url)

print(type(response.history), response.history)

返回值

<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Server': 'openresty', 'Date': 'Fri, 31 Jul 2020 02:39:55 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Keep-Alive': 'timeout=20', 'Set-Cookie': 'uuid_tt_dd=10_18811577610-1596163195036-368686; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net;, dc_session_id=10_1596163195036.257144; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net;', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Strict-Transport-Security': 'max-age=31536000'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie dc_session_id=10_1596163195036.257144 for .csdn.net/>, <Cookie uuid_tt_dd=10_18811577610-1596163195036-368686 for .csdn.net/>]>
<class 'str'> https://www.csdn.net/
<class 'list'> []

其他返回对象

print(res.text)
print(res.json())

补充:常见的网页状态码:

100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',), 

# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect', 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
 
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
   
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),

5.其他操作

  • 文件上传:
import requests 
files = {'file': open('cookie.txt', 'rb')}
url = "http://httpbin.org/post"
r = requests.post(url, files=files)
print(response.text)
  • 获取cookie
import requests 
url = "https://www.baidu.com"
r = requests.get(url)
print(r.cookies)
for key, value in r.cookies.items(): 
print(key + '=' + value)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值