接口自动化测试(Python+Requests+Unittest)

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": "

文章内容

", "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": "

修改内容

", "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)

你可能感兴趣的:(python,开发语言)