I am trying to use xdebug to compute code coverage of a slim application. The results seems erroneous, as it tells me that all code within routes handlers is not executed (and i did some requests...)
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
$app->get('/data', function () use ($app) {
echo "data";
});
$app->get('/STOP', function () use ($app) {
$data = xdebug_get_code_coverage();
var_dump($data);
});
$app->run();
I run the server using:
php -S localhost:8080 -t . test.php
And then perform two requests:
curl http://localhost:8080/server.php/data
curl http://localhost:8080/server.php/STOP > result.html
The coverage output in result.html
tells me:
'.../test.php' =>
array (size=11)
0 => int 1
5 => int 1
6 => int -1
7 => int 1
8 => int 1
9 => int 1
10 => int -1
11 => int 1
12 => int 1
473 => int 1
1267 => int 1
Line 6 should be int 1
, as it has been executed. What am i missing?
The problem is obviously that the coverage shown in output only covers the second request, as the whole PHP script is run at every request.
The easy solution consists in using two other answers : enter link description here and enter link description here to generate coverage reports using php-code-coverage https://github.com/sebastianbergmann/php-code-coverage , and then merge all reports in an external script.
The server is now as below:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
// https://stackoverflow.com/questions/19821082/collate-several-xdebug-coverage-results-into-one-report
$coverage = new PHP_CodeCoverage;
$coverage->start('Site coverage');
function shutdown() {
global $coverage;
$coverage->stop();
$cov = serialize($coverage); //serialize object to disk
file_put_contents('coverage/data.' . date('U') . '.cov', $cov);
}
register_shutdown_function('shutdown');
$app->get('/data', function () use ($app) {
echo "data";
});
$app->run();
And the merge script is:
#!/usr/bin/env php
<?php
// https://stackoverflow.com/questions/10167775/aggregating-code-coverage-from-several-executions-of-phpunit
require 'vendor/autoload.php';
$coverage = new PHP_CodeCoverage;
$blacklist = array();
exec("find vendor -name '*'", $blacklist);
$coverage->filter()->addFilesToBlacklist($blacklist);
foreach(glob('coverage/*.cov') as $filename) {
$cov = unserialize(file_get_contents($filename));
$coverage->merge($cov);
}
print "\nGenerating code coverage report in HTML format ...";
$writer = new PHP_CodeCoverage_Report_HTML(35, 70);
$writer->process($coverage, 'coverage');
print " done\n";
print "See coverage/index.html\n";
The merge script also puts everything in vendor
into the blacklist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.