本篇内容介绍了“如何用python编写接口测试文档”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
打开postman,点击右侧的</>图标,页面右边会显示脚本,顶部修改导出的语言,这边我使用的是Python-Reqyests
复制脚本,在PyCharm中打开即可,在导入使用之前如果没有reuqests库,可能会报错,我们需要安装reuqests库。
cmd命令窗口输入:pip install requests
导出后的脚本格式如下:
import requests
url = "<https://www.douban.com/search?">
payload={'q': '三体'}
files=[
]
headers = {
'Cookie': 'bid=5bBvkukAbvY'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
1.下面就是转成pytest的测试用例
import requests
class TestDouban:
def test_douban(self):
url = "<https://www.douban.com/search?">
payload = {'q': '三体'}
files = []
headers = {
'Cookie': 'bid=5bBvkukAbvY'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
在一个项目中,根路由的路径是一样的,只是不同功能对应的具体的接口不一致,且POST和GET是目前测试用例中比较通用的方法,所以可以将根路由、POST和GET方法封装成一个通用的类,后面直接调用即可。
import requests
class Common:
def __init__(self):
# 豆瓣根路由
self.url_root = "<https://www.douban.com>"
# get请求,uri是接口具体地址,params是get请求的参数,如果没有,默认为空
def get(self, uri, params=''):
# 拼凑访问地址
url = self.url_root + uri + params
# 通过get请求访问对应地址
response = requests.get(url)
# 返回request的response结果,类型为requests的Response类型
return response
# post请求,uri是接口具体地址,params是post请求的参数,如果没有,默认为空
def post(self, uri, params=''):
# 拼凑访问地址
url = self.url_root + uri
# 有参数,则访问对应的url,并赋值给默认参数data
if len(params) > 0:
response = requests.post(url, data=params)
# 无参数,只需要访问对应的url即可
else:
response = requests.post(url)
# 返回request的response结果,类型为requests的Response类型
return response
import requests
from common.common import Common
class TestDouban:
def setup(self):
self.com = Common()
def test_douban(self):
uri = "/search?"
payload = {'q': '三体'}
response = self.com.post(uri, payload)
# 由于file不需要,就将file删除了,至于hearder是否要添加可根据需求来定
执行结果如下:
“如何用python编写接口测试文档”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4469946/blog/4410528