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 --
作者:IT小学生木江
时间:2021/1/7 21:48
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 --
作者:IT小学生木江
时间:2021/1/9 22:51
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 --
作者:IT小学生木江
时间:2021/1/7 22:25
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())

>
> cookie自动获取
>
>
>
-- coding:utf-8 --
作者:IT小学生木江
时间:2021/1/9 22:51
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 --
作者:IT小学生木江
时间:2021/1/9 23:26
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 --
作者:IT小学生木江
时间:2021/1/9 23:23
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 --
作者:IT小学生木江
时间:2021/1/7 22:25
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())

### (6)结合Python+Requests+Unittest框架做接口自动化测试
>
> unittest框架结构:
>
>
>

代码地址:[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 = "蔡坨坨" + 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)
# 编辑完,查询文章
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)
# ④查看文章详情
article_id = str(article_id)
result = self.requests.get("http://[服务器ip]:8081/article/" + article_id, headers=headers)
print(result.json())
if result.json()["title"] == title:
act = "ok"
self.assertEqual(act, "ok")
# ⑤删除文章
payload = {'aids': article_id, 'state': 1}
result = self.requests.put("http://[服务器ip]:8081/article/dustbin", headers=headers, data=payload)
print(result.json())
act = result.json()["msg"]
self.assertEqual(act, "删除成功!")
### (8)通过HTMLTestRunner.py生成可视化HTML测试报告

-- coding:utf-8 --
作者:IT小学生木江
时间:2021/1/10 13:45
from reports import HTMLTestRunner
from case.exam_case.teacher_case import TeacherCase
import unittest
import os
import time
创建测试套件
suite = unittest.TestSuite()
添加测试用例,根据添加顺序执行
添加单个测试用例
suite.addTest(TeacherCase(“test_001_admin_login”))
添加多个测试用例
suite.addTests([TeacherCase(“test_001_admin_login”),
TeacherCase(“test_002_insert_paper”),
TeacherCase(“test_003_select_paper”),
])
定义测试报告的存放的路径
path = r"D:\Desktop\Testman_Study\unittest_exam_system\reports"
判断路径是否存在
if not os.path.exists(path):
# 如果不存在,则创建一个