postman(九):postman接口测试脚本集成到jenkins

本篇的目的是实现使用jenkins远程执行postman接口测试脚本

准备工作:一台linux服务器(可以用虚拟机搭建一个),linux服务器上安装好node.js、newman,部署好jenkins

阶段一:远程执行接口测试脚本

1. 新建一个自由风格的软件项目

2. 在Build标签配置shell脚本(linux服务器选择执行shell;windows系统选择执行windows批处理命令)

(1) 在填写shell脚本前,需要把在postman中导出的json格式的脚本上传到服务器某个目录下,例如我上传到了服务器的 /hanmk/postman_script

 

(2) jenkins在远程执行服务器中的脚本时,也需要切换到测试脚本所在目录(或者直接以绝对路径指定脚本),然后调用newman命令来执行,如下

 

source /etc/profile

#!/bin/bash -ilex

cd /hanmk/postman_script

newman run Test.postman_collection.json -e base_url.postman_environment.json --reporters cli,json,html,junit --reporter-json-export report-json.json --reporter-html-export report-html.html --reporter-junit-export report-xml.xml

注意:需要加上前2行指令,不然在jenkins在远程执行时,会提示找不到newman命令导致构建失败,原因是jenkins执行过程中没有加载到环境变量

开始只加了第二条指令就能够执行成功了,后来重启后发现执行会失败,所以又在此基础上添加第一条指令

相关解析可以参考:

https://blog.csdn.net/zzusimon/article/details/57080337 

https://www.cnblogs.com/silvi/p/7091321.html 

https://blog.csdn.net/luliuliu1234/article/details/80932788

(3)配置完成后,构建一下,然后到这个构建任务的console out中查看构建日志,可以看出构建时成功的,打出了接口执行情况

 

阶段二:把newman生成的html格式的测试报告在jenkins中展示出来

需要先安装一个插件 Publish HTML reports

然后在构建后操作中添加该插件,并进行如下配置

 

HTML directory to archive 填写相对于工作空间的html报告所在的目录,需要填写真实存在的目录名称

Index page[s] 报告目录中提供链接的文件,需要填写一个已经存在的html文件

Report title 报告标题

(1) 要弄明白上述的HTML directory to archiveIndex page[s] 该怎么填,需要先搞清楚jenkins的工作空间的概念。

jenkins每创建一个任务,都会为这个任务产生一个工作空间,jenkins工作空间在服务器中的路径为 /root/.jenkins/workspace

例如这个任务名称为:run_postman-2则它的工作空间为 /root/.jenkins/workspace/run_postman-2

 

所以需要先在工作空间中创建一个名为 htmlreports 的目录,再在 HTML directory to archive 处填写相对工作空间的目录名称才有意义

 

(2)接下来是 Index page[s]在这里填写的html文件名称也必须是已经存在于报告目录中的文件,可以自己在htmlreports中创建一个html文件,或者直接把newman生成的html格式的报告放到这个目录下

注:之所以需要自己创建报告目录和报告文件,是因为这个插件不会自己创建这些,如果工作空间没有这些目录和文件,到时候构建时会报错的

这里我是直接把newman生成的html报告指定输出到工作空间的htmlreports目录中了,改下shell脚本就行

newman run Test.postman_collection.json -e base_url.postman_environment.json --reporters cli,json,html,junit --reporter-json-export report-json.json --reporter-html-export /root/.jenkins/workspace/run_postman-2/htmlreports/report-html.html --reporter-junit-export report-xml.xml

保证Index page[s]处填写的文件名称和生成的报告名称一致

完成上述配置后,进行一次构建动作,构建成功后,会在右侧出现一个html报告按钮,点击查看即可

 

同时,构建成功后,工作空间的htmlreports目录会出现一个report-html.html文件(如果没有在这个job的工作空间创建htmlreports目录,那么点开这里的Workspace显示就是空的了,什么都没有)

 

 

相关知识点可以参考:https://blog.csdn.net/xu19950210rou/article/details/74729296

原文地址:https://www.cnblogs.com/hanmk/p/10387526.html