Git Product home page Git Product logo

istanbul-cobertura-badger's Introduction

istanbul-cobertura-badger

Travis npm version Codacy Badge Code Climate Dependency Status devDependency Status Coverage Status License

Creates a coverage badge by reading the Cobertura XML coverage report from node-istanbul reports using https://github.com/badges/shields.

NPM

Requirements

I started to work with Node a few months ago, and I recently stumbled upon many different badges on GitHub pages, including code coverage. I posted a question on Stack Overflow about it:

http://stackoverflow.com/questions/26028024/how-to-make-a-gulp-code-coverage-badge

  • I want to be able to generate the coverage report after code coverage runs by any Node.js build system like Gulp or Grunt, and be able to publish the badge on the README.md file through a Jenkins link;
  • The badge displays appropriate colors for the badge.
  • Green: >= 80% overall coverage
  • Yellow: 65% <= overall coverage < 80%
  • Red: < 65% overall coverage

The idea is to serve in the Node.js README for internal use in a GitHub enterprise machine along with Jenkins.

Installation

npm install --save-dev istanbul-cobertura-badger

Setup

The following parameters are used:

  • Cobertura file report: The XML-based cobertura file generated by Istanbul "cobertura" report.
  • Destination Path: The path to the destination directory where the badge image will be created.
  • Callback: The callback function after the file has been downloaded.
  • Optional Thresholds: Adjust the thresholds if needed.

Cobertura Xml Report

You can generate the cobertura XML report by adding a new report to the istanbul command as follows:

  --report cobertura

Take a look at this project's package.json for details.

The option to change in the code is as follows:

  // Setting the default coverage file generated by istanbul cobertura report.
  opts.istanbulReportFile = opts.istanbulReportFile || "./coverage/cobertura-coverage.xml";

Destination Dir

The destination directory will, by default, be the one from istanbul $APP/coverage.

  // The default location for the destination being the coverage directory from istanbul.
  opts.destinationDir = opts.destinationDir || "./coverage/";

Note that the default directory will be used as coverage/cobertura-coverage.xml.

Adjusting Thresholds

The overall threshold is computed by using the line rate, branch rate and function rate. That's the final value that defines coverage result. You can adjust the thresholds to properly generate the badges with appropriate colors.

  // The thresholds to be used to give colors to the badge.
  opts.thresholds = {
    excellent: 90,
    good: 65
  };
  • Green: coverage result >= opts.thresholds.excellent;
  • Yellow: coverage result >= opts.thresholds.good;
  • Red: coverage result < opts.thresholds.good.

Upon calling the callback function, the file cobertura.svg will be available in the destination path.

Examples

var coberturaBadger = require('istanbul-cobertura-badger');

// Use the fixture that's without problems
var opts = {
  //badgeFileName: "cobertura", // No extension, Defaults to "coverage"
  destinationDir: __dirname, // REQUIRED PARAMETER!
  istanbulReportFile: path.resolve(__dirname, "coverage", "cobertura-coverage.xml"),
  thresholds: {
    // overall percent >= excellent, green badge
    excellent: 90,
    // overall percent < excellent and >= good, yellow badge
    good: 65
    // overall percent < good, red badge
  }
};

// Load the badge for the report$
badger(opts, function parsingResults(err, badgeStatus) {
  if (err) {
    console.log("An error occurred: " + err.message);
  }
  console.log("Badge successfully generated at " + badgeStatus.badgeFile.file);
  console.log(badgeStatus);
});

An example of a successful badge creation is as follows:

{ overallPercent: 66,
  functionRate: 0.7368421052631579,
  lineRate: 0.8034,
  branchRate: 0.47369999999999995,
  url: 'http://img.shields.io/badge/coverage-66%-yellow.svg',
  badgeFile: { 
    method: 'GET',
    code: 200,
    file: '/home/mdesales/dev/github/intuit/istanbul-cobertura-badger/test/coverage.svg' 
  }
}

Gulp Build

gulp.task('test', function() {
  gulp.src('src/**/*.js')
    .pipe(istanbul()) // coverying files
    .on('finish', function () {
      gulp.src(['test/*.js'])
        .pipe(mocha({reporter: 'spec'})) // different reporters at http://mochajs.org/#reporters
        .pipe(istanbul.writeReports({
          reporters: ['cobertura', 'text-summary', 'html'], // https://www.npmjs.org/package/gulp-istanbul#reporters
          reportOpts: { dir: './docs/tests' }
        }))
        .on('end', function() {

          var opts = {
            destinationDir: path.resolve(__dirname, "docs", "tests"),
            istanbulReportFile: path.resolve(__dirname, "docs", "tests", "cobertura-coverage.xml"),
          }
          coverageBadger(opts, function(err, results) {
            if (err) {
              console.log("An error occurred while generating the coverage badge" + err.message);
              process.exit(-1);
            }
            console.log("Badge generated successfully: " + results)
            process.exit(0);
           });

        });
    });
});

