接口自动化可以通过两种方式实现
第一就是通过postman等工具进行的接口自动化测试
第二就是通过代码的形式来对其进行自动化的测试
本篇主要讲解一下关于代码的自动化
首先,先通过一段代码快速开始post和get两种请求:
需要的依赖库有requests,测试框架pytest
get请求
import requests
def test_topic():
r = requests.get(url="http://39.107.96.138:3000/api/v1/topics?page=1&tab=ask&limit=1&mdrender=true")
print(r,type(r))
# 响应结果 body 文本格式
text = r.text
print("text:", type(text), text)
# 响应结果 body 字典格式
json = r.json()
print('json',type(json),json)
# 响应状态码
statuscode = r.status_code
assert statuscode == 200, "状态码应该为200"
success = json['success']
assert success, 'success 应该为True'
# 对data 数据的长度进行断言
data = json['data']
assert len(data) == 1,"响应数据应该只有1条"
for obj in data:
assert obj['tab'] == 'ask', "tab 值应该为ask"
post请求:
import requests
import pytest
def test_new_topic():
baseurl='http://39.107.96.138:3000/api/v1'
url = baseurl+'/topics'
testdata = {
"accesstoken":"0418178a-b80c-4e15-aa8f-bab03a3491cb",
"title":"1111ssssssss",
"tab":"ask",
"content":"xxxxxxxxxxxxx"
}
r = requests.post(url=url,data=testdata)
print(r.json())
# 请求头信息
print(r.request.headers)
通过代码能够直接看出get和post请求两者之间代码的差别,首先get请求需要携带的是请求参数和请求头信息而post需要的是请求体body和请求头信息(关于get与post的差别请关注我后几篇文章)
通过post的发送和get的获取这两个接口数据传输的完成,能否通过数据联动的方式来进行(API关联)接口测试呢,答案是肯定的:
import requests
import pytest
def test_new_topic():
baseurl='http://39.107.96.138:3000/api/v1'
url = baseurl+'/topics'
testdata = {
"accesstoken":"0418178a-b80c-4e15-aa8f-bab03a3491cb",
"title":"1111ssssssss",
"tab":"ask",
"content":"xxxxxxxxxxxxx"
}
r = requests.post(url=url,json=testdata)
print(r.json())
# 请求头信息
print(r.request.headers)
json = r.json()
assert r.status_code == 200
success = json['success']
assert success
topic_id = json['topic_id']
assert topic_id is not None
# 查看主题详情
detail_url = baseurl+'/topic/'+ topic_id
paramsdata= {'mdrender':'false'}
res = requests.get(url=detail_url,params=paramsdata)
assert res.status_code == 200
resjson = res.json()
assert resjson['success']
resjsondata = resjson['data']
assert resjsondata['tab'] == testdata["tab"], "发帖板块应该为"+testdata['tab']
assert resjsondata['title'] == testdata["title"], "发帖标题应该为" + testdata['title']
assert resjsondata['content'] == testdata["content"], "发帖内容应该为" + testdata['content']
两段代码原理上属于简单的拼接,然后再对其进行数据对比,实现了API的联动
这可能是接口自动化的冰山一角,后面我会对其进行完善。