超薄框架和代码覆盖

时间:2014-09-19 21:02:14

标签: php xdebug

我正在尝试使用xdebug来计算苗条应用程序的代码覆盖率。结果似乎是错误的,因为它告诉我路由处理程序中的所有代码都没有执行(我做了一些请求......)

<?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();

我使用以下方式运行服务器:

php -S localhost:8080 -t . test.php

然后执行两个请求:

curl http://localhost:8080/server.php/data
curl http://localhost:8080/server.php/STOP > result.html

result.html中的覆盖范围输出告诉我:

'.../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

第6行应该是int 1,因为它已被执行。我错过了什么?

1 个答案:

答案 0 :(得分:0)

问题显然是输出中显示的覆盖范围仅涵盖第二个请求,因为每个请求都会运行整个PHP脚本。

简单的解决方案包括使用另外两个答案:enter link description hereenter link description here使用php-code-coverage https://github.com/sebastianbergmann/php-code-coverage生成覆盖率报告,然后在外部脚本中合并所有报告。

服务器现在如下:

<?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();

合并脚本是:

#!/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";

合并脚本还会将vendor中的所有内容放入黑名单。