Publish Karma unit tests in Jenkins - jenkins

Jenkins already builds my Maven Java project. I want the results of karma unit tests to show up in Jenkins, but unfortunately I cannot introduce any configuration changes in Jenkins. How karma should be configured to acomplish that?

in order for Jenkins to be able to parse karma test results they must be published in the Junit XML format, the plugin that does that is karma-junit-reporter
junit test results (outputFile in the karma configuration file) must be stored in target/surefire-reports/TESTS-TestSuite.xml

reporters : ['progress', 'junit', 'coverage'],
port : 9876,
colors : true,
logLevel : config.LOG_INFO,
// don't watch for file change
autoWatch : false,
// only runs on headless browser
browsers : ['PhantomJS'],
// just run one time
singleRun : true,
// remove `karma-chrome-launcher` because we will be running on PhantomJS
// browser on Jenkins
plugins : [
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-junit-reporter',
'karma-coverage',
'karma-jenkins-reporter'
],
// changes type to `cobertura`
coverageReporter : {
type : 'cobertura',
dir : 'target/coverage-reports/'
},
// saves report at `target/surefire-reports/TEST-*.xml` because Jenkins
// looks for this location and file prefix by default.
junitReporter : {
outputDir : 'target/surefire-reports/'
}

Old post, but top result in Google.
Configure karma.conf.js to use 'karma-junit-reporter' and report to outputDir = 'target/karma-reports/'
In your pom.xml, give the test execution step an execution/id like 'karmaTests'
In your pom.xml, set a property jenkins.karmaTest.reportsDirectory = target/karma-reports
Full examples are on this blog post.

Related

Jenkins, Gradle : How to publish Dependency report to Sonar Dashboard

Currently we're using Jenkins free style job for Gradle project and using following commands to run Sonar and Dependencycheck
./gradlew clean build sonarqube dependencyCheckAnalyze \
and I'm getting following message
Analyzing /opt/jenkins_slave_home/workspace/AA/package-lock.json - however, the node_modules directory does not exist. Please run npm install prior to running dependency-check
Generating report for project AA_ArbitraryBuild
Found 0 vulnerabilities in project AA
and we can able to see a file inside "ws/build/reports/" but it dint scanned anything.
Following are the "build.gardle" file
buildscript {
repositories {
maven { url artifactoryRepoUrl }
mavenCentral()
}
dependencies {
classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7'
classpath 'org.owasp:dependency-check-gradle:6.0.3'
}
}
apply plugin: 'org.sonarqube'
apply plugin: 'org.owasp.dependencycheck'
sonarqube {
properties {
property 'sonar.projectName', sonarProjectName
property 'sonar.projectKey', sonarProjectKey
property 'sonar.host.url', sonarHostUrl
property 'sonar.login', sonarAuthToken
property 'sonar.dependencyCheck.reportPath', sonarDependencyCheckReport
property 'sonar.dependencyCheck.htmlReportPath', sonarDependencyCheckHTMLReport
}
}
Can you plz help on what are the additional steps that I need to add.
You've got all you need to push result to sonar. Make sure that you provide right path for your owasp vulnerabilities report for sonar plugin. It's sonar.dependencyCheck.reportPath and should point to build/reports directroy, and if you produce html report file you can point it with sonar.dependencyCheck.htmlReportPath.

gradle artifactorypublish: jenkins pipeline does not publish properties