CLI

You can now use the CLI to create the badge for ANY XML Cobertura report created from Istanbul or Java applications.

CLI Options

The CLI prints the following help:

$ istanbul-cobertura-badger 

  Usage: cli [options]

  Generates a badge for a given Cobertura XML report

  Options:

    -h, --help                          output usage information
    -V, --version                       output the version number
    -f, --defaults                      Use the default values for all the input.
    -e, --excellentThreshold <n>       The threshold for green badges, where coverage >= -e
    -g, --goodThreshold <n>            The threshold for yellow badges, where -g <= coverage < -e  
    -b, --badgeFileName <badge>         The badge file name that will be saved.
    -r, --reportFile <report>           The istanbul cobertura XML file path.
    -d, --destinationDir <destination>  The directory where 'coverage.svg' will be generated at.
    -v, --verbose                       Prints the metadata for the command

  Examples:

    $ istanbul-cobertura-badger -e 90 -g 65 -r coverage/cobertura.xml -d coverage/
      * Green: coverage >= 90
      * Yellow: 65 <= coverage < 90
      * Red: coverage < 65
      * Created at the coverage directory from the given report.

    $ istanbul-cobertura-badger -e 80 -d /tmp/build
      * Green: coverage >= 80
      * Yellow: 65 <= coverage < 80
      * Red: coverage < 65

CLI Default Input

Run the CLI using the default values defined above. Here's the example of running against this project.

$ istanbul-cobertura-badger -f -v
{ overallPercent: 91,
  functionRate: 1,
  lineRate: 0.9309999999999999,
  branchRate: 0.8167,
  url: 'http://img.shields.io/badge/coverage-91%-brightgreen.svg',
  badgeFile: 
   { downloaded: true,
     filePath: '/home/mdesales/dev/github/intuit/istanbul-cobertura-badger/coverage/coverage.svg',
     size: 730 },
  color: 'brightgreen' }
Badge created at /home/mdesales/dev/github/intuit/istanbul-cobertura-badger/coverage/coverage.svg

CLI Simple Output

Just use the simple command with some options.

$ istanbul-cobertura-badger -e 85 -g 70 -r test/fixture/istanbul-report.xml -d /tmp/
Badge created at /tmp/coverage.svg

CLI Verbose Output

The overall information collected is also presented when using the verbose option.

$ istanbul-cobertura-badger -e 85 -g 70 -r test/fixture/istanbul-report.xml -d /tmp/ -v
{ overallPercent: 66,
  functionRate: 0.7368421052631579,
  lineRate: 0.8034,
  branchRate: 0.47369999999999995,
  url: 'http://img.shields.io/badge/coverage-66%-red.svg',
  badgeFile: { downloaded: true, filePath: '/tmp/coverage.svg', size: 733 },
  color: 'red' }
Badge created at /tmp/coverage.svg

CLI Version

You can print the current version of the project by using the -V option. It uses the package.json#version as the value.

$ istanbul-cobertura-badger -V
1.0.0

Contributing

We use the GitFlow branching model http://nvie.com/posts/a-successful-git-branching-model/.

  1. Fork it
  2. Create your feature branch (git checkout -b feature/issue-444-Add-Rest-APIs origin/master --track)
  • Adding the Jira ticket ID helps communicating where this feature is coming from.
  1. Commit your changes (git commit -am 'Fix #444: Add support to REST-APIs')
  • Adding "fix #444" will trigger a link to the GitHub issue #444.
  1. Push to the branch (git push feature/issue-444-Add-Rest-APIS)
  2. Create new Pull Request as indicated by this page or your forked repo.

istanbul-cobertura-badger's People

Contributors

doublesharp avatar hutson avatar marcellodesales avatar mortonfox avatar olivierntk avatar piperchester avatar scottdelly avatar shime avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

istanbul-cobertura-badger's Issues

Display result option

Hi,

Thank you for this generator.
It would be nice to be able to set what kind of calculation we want no?

Today you have your own formula for coverage right?
It would be nice to set in the option something like:

var opts = {
    //Statements
    //Branches
    //Functions
    //Lines
    //istanbul-cobertura-badger => your own formula :)
    resultType: 'Statements'
};

Add function rate for a more accurate coverage result

The current implementation only uses the values from the branch and line rates. This leads to lower numbers of coverage. In addition to them, collect the function rate, which is total number of functions that had hits > 0.

Accept the thresholds as parameters

The thresholds are pre-defined at https://github.com/marcellodesales/istanbul-cobertura-badger/blob/master/index.js#L31

  • Provide refactoring to the API
  • Provide refactoring to the CLI

The behavior about the thresholds could be as follows:

Parser is broken for complex reports

The following report is broken for more complex reports... The parser must be generic to expect a single or multiple packages, classes or methods.

The problem is that the current parser was designed over the samples.

