既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
actual_result = result[“data”][0][“comment”][“user_name”]
print(actual_result)
if expect_result == actual_result:
print(“pass!”)
else:
print(“failed!”)
>
> 响应超时timeout
>
>
>
import requests
V部落:http://[服务器ip]:8081/index.html
文章列表
url_v_article = “http://[服务器ip]:8081/article/all”
v_headers = {
“Cookie”: “studentUserName=ctt01; Hm_lvt_cd8218cd51f800ed2b73e5751cb3f4f9=1609742724,1609762306,1609841170,1609860946; adminUserName=admin; JSESSIONID=9D1FF19F333C5E25DBA60769E9F5248E”}
article_params = {“state”: 1, # -1:全部文章 1:已发表 0:回收站 2:草稿箱
“page”: 1, # 显示第1页
“count”: 6, # 每页显示6条
“keywords”: “” # 包含的关键字
}
keywords = [“大橘猫”, “跑男”, “牙”]
for keyword in keywords:
article_params[“keywords”] = keyword
# headers和params是不定长的,根据定义的字典传参
# timeout超时,单位为秒
# 通过设置超时时间,告诉requests在经过多久后停止等待响应
result = requests.get(url_v_article, headers=v_headers, params=article_params, timeout=30)
print(result.json())
>
> JSON、URL、text、encoding、status\_code、encoding、cookies
>
>
>
print(result.json()) # 响应结果以json的形式打印输出
print(result.url) # 打印url地址
print(result.text) # 以文本格式打印服务器响应的内容
print(result.status_code) # 响应状态码
print(result.encoding) # 编码格式
print(result.cookies) # cookie
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
JSON格式在Python里面相当于字典类型。
JSON格式化:JSON在线视图查看器(Online JSON Viewer)
url在线编码转换:URL在线编码转换工具 - 编码转换工具 - W3Cschool
(3)get、post、put、delete请求方式的自动化实现
>
> GET请求方式
>
>
>
-- coding:utf-8 --
import requests
url_toutiao = “https://www.ixigua.com/tlb/comment/article/v5/tab_comments/?tab_index=0&count=10&group_id=6914830518563373581&item_id=6914830518563373581&aid=1768”
方式一:
result_toutiao = requests.get(url_toutiao)
方式二:
result_toutiao = requests.get(url=url_toutiao)
方式三:
result_toutiao = requests.get(
“https://www.ixigua.com/tlb/comment/article/v5/tab_comments/?tab_index=0&count=1&group_id=6914830518563373581&item_id=6914830518563373581&aid=1768”)
print(result_toutiao.json())
print(type(result_toutiao.json())) # <class ‘dict’>
result = result_toutiao.json()
print(result)
expect_result = “华晨金杯汽车花朵朵”
actual_result = result[“data”][0][“comment”][“user_name”]
print(actual_result)
if expect_result == actual_result:
print(“pass!”)
else:
print(“failed!”)
运行结果:
{‘message’: ‘success’, ‘err_no’: 0, ‘data’: [{‘comment’: {‘id’: 6914864825282215951, ‘id_str’: ‘6914864825282215951’, ‘text’: ‘藁城出国打工的人很多,重点检查藁城区!’, ‘content_rich_span’: ‘{“links”:[]}’, ‘user_id’: 940799526971408, ‘user_name’: ‘华晨金杯汽车花朵朵’,}, ‘post_count’: 0, ‘stick_toast’: 1, ‘stable’: True}
华晨金杯汽车花朵朵
pass!
>
> POST请求方式
>
>
>
-- coding:utf-8 --
import requests
url_v_login = “http://[服务器ip]:8081/login”
定义参数,字典格式
payload = {‘username’: ‘sang’, ‘password’: ‘123’}
Content-Type: application/json --> json
Content-Type: application/x-www-form-urlencoded --> data
result = requests.post(url_v_login, data=payload)
将返回结果转为json格式
result_json = result.json()
print(result_json) # {‘status’: ‘success’, ‘msg’: ‘登录成功’}
获取RequestsCookieJar
result_cookie = result.cookies
print(result_cookie, type(result_cookie)) # RequestsCookieJar
将RequestsCookieJar转化为字典格式
result_cookie_dic = requests.utils.dict_from_cookiejar(result_cookie)
print(result_cookie_dic) # {‘JSESSIONID’: ‘D042C5FE4CFF337806D545B0001E7197’}
获取SESSION
final_cookie = “JSESSIONID=” + result_cookie_dic[“JSESSIONID”] # SJSESSIONID=D042C5FE4CFF337806D545B0001E7197
print(final_cookie)
>
> PUT请求方式
>
>
>
V部落_编辑栏目
定义请求头,自动获取cookie的方法详情请看下文
headers = {“Cookie”: “VBlog(self.requests).get_cookie()”}
new_now_time = time.strftime(“%Y%m%d%H%M%S”, time.localtime(time.time()))
new_category_name = “更新栏目” + new_now_time
payload = {“id”: 2010, “cateName”: new_category_name}
self.requests.put(“http://[服务器ip]:8081/admin/category/”, headers=headers, data=payload)
>
> DELETE请求方式
>
>
>
删除栏目
result = self.requests.delete(“http://[服务器ip]:8081/admin/category/” + “2010”, headers=headers)
print(result.json()) # {‘status’: ‘success’, ‘msg’: ‘删除成功!’}
self.assertEqual(“删除成功!”, result.json()[“msg”])
(4)接口自动化测试过程中cookie的处理
>
> 手动传入cookie的值(每次通过浏览器F12抓包,然后复制request header里面的cookie)
>
>
>
-- coding:utf-8 --
import requests
V部落查询栏目
url_v_category = “http://[服务器ip]:8081/admin/category/all”
定制请求头
如果你想为请求添加HTTP头部,只要简单地传递一个字典给headers参数就可以了
v_headers = {
“cookie”: “studentUserName=ctt01; Hm_lvt_cd8218cd51f800ed2b73e5751cb3f4f9=1609742724,1609762306,1609841170,1609860946; adminUserName=admin; JSESSIONID=9D1FF19F333C5E25DBA60769E9F5248E”}
result = requests.get(url_v_category, headers=v_headers)
打印json格式的响应结果
print(result.json())
![](https://img-blog.csdnimg.cn/2b6e31fe23da4e88a61b09b3beb974ba.png)
>
> cookie自动获取
>
>
>
-- coding:utf-8 --
import requests
url_v_login = “http://[服务器ip]:8081/login”
定义参数,字典格式
payload = {‘username’: ‘sang’, ‘password’: ‘123’}
Content-Type: application/json --> json
Content-Type: application/x-www-form-urlencoded --> data
result = requests.post(url_v_login, data=payload)
将返回结果转为json格式
result_json = result.json()
print(result_json) # {‘status’: ‘success’, ‘msg’: ‘登录成功’}
获取RequestsCookieJar
result_cookie = result.cookies
print(result_cookie, type(result_cookie)) # RequestsCookieJar
将RequestsCookieJar转化为字典格式
result_cookie_dic = requests.utils.dict_from_cookiejar(result_cookie)
print(result_cookie_dic) # {‘JSESSIONID’: ‘D042C5FE4CFF337806D545B0001E7197’}
获取SESSION
final_cookie = “JSESSIONID=” + result_cookie_dic[“JSESSIONID”] # SJSESSIONID=D042C5FE4CFF337806D545B0001E7197
print(final_cookie)
>
> 批量获取cookie脚本
>
>
>
-- coding:utf-8 --
import requests
def get_cookie(username, password):
“”“通过考试系统学生登录获取单个cookie”“”
url_login = "http://[服务器ip]:8088/api/user/login"
payload = {"userName": username, "password": password, "remember": False}
result = requests.post(url_login, json=payload)
# result_json = result.json()
# print(result_json)
# 获取RequestsCookieJar
result_cookie = result.cookies
# print(result_cookie, type(result_cookie)) # RequestsCookieJar
# 将RequestsCookieJar转化为字典格式
result_cookie_dic = requests.utils.dict_from_cookiejar(result_cookie)
# print(result_cookie_dic) # {'SESSION': 'YzFkM2IzN2QtZWY1OC00Nzc4LTgyOWYtNjg5OGRiZDZlM2E4'}
# 获取SESSION
final_cookie = "SESSION=" + result_cookie_dic["SESSION"] # SESSION=Mzc2...
return final_cookie
-- coding:utf-8 --
from test01.demo04_student_login import get_cookie
import os
def get_batch_cookies():
“”“批量获取cookie”“”
# 获取cookie之前,先将cookies.csv文件内容清空
# with open(r"D:\Desktop\Testman_Study\API_auto\file\cookies.csv", “w”) as cookies_info:
# cookies_info.write(“”)
# 或者将文件删除
os.remove(r"D:\Desktop\Testman_Study\API_auto\file\cookies.csv")
# 读取csv文件
with open(r"D:\Desktop\Testman_Study\API_auto\file\register.csv", "r") as user_info:
for user in user_info:
user_list = user.strip().split(",")
# 调用获取单个cookies的方法,传入注册好的用户名和密码
cookies = get_cookie(user_list[0], user_list[1])
# 将cookie追加写入文件
with open(r"D:\Desktop\Testman_Study\API_auto\file\cookies.csv", "a") as cookies_info:
cookies_info.write(cookies + "\n")
调用方法
get_batch_cookies()
register.csv(前提是这些账号和密码都是已经注册过的,可以直接登录)
poopoo001,123456,1
poopoo002,123457,2
poopoo003,123458,3
poopoo004,123459,4
…
cookies.csv
SESSION=ZmE3YmU4ZDctNDExZS00MDdhLWE0YjEtMjAyZjQxOTMxYmUx
SESSION=YjdkNTZhNTUtNGFmMi00MjVkLWEyNjctOTNiMmRmOTY1YTdm
SESSION=ZTJmMTYzMWEtZjUzOS00NTlhLWI0OWQtMzBmN2RkYmU4YmRi
SESSION=YTM0ZGRhOTctZjk5Ni00OWZhLTg1YTItZjUyMTMwZGE2MjVi
…
### (5)不同类型请求参数的处理
-- coding:utf-8 --
import requests
文章列表
url_v_article = “http://[服务器ip]:8081/article/all”
v_headers = {
“Cookie”: “studentUserName=ctt01; Hm_lvt_cd8218cd51f800ed2b73e5751cb3f4f9=1609742724,1609762306,1609841170,1609860946; adminUserName=admin; JSESSIONID=9D1FF19F333C5E25DBA60769E9F5248E”}
自定义url参数,定义一个字典,将参数拆分,再将字典传递给params变量即可
article_params = {“state”: 1, # -1:全部文章 1:已发表 0:回收站 2:草稿箱
“page”: 1, # 显示第1页
“count”: 6, # 每页显示6条
“keywords”: “” # 包含的关键字
}
keywords = [“大橘猫”, “跑男”, “牙”]
for keyword in keywords:
article_params[“keywords”] = keyword
# headers和params是不定长的,根据定义的字典传参
result = requests.get(url_v_article, headers=v_headers, params=article_params)
print(result.json())
![](https://img-blog.csdnimg.cn/d2126d9674d845e5a8d23aa35104fa13.png)
### (6)结合Python+Requests+Unittest框架做接口自动化测试
>
> unittest框架结构:
>
>
>
![](https://img-blog.csdnimg.cn/834ce4c36d1f4517bbdc3857b55b6eb8.png)
代码地址:[https://github.com/itcaituotuo/unittest\_api]( )
>
> if \_*name*\_ == '\_\_main\_\_':
>
>
>
if \_\_name\_\_ == '\_\_main\_\_'的意思是:
当.py文件被直接运行时,if \_\_name\_\_ == '\_\_main\_\_'下的代码块将被运行;
当.py文件以模块形式被导入时,if \_\_name\_\_ == '\_\_main\_\_'下的代码块不被运行。
(7)接口自动化测试过程中高级断言
>
> 闭环断言(新增 --> 查询 --> 修改 --> 查询 --> 删除 -->查询)
>
>
>
def test_article(self):
# ①V部落_新增文章
now_time = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
title = "123" + now_time
payload = {"id": -1, "title": title, "mdContent": "文章内容", "state": 1, "htmlContent": "<p>文章内容</p>",
"dynamicTags": "", "cid": 62}
headers = {"Cookie": VBlog(self.requests).get_cookie()}
result = self.requests.post("http://[服务器ip]:8081/article/", headers=headers, data=payload)
# ②查询文章
url_v_article = "http://[服务器ip]:8081/article/all"
article_params = {"state": 1, # -1:全部文章 1:已发表 0:回收站 2:草稿箱
"page": 1, # 显示第1页
"count": 6, # 每页显示6条
"keywords": title # 包含的关键字title
}
result = requests.get(url_v_article, headers=headers, params=article_params, timeout=30)
print(result.json()) # 响应结果以json的形式打印输出
ls = result.json()["articles"]
act = 123
# 查到新增的文章,说明新增成功
for l in range(0, len(ls)):
if ls[l]["title"] == title:
act = "ok"
article_id = ls[l]["id"]
self.assertEqual("ok", act)
# ③编辑文章
now_time = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
title = "修改文章" + now_time
payload = {"id": article_id, "title": title, "mdContent": "修改内容", "state": 1, "htmlContent": "<p>修改内容</p>",
"dynamicTags": "", "cid": 62}
headers = {"Cookie": VBlog(self.requests).get_cookie()}
self.requests.post("http://[服务器ip]:8081/article/", headers=headers, data=payload)
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
": VBlog(self.requests).get_cookie()}
self.requests.post(“http://[服务器ip]:8081/article/”, headers=headers, data=payload)
[外链图片转存中…(img-CQtA6RJ3-1715047141841)]
[外链图片转存中…(img-DWbk331k-1715047141842)]
[外链图片转存中…(img-XchOpL0d-1715047141842)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新