I'm trying to set up a jenkins pipeline for publishing a zip file to jfrog artifactory.
I am using com.jfrog.artifactory plugin to do so. This works great from command line gradle and I can run the artifactoryPublish task to publish the artifacts and tie them back to the module, which then has a tie back to the artifacts.
The artifacts show up with the properties:
build.name = `projectname`
build.number = `some large number`
And I can click from them to the build/module and back to the artifact.
However, when I run this from a jenkinsfile pipeline, the artifacts get published and get tied back to the module, but then the module does not successfully tie the module back to the artifacts.
The artifacts do not receives the build.name and build.number properties and i cannot click from the module back to the artifacts, as the module cannot find or resolve the paths back to the artifacts(a zip file and a generated pom).
I am passing the params from jenkins like:
ORG_GRADLE_PROJECT_buildInfo.build.number=${env.BUILD_NUMBER} which seems to work on other projects... but for whatever reason I cannot shake it.
I can include more jenkinsfile if that would help debug, but i'm really just checking out a repository and trying to publish it.
I have been reading heavily the documentation here:
https://www.jfrog.com/confluence/display/RTF/Gradle+Artifactory+Plugin
and haven't been able to make it work through -Pproject stuff.
Does anyone have any idea what else I can try? i don't really want to use the jenkins pipeline artifactory plugin directly because it's so nice to be able to deploy from the command line too.
build.gradle:
publishing {
publications {
ManualUpdaterPackage(MavenPublication){
artifact assembleManualUpdaterPackage
}
}
}
artifactory {
contextUrl = "${artifactoryUrl}" //The base Artifactory URL if not overridden by the publisher/resolver
publish {
defaults {
publications('ManualUpdaterPackage')
}
repository {
repoKey = project.version.endsWith('-SNAPSHOT') ? snapshotRepo : releaseRepo
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
}
}
task assembleManualUpdaterPackage (type: Zip){
dependsOn anotherTask
from (packageDir + "/")
include '**'
// archiveName "manualUpdaterPackage-${version}.zip"
destinationDir(file(manualUpdaterZipDir))
}
jenkinsfile snip:
withCredentials(
[
[
$class : 'UsernamePasswordMultiBinding',
credentialsId : 'validcreds',
passwordVariable: 'ORG_GRADLE_PROJECT_artifactory_password',
usernameVariable: 'ORG_GRADLE_PROJECT_artifactory_user'
]
]
) {
withEnv(
[
"ORG_GRADLE_PROJECT_buildInfo.build.number=${env.BUILD_NUMBER}",
"ORG_GRADLE_PROJECT_buildInfo.build.name=${artifactName}",
"ORG_GRADLE_PROJECT_buildInfo.build.url=${env.JOB_URL}"
]
) {
sh 'chmod +x gradlew'
sh "./gradlew --no-daemon clean artifactoryPublish"
}
}
https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins#WorkingWithPipelineJobsinJenkins-GradleBuildswithArtifactory
Eventually my coworker recommended looking into the Artifactory Pipeline Gradle plugin instead. It is very nice to work with and we've had much quicker success with it.

Cobertura code coverage report for jenkins pipeline jobs

I'm using the pipeline plugin for jenkins and I'd like to generate code coverage report for each run and display it along with the pipeline ui. Is there a plugin I can use to do that(e.g. Cobertura but it doesn't seem to be supported by pipeline)?
There is a way to add a pipeline step to publish your coverage report but it doesn't show under the BlueOcean interface. It will show fine in the normal UI.
pipeline {
agent any
stages {
...
}
post {
always {
junit '**/nosetests.xml'
step([$class: 'CoberturaPublisher', autoUpdateHealth: false, autoUpdateStability: false, coberturaReportFile: '**/coverage.xml', failUnhealthy: false, failUnstable: false, maxNumberOfBuilds: 0, onlyStable: false, sourceEncoding: 'ASCII', zoomCoverageChart: false])
}
}
}
Note that one of the parameters to the Cobertura plugin is the XML that it will use ('**/coverage.xml' in the example).
If you are using python, you will want to use something like:
nosetests --with-coverage --cover-xml --cover-package=pkg1,pkg2 --with-xunit test
Nowadays you can also use the cobertura command directly in a Jenkinsfile
stage ("Extract test results") {
cobertura coberturaReportFile: 'path-to/coverage.xml'
}
source: https://issues.jenkins-ci.org/browse/JENKINS-30700
The answer from hwjp is correct, however there are extra parameters that you can add to the command that are not easy to find.
Once you have installed the Cobertura plugin, you can find the cobertura step options in
Job Dashboard Page -> Pipeline Syntax -> Steps Reference
There's also a snippet generator which is really useful to get started at
Job Dashboard Page -> Pipeline Syntax
example command:
cobertura coberturaReportFile: 'coverage.xml', enableNewApi: true, lineCoverageTargets: '80, 60, 70'
enableNewApi is a good one to set to true, as the new API is much prettier :D
setting coverage targets will automatically fail the job if the code coverage is too low
Generate report using command line cobertura-report in specified directory and attach results as artifacts.
cobertura-report [--datafile file] --destination dir [--format
html|xml] [--encoding encoding] directory [--basedir dir]

Karma junitReporter.outputFile is empty

I'm configuring Karma to work with Jenkins CI as described here.
My junitReporter.outputFile, test-results.xml, is always empty.
Per the docs (linked above) Please note the test-results.xml files will be written to subdirectories named after the browsers the tests were run in inside the present working directory (and you will need to tell Jenkins where to find them).
I'm using PhantomJS to run my tests. I do not see any subdirectories named after PhantomJS.
Any ideas?
I ended up adding karma-junit-reporter to plugins in my karma.conf.js file and everything started working, like so:
// Which plugins to enable
plugins: [
"karma-phantomjs-launcher",
"karma-jasmine",
"karma-junit-reporter"
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
reporters: ['progress', 'junit'],
// the default configuration
junitReporter: {
outputDir: 'test', // results will be saved as $outputDir/$browserName.xml
outputFile: 'test-results.xml', // if included, results will be saved as $outputDir/$browserName/$outputFile
suite: '', // suite will become the package name attribute in xml testsuite element
useBrowserName: true // add browser name to report and classes names
},

Getting version info and build data from grails war file

In my application the user has the option to upload a war file to update the software.
I want to get some version information from the war file, before I deploy it to my server. How can I do this?
This information would be useful for me:
def jversion=[
"buildDate": grailsApplication.metadata["build.date"],
"version": grailsApplication.metadata["app.version"],
"branch": grailsApplication.metadata["GIT_BRANCH"],
"buildNumber": grailsApplication.metadata["build.number"],
"gitCommit": grailsApplication.metadata["GIT_COMMIT"]
]
What information can I get from the war file and how?
Best regards,
Peter
For this purpose you can add a script to the grails application that adds this information to a file whenever the user builds the war. Create a new script file under ./scripts in grails app with name _Events.groovy. Here you can hook into different grails events that gets triggered when an app starts or war gets built.
You can use eventCreateWarStart event to log the information whenever war gets built. Below is some sample code that can help you get started. It fetches the current branch name and commit id from local git and stores the data to a file named application.properties.
eventCreateWarStart = { warName, stagingDir ->
addBuildInfo("${stagingDir}/application.properties")
}
private void addBuildInfo(String propertyFile) {
def jVersion = [
"appName" : grailsApp.metadata['app.name'],
"version" : grailsApp.metadata["app.version"],
"buildDate" : new Date(),
"branch" : getBranch().trim(),
"Commit" : getRevision().trim(),
"buildNumber": System.getProperty("build.number", "CUSTOM"),
]
File file = new File(propertyFile)
file.text = ""
jVersion.each {
key, value ->
file.text += "${key}:\t${value}\n"
}
}
def getBranch() {
Process process = "git rev-parse --abbrev-ref HEAD".execute()
process.waitFor()
return process.text ?: 'UNKNOWN'
}
def getRevision() {
Process process = "git log --oneline --no-abbrev-commit -1".execute()
process.waitFor()
return process.text ?: 'UNKNOWN'
}
There is a grails plugin also that claims to fetch build properties from Hudson/Jenkins, if they are being used for building the war.
Grails 3.0.9, in GSP, you can get info from META-INF file. Try these
${grails.util.Metadata.current.getApplicationVersion()}
${grails.util.Metadata.current.getEnvironment()}
${grails.util.Metadata.current.getApplicationName()}
But i don't know how to get build date info.
For grails 3 you can use buildProperties task to add any custom information to war such as build date, verion info, git revision etc.
buildProperties {
inputs.property("info.app.build.date", new Date().format('yyyy-MM-dd HH:mm:ss'))
}
See this article for how to do the same http://nimavat.me/blog/grails3-add-custom-build-info-to-war

Resources