Search code examples
phpphpunitlamp

phpunit Whitelist vs Blacklist


Trying to decide which one would be better suited for my situation. According to the phpunit docs (which are very limited) the whitelist should include all files inside of the directory, but it doesnt seem to be working that way. Does anyone have any suggestions or can point me to a good reference other than the phpunit manual. I am using an XML configuration file. Thanks in advance!

<?xml version="1.0" encoding="utf-8"?>
<phpunit>
  <filter>
    <whitelist>
      <directory suffix=".php">/home/ddohr/git/project/</directory>
    <exclude>
      <directory suffix=".php">/home/ddohr/git/project/vendor/</directory>
      <directory suffix=".php">/home/ddohr/git/project/plugins/</directory>
      <directory suffix=".php">/home/ddohr/git/project/test/</directory>
    </exclude>
    </whitelist>
  </filter>
</phpunit>

Solution

  • Update: The below no longer works with PHPUnit 3.6 and above. See Add files to code-coverage white/blacklists in bootstrap.php for PHPUnit for the new solution.

    Original Answer

    As for the "Whitelist vs Blacklist" question note that they are mutually exclusive, and a whitelist wins out over a blacklist. We use whitelists on our projects since we want 0% coverage reported on classes without tests. Our bootstrap.php modules setup the whitelists as that seemed more manageable than placing them in phpunit.xml at the time.

    For example, the library project's bootstrap.php uses includeDirectoryForCodeCoverage() to add its source to the whitelist:

    includeDirectoryForCodeCoverage(MY_LIBRARY_PATH);
    

    This is a simple helper for abstracting the actual calls to PHP_CodeCoverage:

    function includeDirectoryForCodeCoverage($path) {
        PHP_CodeCoverage_Filter::getInstance()
                ->addDirectoryToWhitelist($path);
    }
    
    function includeFileForCodeCoverage($path) {
        PHP_CodeCoverage_Filter::getInstance()
                ->addFileToWhitelist($path);
    }
    
    function includeFilesForCodeCoverage(array $paths) {
        PHP_CodeCoverage_Filter::getInstance()
                ->addFilesToWhitelist($paths);
    }
    

    The blacklist is still handy, however. PHPUnit will hide stack trace entries for any code in the blacklisted files. For that reason I added this little gem:

    function ignoreDirectoryInStackTraces($path) {
        PHP_CodeCoverage_Filter::getInstance()
                ->addDirectoryToBlacklist($path);
    }