自己自学接口自动化过程遇到的问题及解决方法记录
首先是一个简单的请求
import requests
#这是一个简单是get请求
def test_get():
geturl = 'https://so.csdn.net/api/v1/relevant-search?query=pycharm%E5%AE%89%E8%A3%85requests%E5%BA%93&platform=pc'
getr = requests.get(url=geturl)
print(getr.text)
assert getr.status_code == 200
#这是一个post请求
def test_post():
posturl = 'https://so.csdn.net/api/v1/get_landing_word'
postjson={'url':'https://blog.csdn.net/qq_43779149/article/details/122488766'}
postr=requests.post(url=posturl,json=postjson)
print(postr.text)
list_postr = list(postr)
# assert list_postr[1] == 200
assert postr.status_code == 200
利用request库发送请求
然后用pytest的命名规范写了上述代码,后面我需要用allure生成报告
问题一:allure是什么
allure是第三方的命令行工具,无法直接通过python来安装,需要去官网下载
问题二:allure-pytest是什么
allure-pytest是Python 插件,用于生成测试数据,可以直接用pip来安装
遇到的问题:
一:官网下载的allure没用bin目录,无法用命令行去执行,最后还是在csdn上的某个博客上找到了个人分享的allure压缩包
分享者是:@旺仔牛奶
分享链接是:pycharm中Allure的安装及其环境配置_pycharm安装allure-CSDN博客
链接:https://pan.baidu.com/s/1tMWm5p4sYXgcj5AP4GeRbg?pwd=284i
提取码:284i
下载好allure后,需要找到bin目录,并将其配置环境变量
点击电脑,选择属性—>高级系统设置—>环境变量设置—>系统变量—>Path环境,然后
选中Path点击编辑,然后选择新建,然后将复制的Allure的bin目录的路径粘贴即可,然后点击确定
上述两个下载好之后进行验证
验证命令:pip show allure-pytest
验证命令:allure --version
之后重启PyCharm即可使用allure
之后使用代码
# 运行要进行测试的py文件,生成测试数据到当前目录下的allure-results文件夹
pytest.main(["-s", "alluredpytest.py", "--alluredir=allure-results"])
# 执行allure服务,将allure-results文件夹的测试数据转html,并自动打开网页
subprocess.run("allure serve allure-results", shell=True)
# 服务处于开启状态,关闭服务则链接失效,不可查看报告
allure装饰器的应用
@allure.feature("CSDN接口测试") # 模块/功能分类
class TestCSDNAPI: # 测试类
@allure.story("GET接口测试") # 子功能/用户场景分类
@allure.title("搜索相关文章接口") # 用例标题(默认是函数名,可自定义)
@allure.description("验证GET请求返回状态码200") # 用例描述
将上面的请求加上装饰器的完整代码如下
import allure
import requests
@allure.feature("CSDN接口测试") # 模块/功能分类
class TestCSDNAPI:
@allure.story("GET接口测试") # 子功能/用户场景分类
@allure.title("搜索相关文章接口") # 用例标题(默认是函数名,可自定义)
@allure.description("验证GET请求返回状态码200") # 用例描述
def test_get(self):
with allure.step("步骤1:发送GET请求"): # 记录详细步骤
geturl = 'https://so.csdn.net/api/v1/relevant-search?query=pycharm%E5%AE%89%E8%A3%85requests%E5%BA%93&platform=pc'
getr = requests.get(url=geturl)
allure.attach(f"请求URL: {geturl}", "请求详情") # 附加请求信息到报告
allure.attach(f"响应状态码: {getr.status_code}", "响应详情")
with allure.step("步骤2:验证状态码"):
print(getr.text)
assert getr.status_code == 200, "状态码非200" # 断言失败时显示自定义错误信息
@allure.story("POST接口测试")
@allure.title("获取落地页关键词接口")
def test_post(self):
posturl = 'https://so.csdn.net/api/v1/get_landing_word'
postjson = {'url': 'https://blog.csdn.net/qq_43779149/article/details/122488766'}
with allure.step("发送POST请求"):
postr = requests.post(url=posturl, json=postjson)
# 将请求和响应数据附加到Allure报告
allure.attach(str(postjson), "请求Body", allure.attachment_type.JSON)
allure.attach(postr.text, "响应Body", allure.attachment_type.JSON)
with allure.step("验证状态码"):
# 移除有问题的 list_postr = list(postr)(Response对象不能直接转为list)
assert postr.status_code == 200, f"状态码错误,实际为{postr.status_code}"
运行allure服务,并且自动打开测试报告页面,查看详细报告