Skip to content

Commit

Permalink
Merge pull request #9 from nikoheikkila/refactor
Browse files Browse the repository at this point in the history
Refactor and optimize code
  • Loading branch information
richardregeer authored Oct 14, 2019
2 parents a9b0c07 + aeb8f51 commit 9618fa7
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 34 deletions.
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ This script can be used in your continuous deployment environment or for example

# Installation
The script can be installed using composer. Add this repository as a dependency to the composer.json file.

```bash
composer require --dev rregeer/phpunit-coverage-check
composer install
```

# Usage
Expand All @@ -17,17 +17,19 @@ The script has requires 2 parameters that are mandatory to return the code cover
1. The location of the clover xml file, that's generated by phpunit.
2. The coverage threshold that is acceptable. Min = 1, Max = 100

Generate the clover xml by using phpunit and run the coverage check script:
Generate the `clover.xml` file by using phpunit and run the coverage check script:
Run the script:

```bash
vendor/bin/phpunit --coverage-clover clover.xml
vendor/bin/coverage-check clover.xml 80
vendor/bin/coverage-check clover.xml 80 only-percentage
vendor/bin/coverage-check clover.xml 80 --only-percentage
```

With the `only-percentage` enabled, the CLI command will only return the resulting coverage percentage.
With the `--only-percentage` enabled, the CLI command will only return the resulting coverage percentage.

It's also possible to add the coverage report generation to the phpunit.xml.dist add to following line to the xml file:

```xml
<logging>
<log type="coverage-clover" target="clover.xml"/>
Expand Down
19 changes: 19 additions & 0 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

87 changes: 57 additions & 30 deletions coverage-check.php
Original file line number Diff line number Diff line change
@@ -1,26 +1,46 @@
<?php

declare(strict_types=1);

// Inspired by: https://ocramius.github.io/blog/automated-code-coverage-check-for-github-pull-requests-with-travis/
if (!isset($argv[1]) || !file_exists($argv[1])) {
echo 'Invalid input file provided' . PHP_EOL;
exit(1);

const XPATH_METRICS = '//metrics';
const STATUS_OK = 0;
const STATUS_ERROR = 1;

function formatCoverage(float $number): string
{
return sprintf('%0.2f %%', $number);
}

if (!isset($argv[2])) {
echo 'An integer checked percentage must be given as second parameter'. PHP_EOL;
exit(1);
function loadMetrics(string $file): array
{
$xml = new SimpleXMLElement(file_get_contents($file));

return $xml->xpath(XPATH_METRICS);
}

$onlyEchoPercentage = false;
function printStatus(string $msg, int $exitCode = STATUS_OK)
{
echo $msg.PHP_EOL;
exit($exitCode);
}

if (isset($argv[3]) && $argv[3] === 'only-percentage') {
$onlyEchoPercentage = true;
if (! isset($argv[1]) || ! file_exists($argv[1])) {
printStatus("Invalid input file {$argv[1]} provided.", STATUS_ERROR);
}

$inputFile = $argv[1];
$percentage = min(100, max(0, (float)$argv[2]));
if (! isset($argv[2])) {
printStatus(
'An integer checked percentage must be given as second parameter.',
STATUS_ERROR
);
}

$onlyEchoPercentage = isset($argv[3]) && $argv[3] === '--only-percentage';

$xml = new SimpleXMLElement(file_get_contents($inputFile));
$metrics = $xml->xpath('//metrics');
$inputFile = $argv[1];
$percentage = min(100, max(0, (float) $argv[2]));

$elements = 0;
$coveredElements = 0;
Expand All @@ -29,31 +49,38 @@
$methods = 0;
$coveredmethods = 0;

foreach ($metrics as $metric) {
$elements += (int)$metric['elements'];
$coveredElements += (int)$metric['coveredelements'];
$statements += (int)$metric['statements'];
$coveredstatements += (int)$metric['coveredstatements'];
$methods += (int)$metric['methods'];
$coveredmethods += (int)$metric['coveredmethods'];
foreach (loadMetrics($inputFile) as $metric) {
$elements += (int) $metric['elements'];
$coveredElements += (int) $metric['coveredelements'];
$statements += (int) $metric['statements'];
$coveredstatements += (int) $metric['coveredstatements'];
$methods += (int) $metric['methods'];
$coveredmethods += (int) $metric['coveredmethods'];
}

// See calculation: https://confluence.atlassian.com/pages/viewpage.action?pageId=79986990
$TPC = ($coveredstatements + $coveredmethods + $coveredElements) / ($statements + $methods + $elements) * 100;
$coveredMetrics = $coveredstatements + $coveredmethods + $coveredElements;
$totalMetrics = $statements + $methods + $elements;

if ($totalMetrics === 0) {
printStatus('Insufficient data for calculation. Please add more code.', STATUS_ERROR);
}

$totalPercentageCoverage = $coveredMetrics / $totalMetrics * 100;

if ($TPC < $percentage && ! $onlyEchoPercentage) {
echo 'Total code coverage is ' . sprintf('%0.2f', $TPC) . '%, which is below the accepted ' . $percentage . '%' . PHP_EOL;
exit(1);
if ($totalPercentageCoverage < $percentage && ! $onlyEchoPercentage) {
printStatus(
'Total code coverage is '.formatCoverage($totalPercentageCoverage).' which is below the accepted '.$percentage.'%',
STATUS_ERROR
);
}

if ($TPC < $percentage && $onlyEchoPercentage) {
echo sprintf('%0.2f', $TPC) . PHP_EOL;
exit(1);
if ($totalPercentageCoverage < $percentage && $onlyEchoPercentage) {
printStatus(formatCoverage($totalPercentageCoverage), STATUS_ERROR);
}

if ($onlyEchoPercentage) {
echo sprintf('%0.2f', $TPC) . PHP_EOL;
exit(0);
printStatus(formatCoverage($totalPercentageCoverage));
}

echo 'Total code coverage is ' . sprintf('%0.2f', $TPC) . '% - OK!' . PHP_EOL;
printStatus('Total code coverage is '.formatCoverage($totalPercentageCoverage).' OK!');
20 changes: 20 additions & 0 deletions test/empty.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="1002">
<project timestamp="1002">
<package name="Example">
<file name="/tmp/Example/String.php">
<class name="Example\String" namespace="Example">
<metrics complexity="15" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
</class>
<metrics loc="1" ncloc="1" classes="1" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
</file>
<file name="/tmp/Example/StringList.php">
<class name="Example\StringList" namespace="Example">
<metrics complexity="0" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
</class>
<metrics loc="1" ncloc="1" classes="1" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
</file>
</package>
<metrics files="1" loc="0" ncloc="0" classes="1" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
</project>
</coverage>
7 changes: 7 additions & 0 deletions test/run
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,12 @@ bin/coverage-check test/clover.xml 0
bin/coverage-check test/clover.xml 90

# Expect fail
! bin/coverage-check test/empty.xml 10
! bin/coverage-check test/clover.xml 95
! bin/coverage-check test/clover.xml 100

# Only percentage
expected="90.32 %"
actual=$(bin/coverage-check test/clover.xml 90 --only-percentage)

[[ "$expected" == "$actual" ]] || (echo "ERROR: Expected coverage $expected, got $actual" && exit 1)

0 comments on commit 9618fa7

Please sign in to comment.