【问题标题】:Split PHPunit tests to stop out of memory error拆分 PHPunit 测试以停止内存不足错误
【发布时间】:2018-08-13 13:25:54
【问题描述】:

我有一个使用 phpunit 进行单元测试的业务应用程序。业务应用程序的规模不断扩大,单元测试也在不断增长。当我运行 phpunit 来获取代码覆盖率报告时,内存不足。生成包含大量单元测试的代码覆盖率报告的好方法是什么?

运行下面的phpunit.xml,我在完成之前得到以下错误:

PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 1068290 bytes)

我正在使用 PHP5.6 和 Jenkins 来运行这项工作。

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
  backupStaticAttributes="false"
  bootstrap="./src/bootstrap/autoload.php"
  colors="true"
  convertErrorsToExceptions="true"
  convertNoticesToExceptions="true"
  convertWarningsToExceptions="true"
  processIsolation="false"
  stopOnFailure="false"
  syntaxCheck="false"
>
 <testsuites>
  <testsuite name="module1">
   <directory>./tests/module1</directory>
   <directory>./tests/module2</directory>
   <directory>./tests/module3</directory>
   <directory>./tests/module4</directory>
   <directory>./tests/module5/directory>
   <directory>./tests/module6</directory>
   <directory>./tests/module7</directory>
   <directory>./tests/module8</directory>
  </testsuite>
  <testsuite name="module2">
   <directory>./tests/module9</directory>
   <directory>./tests/module10</directory>
   <directory>./tests/module11</directory>
   <directory>./tests/module12</directory>
   <directory>./tests/module13</directory>
   <directory>./tests/module14</directory>
   <directory>./tests/module15</directory>
   <directory>./tests/module16</directory>
  </testsuite>
 </testsuites>

 <filter>
  <blacklist>
   <directory>./src</directory>
  </blacklist>
  <whitelist>
   <directory>./src/app/module</directory>
  </whitelist>
 </filter>

 <logging>
  <log type="coverage-html" target="build/module" title="module"
   charset="UTF-8" yui="true" highlight="true"
   lowUpperBound="70" highLowerBound="90"/>
  <log type="junit" target="build/logs/module.xml" logIncompleteSkipped="false"/>
 </logging>

</phpunit>

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    好吧,您很少需要将未包含在白名单文件中的内容列入黑名单 - 尽管这可能会节省您开始测试的时间。将您正在测试的代码列入白名单,然后 &lt;exclude&gt; 将没有有用源代码的目录列入白名单。

    关于减少使用的内存量,有一些技术会有所帮助 - 首先,PHP7.1+ 将使用大量更少的内存。其次,找出哪些测试或代码使用了这么多内存。像atrapalo/phpunit-memory-and-time-usage-listener 这样的测试侦听器可以在测试使用大量未清理的内存时报告。您还可以通过此找到代码改进。

    其他 PHPUnit 插件,如 mybuilder/phpunit-accelerator 尝试自动“取消设置”变量。在测试中使用您自己的 tearDown() 函数这样做也会有所帮助。

    在短期内,如果您正在运行测试的机器确实仍有大量 RAM 可用,您可以简单地增加限制:

    <!-- phpunit.xml -->
    <php>
        <ini name="memory_limit" value="-1" />
        <!-- other PHP.ini or environment variables -->
    </php>
    

    最后,如果您的代码库确实很大,您可以将测试和覆盖率报告拆分为单独的部分,将覆盖率报告写入使用phpcov 工具合并的不同文件中。

    【讨论】:

    • 补充:使用新的 XDebug 代码覆盖率白名单功能,或 'pcov' 模块(在 PHP v7+ 和 PHPunit v8+ 中可用 - 向后移植可能适用于 PHPunit),将避免为您的库生成覆盖率/供应商代码(通常您只需要您的 src/ 目录或类似目录)。这可以节省大量内存和时间。
    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    相关资源
    最近更新 更多