Jenkins基础:使用NPM构建前端应用9:结合SonarQube显示测试覆盖率

在前面的文章中我们介绍了如何将Karma、Jasmine的前端测试集成到Jenkins的流水线中,在这篇文章中将继续介绍如何将前端单元测试覆盖率的信息正确地显示到SonarQube之上。

事前准备

SonarQube环境

构建SonarQube环境,可参看如下内容:

  • https://liumiaocn.blog.csdn.net/article/details/56673905

注:此节开始的示例SonarQube版本开始使用LTS 7.9.1,服务端口为9001

Dockerfile

~ # cat /tmp/Dockerfile 
FROM nginx:latest

ADD demo/dist/* /usr/share/nginx/html
~ # 

Karma配置文件

将Karma的配置文件做如下修改

/data/jenkins/workspace/angular-pipeline-job/demo # cat karma.conf.js
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, './coverage/demo'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      }
    },
    singleRun: true,
    restartOnFileChange: true
  });
};
/data/jenkins/workspace/angular-pipeline-job/demo # 

安装Chromium,可参看:

  • https://blog.csdn.net/liumiaocn/article/details/102903761

基础知识

如果对于NodeJS的插件使用或者在Jenkins的Jenkinsfile中使用npm的基本方法不熟悉的开发者可以先行查看如下文章。

Jenkinsfile

node {
   stage('Prepare Node and NPM') { // confirm nodejs plugin and setting
    env.NODEJS_HOME = "${tool 'nodejs-10.15.3'}"
	env.PATH="${env.NODEJS_HOME}/bin:${env.PATH}"
	sh 'npm --version'
   }
   stage('Prepare Angular CLI') { // install global angular cli
    sh 'npm -g install @angular/cli'
    sh 'ng --version'
   }
   stage('Prepare Angular Project') { // prepare angular demo app
    sh 'if [ ! -d demo ]; then ng new demo --style less; fi'
   }
   stage('Build Angular Project') { // build angular demo app
    sh 'cd demo && npm install && npm run build'
   }
   stage('Build Angular demo image') { // build image and push to registry
    sh 'cp /tmp/Dockerfile .'
    docker.withRegistry('http://192.168.31.242:5000') {
      def angular_img = docker.build("angulardemo:${env.BUILD_ID}")
      angular_img.push()
    }
   }
   stage('Deploy Angular image') { // docker run angular image
    docker.image("angulardemo:${env.BUILD_ID}").run('-p 8888:80')
   }
   stage('Jasmine Unit Test') { // Unit Test
    sh 'export CHROME_BIN=/usr/bin/chromium-browser && cd demo && ng test --code-coverage'
   }
   stage('Sonar-Scanner Angular Demo App') { // sonar-scanner
    sh 'cd demo && /usr/local/share/sonar/bin/sonar-scanner -Dsonar.projectKey=demo -Dsonar.sources=src -Dsonar.host.url=http://192.168.31.242:9001 -Dsonar.login=admin -Dsonar.password=admin -Dsonar.typescript.lcov.reportPaths=coverage/demo/lcov.info -Dsonar.exclusions=src/**.spec.ts,src/app/app-routing.module.ts,src/environments/environment*.ts,src/main.ts '
   }
}

代码说明:
angular是通过cli来创建应用程序脚手架的,在Prepare Angular Project的stage中通过使用ng new demo创建了demo的angular应用。而在后续的stage中则通过npm install安装相关的依赖,通过npm run build则生成了结果的dist目录与文件,然后通过docker.withRegistry设定私库地址,通过docker.build构建,通过push方法进行推送,然后使用image的run方法运行容器,通过ng test执行测试用例并生成lcov的测试率覆盖文件,而通过内置的sonar-scanner来进行代码的质量扫描,通过传入lcov的测试覆盖率信息,并设定sonar的除外文件,从而正确地显示覆盖率信息。

结果确认

  • 执行日志确认
    执行日志如下所示:
Started by user root
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /data/jenkins/workspace/angular-pipeline-job
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Prepare Node and NPM)
[Pipeline] tool
[Pipeline] sh
+ npm --version
6.4.1
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Prepare Angular CLI)
[Pipeline] sh
+ npm -g install @angular/cli
...省略
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Sonar-Scanner Angular Demo App)
[Pipeline] sh
+ cd demo
+ /usr/local/share/sonar/bin/sonar-scanner '-Dsonar.projectKey=demo' '-Dsonar.sources=src' '-Dsonar.host.url=http://192.168.31.242:9001' '-Dsonar.login=admin' '-Dsonar.password=admin' '-Dsonar.typescript.lcov.reportPaths=coverage/demo/lcov.info' '-Dsonar.exclusions=src/**.spec.ts,src/app/app-routing.module.ts,src/environments/environment*.ts,src/main.ts'
INFO: Scanner configuration file: /usr/local/share/sonar/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarQube Scanner 3.2.0.1227
INFO: Java 1.8.0_212 IcedTea (64-bit)
INFO: Linux 4.9.87-linuxkit-aufs amd64
INFO: User cache: /root/.sonar/cache
INFO: SonarQube server 7.9.1
INFO: Default locale: "en_US", source code encoding: "UTF-8" (analysis is platform dependent)
WARN: SonarScanner will require Java 11+ to run starting in SonarQube 8.x
INFO: Load global settings
INFO: Load global settings (done) | time=596ms
INFO: Server id: 46AF5D23-AW4QVqQKMR98oZUMGunZ
INFO: User cache: /root/.sonar/cache
INFO: Load/download plugins
INFO: Load plugins index
INFO: Load plugins index (done) | time=472ms
INFO: Load/download plugins (done) | time=509ms
INFO: Process project properties
INFO: Project key: demo
INFO: Base dir: /data/jenkins/workspace/angular-pipeline-job/demo
INFO: Working dir: /data/jenkins/workspace/angular-pipeline-job/demo/.scannerwork
INFO: Load project settings for component key: 'demo'
INFO: Load project settings for component key: 'demo' (done) | time=415ms
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=500ms
INFO: Load active rules
INFO: Load active rules (done) | time=1023ms
WARN: SCM provider autodetection failed. Please use "sonar.scm.provider" to define SCM of your project, or disable the SCM Sensor in the project settings.
INFO: Indexing files...
INFO: Project configuration:
INFO:   Excluded sources: src/**.spec.ts, src/app/app-routing.module.ts, src/environments/environment*.ts, src/main.ts
INFO: 9 files indexed
INFO: 0 files ignored because of inclusion/exclusion patterns
INFO: Quality profile for ts: Sonar way
INFO: ------------- Run sensors on module demo
INFO: Load metrics repository
INFO: Load metrics repository (done) | time=385ms
INFO: Sensor SonarTS [typescript]
INFO: Load project repositories
INFO: Load project repositories (done) | time=425ms
INFO: Analyzing 4 typescript file(s) with the following configuration file /data/jenkins/workspace/angular-pipeline-job/demo/tsconfig.json
INFO: 4 files analyzed out of 4
INFO: Sensor SonarTS [typescript] (done) | time=15803ms
INFO: Sensor SonarTS Coverage [typescript]
INFO: Analysing [/data/jenkins/workspace/angular-pipeline-job/demo/coverage/demo/lcov.info]
INFO: Sensor SonarTS Coverage [typescript] (done) | time=31ms
INFO: ------------- Run sensors on project
INFO: Sensor Zero Coverage Sensor
INFO: Sensor Zero Coverage Sensor (done) | time=6ms
INFO: No SCM system was detected. You can use the 'sonar.scm.provider' property to explicitly specify it.
INFO: 2 files had no CPD blocks
INFO: Calculating CPD for 2 files
INFO: CPD calculation finished
INFO: Analysis report generated in 145ms, dir size=16 KB
INFO: Analysis report compressed in 1037ms, zip size=8 KB
INFO: Analysis report uploaded in 448ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://192.168.31.242:9001/dashboard?id=demo
INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
INFO: More about the report processing at http://192.168.31.242:9001/api/ce/task?id=AW42lmv5zxaMqkyn8AZx
INFO: Analysis total time: 26.080 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 29.437s
INFO: Final Memory: 9M/73M
INFO: ------------------------------------------------------------------------
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
  • 构建结果
    在blueocean上也能实时地确认到构建的输出信息
    在这里插入图片描述
  • 登陆SonarQube确认扫描结果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
淼叔 CSDN认证博客专家 神经网络 TensorFlow NLP
资深架构师,PMP、OCP、CSM、HPE University讲师,EXIN DevOps Professional与DevOps Master认证讲师,曾担任HPE GD China DevOps & Agile Leader,帮助企业级客户提供DevOps咨询培训以及实施指导。熟悉通信和金融领域,有超过十年金融外汇行业的架构设计、开发、维护经验,在十几年的IT从业生涯中拥有了软件开发设计领域接近全生命周期的经验和知识积累,著有企业级DevOps技术与工具实战。
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页