<?xml version="1.0" ?>
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
<coverage lines-valid="328"  lines-covered="255"  line-rate="0.7774"  branches-valid="58"  branches-covered="30"  branch-rate="0.5172"  timestamp="1444266082605" complexity="0" version="0.1">
<sources>
    <source>/home/mdesales/dev/github-intuit/servicesplatform-nodejs/sp-quality</source>
</sources>
<packages>
    <package name="sp-quality"  line-rate="0.6667000000000001"  branch-rate="1" >
    <classes>
        <class name="lint.js"  filename="lint.js"  line-rate="1"  branch-rate="1" >
        <methods>
        </methods>
        <lines>
            <line number="5"  hits="1"  branch="false" />
            <line number="10"  hits="1"  branch="false" />
        </lines>
        </class>
        <class name="test.js"  filename="test.js"  line-rate="0.6"  branch-rate="1" >
        <methods>
            <method name="(anonymous_1)"  hits="0"  signature="()V" >
                <lines><line number="8"  hits="0" /></lines>
            </method>
            <method name="(anonymous_2)"  hits="8"  signature="()V" >
                <lines><line number="15"  hits="8" /></lines>
            </method>
            <method name="(anonymous_3)"  hits="0"  signature="()V" >
                <lines><line number="22"  hits="0" /></lines>
            </method>
            <method name="(anonymous_4)"  hits="0"  signature="()V" >
                <lines><line number="29"  hits="0" /></lines>
            </method>
            <method name="(anonymous_5)"  hits="0"  signature="()V" >
                <lines><line number="37"  hits="0" /></lines>
            </method>
        </methods>
        <lines>
            <line number="8"  hits="1"  branch="false" />
            <line number="9"  hits="0"  branch="false" />
            <line number="15"  hits="1"  branch="false" />
            <line number="16"  hits="8"  branch="false" />
            <line number="22"  hits="1"  branch="false" />
            <line number="23"  hits="0"  branch="false" />
            <line number="29"  hits="1"  branch="false" />
            <line number="30"  hits="0"  branch="false" />

Allow custom badge text instead of coverage

It would be helpful to have an option to set the text on the left side of the badge shield to something other than coverage. This would be useful for projects that might have more than one badge generated for different test runs-e.g. unit, integration, acceptance, etc.

100% Unachiveable

Seems the percentage math is setup so that 100% can't be achieved.

In my particular case, I have a functionRate of 1, a lineRate of 1, and a branchRate of 1. However, the coverage percentage comes out to 99%.

var percent = (((functionRate + lineRate + branchRate) / 3) * 100).toFixed(0) - 1;

Percent not Encoded for shields.io Request

Hi, when making a request for a badge from shields.io, the percent inside the url is not url encoded. Example:

https://img.shields.io/badge/coverage-100%-brightgreen.svg?style=flat

This works:

https://img.shields.io/badge/coverage-100%25-brightgreen.svg?style=flat

I'm not sure what changed on shields.io but it is no longer accepting that request. I'm getting a 400 bad request with the first url.

This was the command I used:

$ istanbul-cobertura-badger -f -b badge -v
{ overallPercent: 100,
  functionRate: 1,
  lineRate: 1,
  branchRate: 1,
  url: 'https://img.shields.io/badge/coverage-100%-brightgreen.svg?style=flat',
  badgeFile:
   { downloaded: true,
     filePath: '/Users/x/Projects/fathom-template/coverage/badge.svg',
     size: 177 },
  color: 'brightgreen' }
Badge created at /Users/x/Projects/fathom-template/coverage/badge.svg
Done in 0.64s.

Any ideas?

Create a cli binary to support post test scripts on package.json

Using this as a CLI will make it simpler for the cases of running it without an API.

The posttest script, which runs only after a successful test execution, can be used to generate the badge. The client binary would be something like the following:

   "scripts": {
     "posttest": "node_modules/istanbul-cobertura-badger/bin/badger --reportDir ./cobertura"
   }

NaN badge returned if no methods in tested code

When the code doesn't contain any methods, the generated coverage report won't calculate the coverage for methods.
However, the functionRate is still being calculated and returning a NaN. Thus causing the overall rate to be NaN

Threshold are always NaN

No matter how I run the script I always get this:

 overallPercent: NaN,
  functionRate: NaN,
  lineRate: 0.8214,
  branchRate: 0.5,
  url: 'http://img.shields.io/badge/coverage-NaN%-red.svg',
  badgeFile:
   { downloaded: true,
     filePath: 'mypath/coverage.svg',
     size: 742 },
  color: 'red' }
Badge created at mypath/coverage.svg

I've tried:
istanbul-cobertura-badger -f -v global
node_modules/.bin/istanbul-cobertura-badger -f -v local
istanbul-cobertura-badger -e 80 -g 60 -v
istanbul-cobertura-badger -f -r mypath/cobertura.xml -v

I've checked also the cobertura.xml and looks fine.

Any idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.