本文主要是介绍Jenkins高级篇之Pipeline实践篇-8-Selenium和Jenkins持续集成-添加事后删除报告功能和解决报告名称硬编码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这篇,我们第一件事情来实现把html报告publish完成之后就删除报告文件。这个是很有必要的操作,虽然我们前面写死了报告名称为index.html,你跑多次测试,都会在test-output文件夹下覆盖原来的html报告文件。但是,就像我们最早的时候,报告名称是特定文字加时间戳命名,那么如果不删除,这个test-output下就有多个html文件。
1.代码优化,添加删除报告文件代码
我之前把publish html report写在了post的区域块代码中,这次我把publish html report抽取到一个新的stage中,然后在post中写删除html报告文件代码。这样测试完一次,都会去执行删除旧测试报告的操作。
完成的selenium_jenkins.groovy代码如下
import hudson.model.*;pipeline{agent anyparameters {string(name: 'BROWSER_TYPE', defaultValue: 'chrome', description: 'Type a browser type, should be chrome/firefox')string(name: 'TEST_SERVER_URL', defaultValue: '', description: 'Type the test server url')string(name: 'NODE', defaultValue: 'win-anthony-demo', description: 'Please choose a windows node to execute this job.')}stages{stage("Initialization"){steps{script{browser_type = BROWSER_TYPE?.trim()test_url = TEST_SERVER_URL?.trim()win_node = NODE?.trim()}}}stage("Git Checkout"){steps{script{node(win_node) {checkout([$class: 'GitSCM', branches: [[name: '*/master']],userRemoteConfigs: [[credentialsId: '6f4fa66c-eb02-46dc-a4b3-3a232be5ef6e', url: 'https://github.com/QAAutomationLearn/JavaAutomationFramework.git']]])}}}}stage("Set key value"){steps{script{node(win_node){selenium_test = load env.WORKSPACE + "\\pipeline\\selenium.groovy"config_file = env.WORKSPACE + "\\Configs\\config.properties"try{selenium_test.setKeyValue("browser", browser_type, config_file)file_content = readFile config_fileprintln file_content}catch (Exception e) {error("Error met:" + e)}}}}}stage("Run Selenium Test"){steps{script{node(win_node){run_bat = env.WORKSPACE + "\\run.bat"bat (run_bat)}}}}stage("Publish Selenium HTML Report"){steps{script{node(win_node){publishHTML (target: [allowMissing: false,alwaysLinkToLastBuild: false,keepAll: true,reportDir: 'test-output',reportFiles: 'index.html',reportName: "HTML Report"])}}}}}post{always{script{node(win_node){//delete report fileprintln "Start to delete old html report file."bat("del /s /q C:\\JenkinsNode\\workspace\\selenium-pipeline-demo\\test-output\\index.html")}}}}}
上面的del语句 也可以写相对文件路径 写".\\test-output\\index.html"。
2.运行效果
具体删除报告日志如下
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] publishHTML
[htmlpublisher] Archiving HTML reports...
[htmlpublisher] Archiving at BUILD level C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output to /var/lib/jenkins/jobs/selenium-pipeline-demo/builds/58/htmlreports/HTML_20Report
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] echo
Start to delete old html report file.
[Pipeline] bat
[selenium-pipeline-demo] Running batch scriptC:\JenkinsNode\workspace\selenium-pipeline-demo>del /s /q C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\index.html
删除文件 - C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\index.html
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
我跑成功的Jenkins job地址如下
http://65.49.216.200:8080/job/selenium-pipeline-demo/58/console
3.测试下载删除文件代码中,使用*.index行不行
上面我制定了删除某路径下的index.html,那么肯定有人会想,能不能以后缀结尾,不要写死报告的名称,接下来,我们在jenkins的replay中改下这个代码,然后进行测试。
测试发现是没问题的
[Pipeline] echo
Start to delete old html report file.
[Pipeline] bat
[selenium-pipeline-demo] Running batch scriptC:\JenkinsNode\workspace\selenium-pipeline-demo>del /s /q C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\*.html
删除文件 - C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\index.html
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
那么,我们github项目的这段代码就改成删除 *.html,接下来我们来研究下能不能把前面写死的报告名称改成灵活一点的。
我改了两处地方
stage("Publish Selenium HTML Report"){steps{script{node(win_node){publishHTML (target: [allowMissing: false,alwaysLinkToLastBuild: false,keepAll: true,reportDir: 'test-output',reportFiles: '*.html',reportName: "Selenium Test Report"])}}}}post{always{script{node(win_node){//delete report fileprintln "Start to delete old html report file."bat("del /s /q C:\\JenkinsNode\\workspace\\selenium-pipeline-demo\\test-output\\*.html")}}}}
结果不行,报告没有直接加载出来,需要手动点击下面的index.html才可以。看来在使用publishHTML这个插件中报告名称写成*.html是不可以的。
4.把报告名称改成selenium-report.html
我把生成extentreport代码中报告名称由index.html改成了selenium-report.html,然后在publishHTML代码中报告名称改成selenium-report.html,测试一下,结果是成功的。
http://65.49.216.200:8080/job/selenium-pipeline-demo/61/Selenium_20Test_20Report/
5.恢复到原始报告名称带时间戳的如何改相关代码
在步骤四中证明了,任意的reportName都是支持,前面我们试过了Index.html和selenium_report.html,那么Test-Report-时间戳.html的文件名称也应该可以,对不对。下面,我给出我的思路,然后动手写代码。
写一个模块方法,用来在test-output文件夹下得到这个带时间戳的html文件名称,然后赋值给一个变量,这样,我们再去调用publishHTML方法,此时,传递给reportName的值就写这个变量的名称,这样就应该可以完成。
5.1 在Reporting.java文件中恢复到原来的报告名称格式,即:“Test-Report-时间戳.html”
5.2 selenium_jenkins.groovy全部代码如下,在publish html report之前调用得到报告名称方法
import hudson.model.*;pipeline{agent anyparameters {string(name: 'BROWSER_TYPE', defaultValue: 'chrome', description: 'Type a browser type, should be chrome/firefox')string(name: 'TEST_SERVER_URL', defaultValue: '', description: 'Type the test server url')string(name: 'NODE', defaultValue: 'win-anthony-demo', description: 'Please choose a windows node to execute this job.')}stages{stage("Initialization"){steps{script{browser_type = BROWSER_TYPE?.trim()test_url = TEST_SERVER_URL?.trim()win_node = NODE?.trim()}}}stage("Git Checkout"){steps{script{node(win_node) {checkout([$class: 'GitSCM', branches: [[name: '*/master']],userRemoteConfigs: [[credentialsId: '6f4fa66c-eb02-46dc-a4b3-3a232be5ef6e', url: 'https://github.com/QAAutomationLearn/JavaAutomationFramework.git']]])}}}}stage("Set key value"){steps{script{node(win_node){selenium_test = load env.WORKSPACE + "\\pipeline\\selenium.groovy"config_file = env.WORKSPACE + "\\Configs\\config.properties"try{selenium_test.setKeyValue("browser", browser_type, config_file)file_content = readFile config_fileprintln file_content}catch (Exception e) {error("Error met:" + e)}}}}}stage("Run Selenium Test"){steps{script{node(win_node){run_bat = env.WORKSPACE + "\\run.bat"bat (run_bat)}}}}stage("Publish Selenium HTML Report"){steps{script{node(win_node){html_file_name = selenium_test.get_html_report_filename("test-output")publishHTML (target: [allowMissing: false,alwaysLinkToLastBuild: false,keepAll: true,reportDir: 'test-output',reportFiles: html_file_name,reportName: "Selenium Test Report"])}}}}}post{always{script{node(win_node){//delete report fileprintln "Start to delete old html report file."bat("del /s /q C:\\JenkinsNode\\workspace\\selenium-pipeline-demo\\test-output\\*.html")}}}}}
5.3 selenium.groovy全部代码如下,重点看get_html_report_filename这个方法
import hudson.model.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;def setKeyValue(key, value, file_path) {// read file, get string objectfile_content_old = readFile file_pathprintln file_content_oldlines = file_content_old.tokenize("\n")new_lines = []lines.each { line ->if(line.trim().startsWith(key)) {line = key + "=" + valuenew_lines.add(line)}else {new_lines.add(line)}}// write into filefile_content_new = ""new_lines.each{line ->file_content_new += line + "\n"}writeFile file: file_path, text: file_content_new, encoding: "UTF-8"
}def get_html_report_filename(report_store_path) {get_html_file_command = "cd ${report_store_path}&dir /b /s *.html"out = bat(script:get_html_file_command,returnStdout: true).trim()out = out.tokenize("\n")[1] // get the second line stringprintln outhtml_report_filename = out.split("test-output")[1].replace("\\", "")println html_report_filenamereturn html_report_filename
}return this;
5.4 运行,看看测试效果
成功的验证jenkins job: http://65.49.216.200:8080/job/selenium-pipeline-demo/74/console
为了防止我jenkins服务器以后不可用,这里贴出一个完整版日志,方便其他人参考。
Started by user admin
Obtained pipeline/selenium_jenkins.groovy from git https://github.com/QAAutomationLearn/JavaAutomationFramework.git
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/selenium-pipeline-demo
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository> git config remote.origin.url https://github.com/QAAutomationLearn/JavaAutomationFramework.git # timeout=10
Fetching upstream changes from https://github.com/QAAutomationLearn/JavaAutomationFramework.git> git --version # timeout=10
using GIT_ASKPASS to set credentials > git fetch --tags --progress https://github.com/QAAutomationLearn/JavaAutomationFramework.git +refs/heads/*:refs/remotes/origin/*> git rev-parse refs/remotes/origin/master^{commit} # timeout=10> git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision ebbc8415225647dbc68e0ea9ad92ca6208e9e59d (refs/remotes/origin/master)> git config core.sparsecheckout # timeout=10> git checkout -f ebbc8415225647dbc68e0ea9ad92ca6208e9e59d
Commit message: "update get report file name"> git rev-list --no-walk 0f7fd4277f66d0716e452f6ec367e29a8f36c177 # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Initialization)
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Git Checkout)
[Pipeline] script
[Pipeline] {
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] checkout> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository> git config remote.origin.url https://github.com/QAAutomationLearn/JavaAutomationFramework.git # timeout=10
Fetching upstream changes from https://github.com/QAAutomationLearn/JavaAutomationFramework.git> git --version # timeout=10
using GIT_ASKPASS to set credentials > git fetch --tags --progress https://github.com/QAAutomationLearn/JavaAutomationFramework.git +refs/heads/*:refs/remotes/origin/*> git rev-parse "refs/remotes/origin/master^{commit}" # timeout=10> git rev-parse "refs/remotes/origin/origin/master^{commit}" # timeout=10
Checking out Revision ebbc8415225647dbc68e0ea9ad92ca6208e9e59d (refs/remotes/origin/master)> git config core.sparsecheckout # timeout=10> git checkout -f ebbc8415225647dbc68e0ea9ad92ca6208e9e59d
Commit message: "update get report file name"
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Set key value)
[Pipeline] script
[Pipeline] {
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] load
[Pipeline] { (C:\JenkinsNode\workspace\selenium-pipeline-demo\pipeline\selenium.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] readFile
[Pipeline] echo
baseURL=http://demo.guru99.com/v4/index.php
# https://www.utest.com backup website
userName=mngr169501
password=sYhYtUd# browser driver path
firefoxpath=./Drivers\\geckodriver.exe
chromepath=./Drivers\\chromedriver.exe# browser instance
# the browser vlaue will only be firefox or chrome here
browser=[Pipeline] writeFile
[Pipeline] readFile
[Pipeline] echo
baseURL=http://demo.guru99.com/v4/index.php
# https://www.utest.com backup website
userName=mngr169501
password=sYhYtUd# browser driver path
firefoxpath=./Drivers\\geckodriver.exe
chromepath=./Drivers\\chromedriver.exe# browser instance
# the browser vlaue will only be firefox or chrome here
browser=chrome[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Run Selenium Test)
[Pipeline] script
[Pipeline] {
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] bat
[selenium-pipeline-demo] Running batch scriptC:\JenkinsNode\workspace\selenium-pipeline-demo>C:\JenkinsNode\workspace\selenium-pipeline-demo\run.batC:\JenkinsNode\workspace\selenium-pipeline-demo>cd C:\JenkinsNode\workspace\selenium-pipeline-demo C:\JenkinsNode\workspace\selenium-pipeline-demo>mvn clean install
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for AnthonyAutoV10:AnthonyAutoV10:jar:0.0.1-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 19, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] -------------------< AnthonyAutoV10:AnthonyAutoV10 >--------------------
[INFO] Building AnthonyAutoV10 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[WARNING] The POM for com.beust:jcommander:jar:1.66 is missing, no dependency information available
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ AnthonyAutoV10 ---
[INFO] Deleting C:\JenkinsNode\workspace\selenium-pipeline-demo\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ AnthonyAutoV10 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\JenkinsNode\workspace\selenium-pipeline-demo\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ AnthonyAutoV10 ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ AnthonyAutoV10 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\JenkinsNode\workspace\selenium-pipeline-demo\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ AnthonyAutoV10 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 11 source files to C:\JenkinsNode\workspace\selenium-pipeline-demo\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ AnthonyAutoV10 ---
[INFO] Surefire report directory: C:\JenkinsNode\workspace\selenium-pipeline-demo\target\surefire-reports-------------------------------------------------------T E S T S
-------------------------------------------------------
Running TestSuite
Starting ChromeDriver 2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab) on port 2607
Only local connections are allowed.
Dec 31, 2018 8:20:23 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSSINFO [main] (TC_NewCustomer_004.java:22)- Login is completedINFO [main] (TC_NewCustomer_004.java:28)- Proving customer details.............INFO [main] (TC_NewCustomer_004.java:46)- Validating adding new customer..............
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 75.55 sec - in TestSuiteResults :Tests run: 1, Failures: 0, Errors: 0, Skipped: 0[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ AnthonyAutoV10 ---
[WARNING] JAR will be empty - no content was marked for inclusion!
[INFO] Building jar: C:\JenkinsNode\workspace\selenium-pipeline-demo\target\AnthonyAutoV10-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ AnthonyAutoV10 ---
[INFO] Installing C:\JenkinsNode\workspace\selenium-pipeline-demo\target\AnthonyAutoV10-0.0.1-SNAPSHOT.jar to C:\Users\Anthont\.m2\repository\AnthonyAutoV10\AnthonyAutoV10\0.0.1-SNAPSHOT\AnthonyAutoV10-0.0.1-SNAPSHOT.jar
[INFO] Installing C:\JenkinsNode\workspace\selenium-pipeline-demo\pom.xml to C:\Users\Anthont\.m2\repository\AnthonyAutoV10\AnthonyAutoV10\0.0.1-SNAPSHOT\AnthonyAutoV10-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:26 min
[INFO] Finished at: 2018-12-31T20:21:35+08:00
[INFO] ------------------------------------------------------------------------
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Publish Selenium HTML Report)
[Pipeline] script
[Pipeline] {
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] bat
[selenium-pipeline-demo] Running batch script
[Pipeline] echo
C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\Test-Report-2018.12.31.20.20.19.html
[Pipeline] echo
Test-Report-2018.12.31.20.20.19.html
[Pipeline] publishHTML
[htmlpublisher] Archiving HTML reports...
[htmlpublisher] Archiving at BUILD level C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output to /var/lib/jenkins/jobs/selenium-pipeline-demo/builds/74/htmlreports/Selenium_20Test_20Report
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] node
Running on win-anthony-demo in C:\JenkinsNode\workspace\selenium-pipeline-demo
[Pipeline] {
[Pipeline] echo
Start to delete old html report file.
[Pipeline] bat
[selenium-pipeline-demo] Running batch scriptC:\JenkinsNode\workspace\selenium-pipeline-demo>del /s /q C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\*.html
删除文件 - C:\JenkinsNode\workspace\selenium-pipeline-demo\test-output\Test-Report-2018.12.31.20.20.19.html
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
本篇就到这里,结合前面一篇,把HTML报告从windows节点机器publish到jenkins服务器上,并保持原来的样式显示的整个过程都给一一介绍了。遇到问题,一点一点去尝试,然后写代码,根据错误提示不断去调整代码。最后来看,代码真的不难,对不对。对我个人来说,在windows上运行bat、dos命令,确实没有在linux上运行shell命令效率高和方法丰富。文章用到的bat相关命令我都是现成网上查找到的,例如如何多个dos命令写到一行执行,这里需要用到符号&,这个很好的锻炼和学习过程。
这篇关于Jenkins高级篇之Pipeline实践篇-8-Selenium和Jenkins持续集成-添加事后删除报告功能和解决报告名称硬编码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!