如何从 xdebug 输出生成 PHP 代码覆盖率报告

How to generate PHP Code Coverage Reports from xdebug output

我正在尝试为 运行ning PHP 应用程序生成 HTML 代码覆盖率报告。我的目标是使用 XDebug 分析应用程序,同时我 运行 我的功能测试以确定我的功能测试套件的代码覆盖率。

我可以通过 phpunit 测量我的单元测试的代码覆盖率(它使用 php-code-coverage API 来单独分析每个单元测试,然后聚合它到代码覆盖率报告中)。因为这些工具是建立在 xdebug 之上的,所以我希望有一种方法可以从 XDebug 分析器中获取输出文件并生成 HTML 报告。

这是我目前的情况:

我可以通过在 php.ini 中添加以下配置来生成 cachegrind.out 文件:

xdebug.profiler_enable_trigger=1
xdebug.profiler_output_dir=/var/log/xdebug_profiler
xdebug.profiler_output_name=cachegrind.out
xdebug.profiler_append=1
xdebug.coverage_enable=1

然后 运行在 "PROFILE" 模式下使用 XDebug Helper Chrome 扩展进行我的功能测试。这会将 XDEBUG_PROFILE 添加到 HTTP 请求的 cookie 字段,进而触发 PHP 应用程序中的分析器。 (或者,您可以为所有使用 xdebug.profiler_enable=1 的请求打开探查器)

我遇到的问题是将输出文件 (cachegrind.out) 转换为由 phpunit 提供的同类 html 报告。我可以使用 kcachegrind 分析器输出,但该应用程序无法导出代码覆盖率报告,更不用说指定 included/excluded 个文件了。

我也查看了 phpcov 命令行工具,但虽然它支持序列化 PHP_CodeCoverage 对象,但它不适用于 XDebug cachegrind 文件。

我希望我可以编写一些 PHP 将 XDebug 分析器输出文件 (cachegrind.out) 导入到 PHP_CodeCoverage 对象中,然后按照 [=45] 中的示例=] 生成 HTML 报告的单元源代码。有没有人有以这种方式分析 运行ning PHP 应用程序的经验?有更简单的方法吗?

如果可能,我想避免在我的 PHP 应用程序源代码中直接使用 PHP_CodeCoverage。

您无法从概要分析数据的分析中获得细粒度的代码覆盖率数据。后者仅具有已执行功能或方法的信息。虽然这足以计算函数覆盖率和方法覆盖率的弱变体,但不足以产生细粒度的行覆盖率,例如。

我最终使用 PHP 代码覆盖率库完成了这项工作。我创建了一个对象并开始跟踪 pre_system CodeIgniter 挂钩中的代码覆盖率,并将覆盖率报告写入 post_system CodeIgniter 挂钩中的文件。然后我制作了一个脚本来合并 coverage-php 对象并将它们输出为 HTML.

我原以为 HTML 文件可以与 phpcov 合并,但我无法合并 .html 报告,因为缺少 "Template" 文件.我还惊讶地发现 phpcov 不允许您指定合并文件的输出格式(即我可以合并 .cov 文件但无法将它们输出到 .html 报告) .

所以这是我的合并代码,大部分只是 extension of this post,但他的反序列化 .cov 文件的方法在 PHP 5.3

中对我不起作用
<?php
/**
 * "Deserializes" PHP_CodeCoverage objects from the files passed on the command line,
 * combines them into a single coverage object and creates an HTML report of the
 * combined coverage.
 */
require_once '/var/www/quickstart/vendor/autoload.php';

if ($argc <= 1) {
  die("Usage: php generate-coverage-report.php cov-file1 [cov-file2 cov-    file3...]\n");
}

foreach (array_slice($argv, 1) as $filename) {
  if (isset($codeCoverage)) {
      // Reconstruct serialized output (from .cov file such as generated from 'phpunit --coverage-php')
      $_coverage = include($filename);
      // $codeCoverage->filter()->addFilesToWhitelist($_coverage->filter()->getWhitelist());
      $codeCoverage->merge($_coverage);
      unset($_coverage);
  } else {
      $codeCoverage = include($filename);
  }
}

print "\nGenerating code coverage report in HTML format ...";

// Based on PHPUnit_TextUI_TestRunner::doRun
$writer = new PHP_CodeCoverage_Report_HTML(
  'UTF-8',
  false, // 'reportHighlight'
  35, // 'reportLowUpperBound'
  70, // 'reportHighLowerBound'
  sprintf(
    ' and <a href="http://phpunit.de/"></a>'
    //PHPUnit_Runner_Version::id()
      )
  );

$writer->process($codeCoverage, 'coverage');

print " done\n";
print "See coverage/index.html\n";