Code Coverage on Google Cloud Build

When you set up a CI/CD pipeline for your project, you probably want to calculate the code coverage and send it to a third party service like Codecov.

I’m going to show you how to set this up on Google Cloud Build.

Problem

The codecov tool must be run from within a git repository by default, otherwise it will throw an error:

fatal: Not a git repository

The reason is that codecov is designed to report coverage for a specific branch and commit of your code.

Because the Google Cloud Build GitHub App doesn’t re-create a full git repository, we need a workaround.

Solution

The solution is to manually pass the branch and commit to the tool:

$ codecov --token=X --disable=detect --commit=FOO --branch=BAR

Cloud Build makes this kind of information available to the build through built-in substitutions.

cloudbuild.yaml

steps: 
- name: 'gcr.io/cloud-builders/npm'
args: ['install']
- name: 'gcr.io/cloud-builders/npm'  
args: ['run', 'ci']
- name: 'gcr.io/cloud-builders/npm'  
args:
[
'run',
'codecov',
'--',
'--disable=detect',
'--commit=$COMMIT_SHA',
'--branch=$BRANCH_NAME'
]

package.json

{
"devDependencies": {
"codecov": "3.1.0",
"mocha": "5.2.0",
"nyc": "13.1.0"
},
  "scripts": {
"ci": "NODE_ENV=test node_modules/.bin/nyc node_modules/.bin/mocha --reporter spec 'server/test/**/*test.js' && node_modules/.bin/nyc report --reporter=text-lcov > coverage.lcov",
"codecov": "node_modules/.bin/codecov --token=X"
}
}

Conclusion

You can bypass the codecov tool detection, and manually pass the commit and branch of the current CI run.

The Cloud Build configuration is easy to read: it installs the dependencies, runs the tests, then uploads the results to Codecov.

In my next post, I will show you how you can cache the first step for better performance.