Devops实现之Pipeline工作流框架 (十)
Pipeline 是一套运行于 jenkins 上的工作流框架,将原本独立运行于单个或者多个节点的任务连接起来,实现单个任务难以完成的复杂流程编排与可视化。
postman 接口自动化测试
项目执行结果
其他项目构建成功后,会触发接口自动化测试项目。接口自动化测试项目分为 3 个阶段:Preparation,Build 和 Result。下图显示项目的执行效果。
新建项目,选择 “流水线” 项目
新建 Pipeline 项目很简单:Jenkins 选择 “新建” -> “流水线”(Pipeline)
项目配置
“General” 配置和 “构建触发器” 配置,这里不再介绍,重点介绍 Pipeline“流水线” 配置,需要把构建过程用 Pipeline script 的形式描述
保存 Pipeline script 有 2 种方法:一种是 pipeline script from SCM:需要配置 SCM 代码存储 Git 地址或 SVN 地址,指定 script 文件 Jenkinsfile 所在路径,每次构建 job 会自动去指定的目录执行 script 文件;界面如下:
一种是 pipeline script,直接在 Web UI 的 script 输入框输入 pipeline script 语句;界面如下:
PIpeline 脚本
node('229') {stage('Preparation') {git credentialsId: '****', url: 'http://gitlab.***.com/***/testcase_****_APITest.git'}sleep time: 1, unit: 'MINUTES'stage('Build') {catchError {sh '''#!/bin/bashcd ..source httpruner_venv/bin/activatecd PCCashier_APITest_Devhrun --dot-env-path devlop.env --html-report-name index_dev.html tests/testcases/'''}echo currentBuild.resultif (currentBuild.result == 'FAILURE'){step([$class: 'Mailer', notifyEveryUnstableBuild: true,recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],[$class: 'RequesterRecipientProvider']])])}}stage('Results') {publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, includes: '**/*.html', keepAll: true, reportDir: '/home/jenkins/work/workspace/PCCashier_APITest_Dev/reports', reportFiles: 'index_dev.html', reportName: 'Html_Report', reportTitles: 'PC收银台接口测试报告'])}
}简单描述脚本的注释。
node('229')表示项目运行在 Jenkins 的节点 229 上。stage('Preparation')项目的 Preparation 阶段,主要填写接口测试项目的 git 库地址,用户名和密码(身份认证),这样每次执行构建,都会更新到最新的状态,执行最新的测试用例。stage('Build')项目的 Build 阶段,主要填写执行接口测试的 shell 脚本,并在测试执行失败时给造成构建失败的代码提交者和触发构建者发送邮件。stage('Results')项目的 Result 阶段,主要填写接口测试执行完成后,发布生成的测试报告(index_dev.html),可在 Jenkins 里查看,报告名是 Html_Report,报告页面的标题是。
第一次接触 Pipeline script,肯定比较困难。Jenkins 也提供了脚本生成器。可以选择需要的功能,并输入参数,可点击自动生成脚本。
Newman 是 postman 的命令行工具,通过命令行执行 Postman 的脚本 (collection)。因此,通过 Newman 执行脚本,可以在 Jenkins 上实现 postman 接口测试持续集成,是一种非常简单方便进行接口测试的方法。主要包括以下步骤:
- 准备软件环境
- 准备测试脚本
- Newman 执行脚本
- 创建 Jenkins 项目
环境准备
工具安装和配置的过程,这里不再详细描述,请网上自行查阅。
- 安装 Jenkins 目前网上很多关于 Jenkins 的安装和配置的资料,比较简单的方式有 2 种:
- Docker 安装
- 直接运行 war 包
java -jar jenkins_located_path/jenkins.war --httpPort=88 &
- 安装 newman 使用命令
npm install -g newman
全局安装工具 newman。前提是已安装 nodejs 和 npm。也可以通过淘宝 NPM 镜像安装 newman,npm install -g newman
使用命令newman -v
检查是否安装成功。 - 安装 html 报告工具 使用命令
npm install -g newman-reporter-html
安装 html 报告模板,方便查看测试用例执行结果
测试脚本
如何写 Postman 的测试脚本,目前网上已有很多资料,请自行查阅。Postman 一直在更新中,建议查看官网文档。
postman 的测试脚本包括 3 部分:
测试用例的脚本 (collection) Newman 执行测试用例是以 collection 为单位的,有 2 种方式获取测试脚本 (collection):
通过 postman 导出 collection 的 Json 格式,查看官网文档;
获取脚本 (collection) 的 URL 地址,查看官方文档
环境变量 (enviroment) Postman 的 “MANAGE ENVIRONMENTS” 中导出对应的环境变量,Json 格式。
- 全局变量 (global) Postman 的 “MANAGE ENVIRONMENTS” 中下载全局变量,Json 格式。
Newman 执行脚本 (collection)
利用newman run -h
命令查看 Newman 执行脚本的使用说明。
ubuntu001:~$ newman run -hUsage: run <collection> [options]URL or path to a Postman Collection.Options:-e, --environment <path> Specify a URL or Path to a Postman Environment.-g, --globals <path> Specify a URL or Path to a file containing Postman Globals.--folder <path> Specify folder to run from a collection. Can be specified multiple times to run multiple folders (default: )-r, --reporters [reporters] Specify the reporters to use for this run. (default: cli)-n, --iteration-count <n> Define the number of iterations to run.-d, --iteration-data <path> Specify a data file to use for iterations (either json or csv).--export-environment <path> Exports the environment to a file after completing the run.--export-globals <path> Specify an output file to dump Globals before exiting.--export-collection <path> Specify an output file to save the executed collection--postman-api-key <apiKey> API Key used to load the resources from the Postman API.--delay-request [n] Specify the extent of delay between requests (milliseconds) (default: 0)--bail [modifiers] Specify whether or not to gracefully stop a collection run on encountering an errorand whether to end the run with an error based on the optional modifier.-x , --suppress-exit-code Specify whether or not to override the default exit code for the current run.--silent Prevents newman from showing output to CLI.--disable-unicode Forces unicode compliant symbols to be replaced by their plain text equivalents--global-var <value> Allows the specification of global variables via the command line, in a key=value format (default: )--color <value> Enable/Disable colored output. (auto|on|off) (default: auto)--timeout [n] Specify a timeout for collection run (in milliseconds) (default: 0)--timeout-request [n] Specify a timeout for requests (in milliseconds). (default: 0)--timeout-script [n] Specify a timeout for script (in milliseconds). (default: 0)--ignore-redirects If present, Newman will not follow HTTP Redirects.-k, --insecure Disables SSL validations.--ssl-client-cert <path> Specify the path to the Client SSL certificate. Supports .cert and .pfx files.--ssl-client-key <path> Specify the path to the Client SSL key (not needed for .pfx files)--ssl-client-passphrase <path> Specify the Client SSL passphrase (optional, needed for passphrase protected keys).-h, --help output usage information
下面介绍常用的参数:
- 必填参数
<collection>
,测试脚本 (collection) 的 Json 格式文件的路径,或者 URL 地址 - 选填参数
-e, --environment <path>
,指定环境变量的 Json 格式文件的路径或者 URL 地址 - 选填参数
-g, --globals <path>
,指定全局变量的 Json 格式文件的路径或者 URL 地址 - 选填参数
-r, --reporters [reporters]
,指定测试报告的文件格式,默认是 cli(命令行输出),还支持 html,Json 格式 - 选填参数
-n, --iteration-count <n>
,定义测试脚本执行的次数,默认是 1
例如:
newman run APITestForAPP.postman_collection.json -e APP.dev_environment.json -g postman_globals.json -r cli,html --reporter-html-export report/reportAPP.html
控制台输出命令行报告,执行路径下生成 html 报告 reportAPP.html:
┌─────────────────────────┬──────────┬──────────┐
│ │ executed │ failed │
├─────────────────────────┼──────────┼──────────┤
│ iterations │ 1 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ requests │ 40 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ test-scripts │ 80 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ prerequest-scripts │ 40 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ assertions │ 121 │ 0 │
├─────────────────────────┴──────────┴──────────┤
│ total run duration: 4.4s │
├───────────────────────────────────────────────┤
│ total data received: 11.31KB (approx) │
├───────────────────────────────────────────────┤
│ average response time: 49ms │
└───────────────────────────────────────────────┘
下面的命令会输出同样的结果。
newman run https://www.getpostman.com/collections/e260b7ccb7ee71eb761a -e APP.dev_environment.json -g postman_globals.json -r cli,html --reporter-html-export report/reportAPP.html
创建 Jenkins 项目
新建一个流水线项目 (Pipeline),具体的创建过程可参见Jenkins 创建流水线 (Pipeline) 项目的脚本。项目中,接口的变更涉及到 3 个客户端,每个端的 URL 地址的域不同,接口实现相同。一次接口测试中,最好 3 个端的接口均运行。Jenkins 的 Pipeline 脚本如下:
node('229') {stage('Preparation') {git credentialsId: '6a9***8-6bf7-445e-aa78-94****4', url: 'http://gitlab.****.com/****/testcase_***_APITest.git'}stage('testWebAPI') {catchError {sh '''#!/bin/bash -ilnewman run APITestForWeb.postman_collection.json -e Web.dev_environment.json -g postman_globals.json -r cli,html --reporter-html-export report/reportWeb.html'''}if (currentBuild.result == 'FAILURE'){step([$class: 'Mailer', notifyEveryUnstableBuild: true,recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],[$class: 'RequesterRecipientProvider']])])}}stage('testAppAPI') {catchError {sh '''#!/bin/bash -ilnewman run APITestForAPP.postman_collection.json -e APP.dev_environment.json -g postman_globals.json -r cli,html --reporter-html-export report/reportAPP.html'''}if (currentBuild.result == 'FAILURE'){step([$class: 'Mailer', notifyEveryUnstableBuild: true,recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],[$class: 'RequesterRecipientProvider']])])}}stage('testCashierAPI') {catchError {sh '''#!/bin/bash -ilnewman run APITestForCashier.postman_collection.json -e Cashier.dev_environment.json -g postman_globals.json -r cli,html --reporter-html-export report/reportCashier.html'''}if (currentBuild.result == 'FAILURE'){step([$class: 'Mailer', notifyEveryUnstableBuild: true,recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],[$class: 'RequesterRecipientProvider']])])}}stage('Results') {publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: '/home/jenkins/work/workspace/APITest_Daily/report', reportFiles: 'reportWeb.html', reportName: 'HTML Report Web', reportTitles: 'Web端接口测试'])publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: '/home/jenkins/work/workspace/APITest_Daily/report', reportFiles: 'reportAPP.html', reportName: 'HTML Report APP', reportTitles: 'APP端接口测试'])publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: '/home/jenkins/work/workspace/APITest_Daily/report', reportFiles: 'reportCashier.html', reportName: 'HTML Report Cashier', reportTitles: '收银台端接口测试'])}
}
执行结果如图:
Soar实现自动化SQL审查
一、Soar介绍
Soar是在文章来源(Source):https://www.dqzboy.com2018年10月20日的开源先锋日上,由小米公布开源的项目,主要是通过智能检查SQL,并对SQL实现优化和改写的工具。
项目地址:https://github.com/XiaoMi/soar
二、功能特点
- 跨平台支持(支持 Linux, Mac 环境,Windows 环境理论上也支持,不过未全面测试)
- 目前只支持 MySQL 语法族协议的 SQL 优化
- 支文章来源(Source):https://www.dqzboy.com持基于启发式算法的语句优化
- 支持复杂查询的多列索引优化(UPDATE, INSERT, DELETE, SELECT)
- 支持 EXPLAIN 信息丰富解读
- 支持 SQL 指纹、压缩和美化
- 支持同一张表多条 ALTER 请求合并
- 支持自定义规则的 SQL 改写
三、安装部署
- Soar的安装很简单,只需要将项目下载下来后,执行soar命令即可使用
[root@localhost ~]# wget https://github.com/XiaoMi/soar/releases/download/0.11.0/soar.linux-amd64 -O soar#或者下载到本机PC再上传至服务器
[root@localhost ~]# mv soar.linux-amd64 soar
[root@localhost ~]# chmod +x soar
[root@localhost ~]# mv soar /usr/local/bin/
[root@localhost ~]# soar --version
Version: 2019-01-21 16:54:09 +0800 0.11.0-16-gc12ae96
Branch: master
Compile: 2019-01-21 16:55:46 +0800 by go version go1.10.7 linux/amd64
GitDirty: 0
四、使用测试
[root@localhost ~]# soar -query "select * from tb;"
# Query: 09D1F5952A76399F★ ★ ★ ☆ ☆ 75分```sqlSELECT *
FROM tb
```## 最外层 SELECT 未指定 WHERE 条件* **Item:** CLA.001* **Severity:** L4* **Content:** SELECT 语句没有 WHERE 子句,可能检查比预期更多的行(全表扫描)。对于 SELECT COUNT(\*) 类型的请求如果不要求精度,建议使用 SHOW TABLE STATUS 或 EXPLAIN 替代。## 不建议使用 SELECT * 类型查询* **Item:** COL.001* **Severity:** L1* **Content:** 当表结构变更时,使用 \* 通配符选择所有列将导致查询的含义和行为会发生更改,可能导致查询返回更多的数据。
五、结合Jenkins
1、安装插件
- Jenkins需要安装插件 HTMLResource,这样才可以将报告通过html方式查看,安装Email 原文链接:https://www.dqzboy.comExtension插件实现邮件通知
2、配置邮件
- Linux系统上安装Email服务
[root@localhost ~]# yum -y install sendmail
[root@localhost ~]# yum install -y mailx
[root@localhost ~]# yum -y install jwhois
3、编写代码
//解决HTML显示问题
System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","")
pipeline {agent { node {label "master"}}stages {stage("CreateSQLFile"){steps{script{sh "echo '${SQL};' > migrate.sql && cat migrate.sql"}}}stage("SoarSQL"){steps{script{sh """#一般jenkins是普通用户运行的,所以把soar命令拷贝到当前jenkins运行用户的家目录下,防止权限问题导致命令无法执行/home/deploy/soar -report-type html -query v${ProjectName}-migrate.sql > soarsql.htmlcat soarsql.html"""publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: '', reportFiles: ' soarsql.html', reportName: 'SQLreport', reportTitles: ''])Email("SQL审核完成 <a href='http://192.168.66.101:8080/ /view/${JOB_NAME}/job/${JOB_NAME}/SQLreport/'>审核报告</a>","${EmailUser}") #Job传入email地址}}}}
}//定义邮件内容
def Email(status,emailUser){emailext body: """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0"> <img src="http://192.168.66.112/jenkins.jpg"> //logo地址<table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif"> <tr> <td><br /> <b><font color="#0B610B">构建信息</font></b> </td> </tr> <tr> <td> <ul> <li>项目名称:${JOB_NAME}</li> <li>构建编号:${BUILD_ID}</li> <li>构建信息: ${status} </li> <li>项目地址:<a href="${BUILD_URL}">${BUILD_URL}</a></li> <li>构建日志:<a href="${BUILD_URL}console">${BUILD_URL}console</a></li> </ul> </td> </tr> <tr> </table> </body> </html> """,subject: "Jenkins-${JOB_NAME}项目构建信息 ",to: emailUser
}
- 如果执行构建出现以下错误,这是因为Jenkins不允许使用外部的css等样式,需要允许后才可以执行
- 处文章来源(Source):https://www.dqzboy.com理方案就是点击下图部分,然后跳转进去选择允许运行脚本
4、创建任务
- 现在我们创建一个流水线任务,配置如下
5、执行构建
5.1:查看分析结果
5.2:查看邮箱消息
Devops实现之Pipeline工作流框架 (十)相关推荐
- MLFlow︱机器学习工作流框架:介绍(一)
文章目录 1 DataOps.MLOps 和 AIOps,你要的是哪个Ops? 2 MLFlow 2.1 MLFlow优势 2.2 MLFlow劣势 2.3 MLFlow 和 AirFlow的差异 2 ...
- 生信工作流框架搭建 | 从零开始入门指南 - 00工作流之华山论剑
本篇为biodoge<生信工作流框架搭建>系列笔记的开篇作,该系列将持续更新. 导语 小白生信工程师一枚,写这样的系列其实是个大工程,出发点很简单,工作是宏基因组相关,我司长期使用的流程p ...
- Docker的Jenkins Pipeline工作流
原文地址:http://www.youruncloud.com/blog/127.html 分享主题 一个软件产品的开发周期中,尤其是敏捷开发,持续集成和持续部署是必不可少的环节,而随着产品的丰富,模 ...
- 技术内幕 | StarRocks Pipeline 执行框架(下)
作者:冉攀峰,StarRocks 核心研发,知乎账号 satanson 导读:欢迎来到 StarRocks 技术内幕系列文章,我们将为你全方位揭晓 StarRocks 背后的技术原理和实践细节,助你快 ...
- 宅急送 项目第八天 JBPM工作流框架
项目第八天和项目第九天 学习 JBPM 理论部分 项目第十天 权限管理模块 项目第十一天 项目第十二天 JBPM 应用 1. 工作流框架概述 1.1. 什么是工作流 工作流(Workflow),就是& ...
- 生信工作流框架搭建 | 01-nextflow、snakemake、wdl 对比测试
本篇为biodoge<生信工作流框架搭建>系列笔记的第2篇,该系列将持续更新. 前情提要 上回说到五大流派华山论剑.各显神通,指标衡量下,方才有三大主流框架脱颖而出: 基于groovy的n ...
- # SpringBoot 整合 Activiti 工作流框架
SpringBoot 整合 Activiti 工作流框架 Activiti 介绍 Activiti是一个开源的工作流引擎,它实现了BPMN 2.0规范,可以发布设计好的流程定义,并通过api进行流程调 ...
- jbpm_工作流框架笔记
1. 工作流基础 1.1. 工作流相关概念 工作流(Workflow),就是"业务过程的部分或整体在计算机应用环境下的自动化",它主要解决的是"使在多个参与者之间按照某种 ...
- .NET 5 开源工作流框架elsa技术研究
编者注: 工作流框架 elsa 是.NET基金会下面的开源项目,2.0版本即将在3月份发布,目前正在紧锣密鼓的开发之中,2020年2月份我也介绍过推荐一个很棒的开源工作流elsa-core ,今天给大 ...
最新文章
- yii2 导入开源php项目_终于来了,yii2和phpstorm的完美整合,支持到你不要不要的。...
- 趣谈NAT和防火墙的对话+防火墙静态PAT的应用
- Python中的进制书写
- 【数据结构与算法】之给Nx3网格图涂色的方案数的求解算法
- TQ2440+RealViewMDK调试LED跑马灯(成功!)
- STL源码剖析 迭代器iterator的概念 和 traits编程技法
- 双拓扑排序 HDOJ 5098 Smart Software Installer
- I.MX6 wm8962 0-001a: DC servo timed out
- asp.net中用LinkButton取到gridview中当前行的ID值
- 如何精通C++ 摘自知乎和quora
- 项目分析-纷享车链AutoChain的数据保险柜解读
- 基于ffmpeg的h264播放器无法播放HI3516开发板保存的h264码流的问题
- UA OPTI570 量子力学 角动量 公式与结论总结
- 开源代码和框架专栏汇总
- 2年python自动化编程自学经历,分享一些学习心得和避坑经验
- python自回归_向量自回归模型(VAR)到底厉害在哪里?
- Linux(Centos 7)使用tcpdump抓取流量包
- 笔刷分享|每个建模人都在用的笔刷合集
- 第二组第一次成团哈哈哈哈
- pandas级联与合并
热门文章
- 三年级语文计算机之父教学反思,小学三年级语文教学反思(5篇)
- 2021年全国科普日长沙主场活动成功举办
- matlab中push,如何在GUI中pushbutton的回调函数中嵌入函数
- SourceInsight使用详解
- 机器学习中的高斯分布
- 英文版资料[庖丁解牛—纵向切入Asp.net 3.5控件和组件开发技术]
- C语言求最大公约数和最小公倍数(思路清晰+拓展)
- [转]ASP.NET验证发生前无法调用 Page.IsValid。应在 CausesValidation=True 且已启动回发的控件...
- 大数据初体验——基于地图可视化分析新浪新闻评论地域分布特点
- 学好新三科计算机英语,学英语专业新高考选科要求:英语专业高考选哪三科?...