Fact: Numbers matter to some people.
We can easily visualize test reports of a build With Cobertura plugin in Jenkins. However, we need to have the report generated in the first place.
To do so, we use the multistage feature in our dockerfile to add a stage that will do that for us.
Multi Stage Dockefile
Here is an example of a Dotnet project where the Dockerfile has a Test report generation stage. We label it to create a container from this stage directly after build, and then retrieve the test coverage report using docker cp.
...
FROM build AS test
WORKDIR /src
# install the report generator tool
RUN dotnet tool install --global coverlet.console
#Adding Test Projects
LABEL test=true
RUN dotnet add /src/Service.Tests/**.csproj package coverlet.msbuild --version 2.5.1
RUN dotnet test /src/ /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput='/src/coverage/'
...
Now the report is generated inside our image, to retrieve it, we need to create a container and use the docker cp command on this container to make it available for the Jenkins host. Thus, available for the Cobertura plugin to generate the report in the User Interface.
Jenkinsfile
To do so, we add these lines to our Test Report step in the Jenkinsfile.
pipeline {
agent any
environment {
...
}
stages {
stage('Build') {
steps {
withDockerRegistry([credentialsId: 'ACR_CRED', url: 'https://mindevcr.azurecr.io']) {
sh 'docker build -f Dockerfile --force-rm -t $IMAGE:latest .'
}
}
}
stage('Test Report') {
steps {
script {
env.CI_CNTR_NAME= JOB_NAME.replaceAll("[^a-zA-Z0-9 ]+","")
}
sh 'docker create --name testcontainer$CI_CNTR_NAME$BUILD_NUMBER $(docker images --filter "label=test=true" -q | head -1)'
sh 'docker cp testcontainer$CI_CNTR_NAME$BUILD_NUMBER:/src/coverage/Cobertura.xml cobertura.xml'
sh 'docker rm testcontainer$CI_CNTR_NAME$BUILD_NUMBER'
cobertura coberturaReportFile: 'cobertura.xml'
}
}
...
}
As of today, we cannot “docker cp” on images directly, that is why we create an intermediate container and remove it once the report is on the Jenkins VM.
Results
If all works well, cobertura commands should succeed.