Beispiel #1
0
 /**
  * @param CodeCoverage $coverage
  * @param string       $target
  */
 public function process(CodeCoverage $coverage, $target)
 {
     $target = $this->getDirectory($target);
     $report = $coverage->getReport();
     unset($coverage);
     if (!isset($_SERVER['REQUEST_TIME'])) {
         $_SERVER['REQUEST_TIME'] = time();
     }
     $date = date('D M j G:i:s T Y', $_SERVER['REQUEST_TIME']);
     $dashboard = new Dashboard($this->templatePath, $this->generator, $date, $this->lowUpperBound, $this->highLowerBound);
     $directory = new Directory($this->templatePath, $this->generator, $date, $this->lowUpperBound, $this->highLowerBound);
     $file = new File($this->templatePath, $this->generator, $date, $this->lowUpperBound, $this->highLowerBound);
     $directory->render($report, $target . 'index.html');
     $dashboard->render($report, $target . 'dashboard.html');
     foreach ($report as $node) {
         $id = $node->getId();
         if ($node instanceof DirectoryNode) {
             if (!file_exists($target . $id)) {
                 mkdir($target . $id, 0777, true);
             }
             $directory->render($node, $target . $id . '/index.html');
             $dashboard->render($node, $target . $id . '/dashboard.html');
         } else {
             $dir = dirname($target . $id);
             if (!file_exists($dir)) {
                 mkdir($dir, 0777, true);
             }
             $file->render($node, $target . $id . '.html');
         }
     }
     $this->copyFiles($target);
 }
 /**
  * Test merge for code coverage library 4 version
  *
  * @requires function \SebastianBergmann\CodeCoverage\CodeCoverage::merge
  */
 public function testSimpleMerge()
 {
     $firstFile = PARATEST_ROOT . '/src/ParaTest/Logging/LogInterpreter.php';
     $secondFile = PARATEST_ROOT . '/src/ParaTest/Logging/MetaProvider.php';
     $filter = new Filter();
     $filter->addFilesToWhitelist([$firstFile, $secondFile]);
     $coverage1 = new CodeCoverage(null, $filter);
     $coverage1->append(array($firstFile => array(35 => 1), $secondFile => array(34 => 1)), 'Test1');
     $coverage2 = new CodeCoverage(null, $filter);
     $coverage2->append(array($firstFile => array(35 => 1, 36 => 1)), 'Test2');
     $merger = new CoverageMerger();
     $this->call($merger, 'addCoverage', $coverage1);
     $this->call($merger, 'addCoverage', $coverage2);
     /** @var CodeCoverage $coverage */
     $coverage = $this->getObjectValue($merger, 'coverage');
     $this->assertInstanceOf('\\SebastianBergmann\\CodeCoverage\\CodeCoverage', $coverage);
     $data = $coverage->getData();
     $this->assertCount(2, $data[$firstFile][35]);
     $this->assertEquals('Test1', $data[$firstFile][35][0]);
     $this->assertEquals('Test2', $data[$firstFile][35][1]);
     $this->assertCount(1, $data[$firstFile][36]);
     $this->assertEquals('Test2', $data[$firstFile][36][0]);
     $this->assertCount(1, $data[$secondFile][34]);
     $this->assertEquals('Test1', $data[$secondFile][34][0]);
 }
Beispiel #3
0
 /**
  * @param \PHP_CodeCoverage|CodeCoverage $coverage
  */
 private function addCoverage($coverage)
 {
     if (null === $this->coverage) {
         $this->coverage = $coverage;
     } else {
         $this->coverage->merge($coverage);
     }
 }
Beispiel #4
0
 /**
  * @param CodeCoverage $coverage
  *
  * @return Directory
  */
 public function build(CodeCoverage $coverage)
 {
     $files = $coverage->getData();
     $commonPath = $this->reducePaths($files);
     $root = new Directory($commonPath, null);
     $this->addItems($root, $this->buildDirectoryStructure($files), $coverage->getTests(), $coverage->getCacheTokens());
     return $root;
 }
Beispiel #5
0
 /**
  * @param AbstractParaunitProcess $process
  */
 private function merge(AbstractParaunitProcess $process)
 {
     $newCoverageData = $this->coverageFetcher->fetch($process);
     if ($this->coverageData instanceof CodeCoverage) {
         $this->coverageData->merge($newCoverageData);
     } else {
         $this->coverageData = $newCoverageData;
     }
 }
Beispiel #6
0
 /**
  * @param CodeCoverage $coverage
  * @param string       $target
  *
  * @throws RuntimeException
  */
 public function process(CodeCoverage $coverage, $target)
 {
     if (substr($target, -1, 1) != DIRECTORY_SEPARATOR) {
         $target .= DIRECTORY_SEPARATOR;
     }
     $this->target = $target;
     $this->initTargetDirectory($target);
     $report = $coverage->getReport();
     $this->project = new Project($coverage->getReport()->getName());
     $this->processTests($coverage->getTests());
     $this->processDirectory($report, $this->project);
     $index = $this->project->asDom();
     $index->formatOutput = true;
     $index->preserveWhiteSpace = false;
     $index->save($target . '/index.xml');
 }
Beispiel #7
0
    /**
     * @param CodeCoverage $coverage
     * @param string       $target
     *
     * @return string
     */
    public function process(CodeCoverage $coverage, $target = null)
    {
        $filter = $coverage->filter();
        $output = sprintf('<?php
$coverage = new SebastianBergmann\\CodeCoverage\\CodeCoverage;
$coverage->setData(%s);
$coverage->setTests(%s);

$filter = $coverage->filter();
$filter->setWhitelistedFiles(%s);

return $coverage;', var_export($coverage->getData(true), 1), var_export($coverage->getTests(), 1), var_export($filter->getWhitelistedFiles(), 1));
        if ($target !== null) {
            return file_put_contents($target, $output);
        } else {
            return $output;
        }
    }
Beispiel #8
0
 /**
  * @expectedException SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
  */
 public function testAppendThrowsExceptionIfUsedCodeWasNotExecuted()
 {
     $this->coverage->filter()->addDirectoryToWhitelist(TEST_FILES_PATH);
     $this->coverage->setCheckForUnexecutedCoveredCode(true);
     $data = [TEST_FILES_PATH . 'BankAccount.php' => [29 => -1, 31 => -1]];
     $linesToBeCovered = [TEST_FILES_PATH . 'BankAccount.php' => [29, 31]];
     $linesToBeUsed = [TEST_FILES_PATH . 'BankAccount.php' => [22, 24]];
     $this->coverage->append($data, 'File1.php', true, $linesToBeCovered, $linesToBeUsed);
 }
Beispiel #9
0
 /**
  * @param CodeCoverage $coverage
  * @param bool         $showColors
  *
  * @return string
  */
 public function process(CodeCoverage $coverage, $showColors = false)
 {
     $output = PHP_EOL . PHP_EOL;
     $report = $coverage->getReport();
     unset($coverage);
     $colors = ['header' => '', 'classes' => '', 'methods' => '', 'lines' => '', 'reset' => '', 'eol' => ''];
     if ($showColors) {
         $colors['classes'] = $this->getCoverageColor($report->getNumTestedClassesAndTraits(), $report->getNumClassesAndTraits());
         $colors['methods'] = $this->getCoverageColor($report->getNumTestedMethods(), $report->getNumMethods());
         $colors['lines'] = $this->getCoverageColor($report->getNumExecutedLines(), $report->getNumExecutableLines());
         $colors['reset'] = $this->colors['reset'];
         $colors['header'] = $this->colors['header'];
         $colors['eol'] = $this->colors['eol'];
     }
     $classes = sprintf('  Classes: %6s (%d/%d)', Util::percent($report->getNumTestedClassesAndTraits(), $report->getNumClassesAndTraits(), true), $report->getNumTestedClassesAndTraits(), $report->getNumClassesAndTraits());
     $methods = sprintf('  Methods: %6s (%d/%d)', Util::percent($report->getNumTestedMethods(), $report->getNumMethods(), true), $report->getNumTestedMethods(), $report->getNumMethods());
     $lines = sprintf('  Lines:   %6s (%d/%d)', Util::percent($report->getNumExecutedLines(), $report->getNumExecutableLines(), true), $report->getNumExecutedLines(), $report->getNumExecutableLines());
     $padding = max(array_map('strlen', [$classes, $methods, $lines]));
     if ($this->showOnlySummary) {
         $title = 'Code Coverage Report Summary:';
         $padding = max($padding, strlen($title));
         $output .= $this->format($colors['header'], $padding, $title);
     } else {
         $date = date('  Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
         $title = 'Code Coverage Report:';
         $output .= $this->format($colors['header'], $padding, $title);
         $output .= $this->format($colors['header'], $padding, $date);
         $output .= $this->format($colors['header'], $padding, '');
         $output .= $this->format($colors['header'], $padding, ' Summary:');
     }
     $output .= $this->format($colors['classes'], $padding, $classes);
     $output .= $this->format($colors['methods'], $padding, $methods);
     $output .= $this->format($colors['lines'], $padding, $lines);
     if ($this->showOnlySummary) {
         return $output . PHP_EOL;
     }
     $classCoverage = [];
     foreach ($report as $item) {
         if (!$item instanceof File) {
             continue;
         }
         $classes = $item->getClassesAndTraits();
         foreach ($classes as $className => $class) {
             $classStatements = 0;
             $coveredClassStatements = 0;
             $coveredMethods = 0;
             $classMethods = 0;
             foreach ($class['methods'] as $method) {
                 if ($method['executableLines'] == 0) {
                     continue;
                 }
                 $classMethods++;
                 $classStatements += $method['executableLines'];
                 $coveredClassStatements += $method['executedLines'];
                 if ($method['coverage'] == 100) {
                     $coveredMethods++;
                 }
             }
             if (!empty($class['package']['namespace'])) {
                 $namespace = '\\' . $class['package']['namespace'] . '::';
             } elseif (!empty($class['package']['fullPackage'])) {
                 $namespace = '@' . $class['package']['fullPackage'] . '::';
             } else {
                 $namespace = '';
             }
             $classCoverage[$namespace . $className] = ['namespace' => $namespace, 'className ' => $className, 'methodsCovered' => $coveredMethods, 'methodCount' => $classMethods, 'statementsCovered' => $coveredClassStatements, 'statementCount' => $classStatements];
         }
     }
     ksort($classCoverage);
     $methodColor = '';
     $linesColor = '';
     $resetColor = '';
     foreach ($classCoverage as $fullQualifiedPath => $classInfo) {
         if ($classInfo['statementsCovered'] != 0 || $this->showUncoveredFiles) {
             if ($showColors) {
                 $methodColor = $this->getCoverageColor($classInfo['methodsCovered'], $classInfo['methodCount']);
                 $linesColor = $this->getCoverageColor($classInfo['statementsCovered'], $classInfo['statementCount']);
                 $resetColor = $colors['reset'];
             }
             $output .= PHP_EOL . $fullQualifiedPath . PHP_EOL . '  ' . $methodColor . 'Methods: ' . $this->printCoverageCounts($classInfo['methodsCovered'], $classInfo['methodCount'], 2) . $resetColor . ' ' . '  ' . $linesColor . 'Lines: ' . $this->printCoverageCounts($classInfo['statementsCovered'], $classInfo['statementCount'], 3) . $resetColor;
         }
     }
     return $output . PHP_EOL;
 }
Beispiel #10
0
 /**
  * @param CodeCoverage $coverage
  * @param string       $target
  * @param string       $name
  *
  * @return string
  */
 public function process(CodeCoverage $coverage, $target = null, $name = null)
 {
     $xmlDocument = new \DOMDocument('1.0', 'UTF-8');
     $xmlDocument->formatOutput = true;
     $xmlCoverage = $xmlDocument->createElement('coverage');
     $xmlCoverage->setAttribute('generated', (int) $_SERVER['REQUEST_TIME']);
     $xmlDocument->appendChild($xmlCoverage);
     $xmlProject = $xmlDocument->createElement('project');
     $xmlProject->setAttribute('timestamp', (int) $_SERVER['REQUEST_TIME']);
     if (is_string($name)) {
         $xmlProject->setAttribute('name', $name);
     }
     $xmlCoverage->appendChild($xmlProject);
     $packages = [];
     $report = $coverage->getReport();
     unset($coverage);
     foreach ($report as $item) {
         if (!$item instanceof File) {
             continue;
         }
         /* @var File $item */
         $xmlFile = $xmlDocument->createElement('file');
         $xmlFile->setAttribute('name', $item->getPath());
         $classes = $item->getClassesAndTraits();
         $coverage = $item->getCoverageData();
         $lines = [];
         $namespace = 'global';
         foreach ($classes as $className => $class) {
             $classStatements = 0;
             $coveredClassStatements = 0;
             $coveredMethods = 0;
             $classMethods = 0;
             foreach ($class['methods'] as $methodName => $method) {
                 if ($method['executableLines'] == 0) {
                     continue;
                 }
                 $classMethods++;
                 $classStatements += $method['executableLines'];
                 $coveredClassStatements += $method['executedLines'];
                 if ($method['coverage'] == 100) {
                     $coveredMethods++;
                 }
                 $methodCount = 0;
                 foreach (range($method['startLine'], $method['endLine']) as $line) {
                     if (isset($coverage[$line]) && $coverage[$line] !== null) {
                         $methodCount = max($methodCount, count($coverage[$line]));
                     }
                 }
                 $lines[$method['startLine']] = ['ccn' => $method['ccn'], 'count' => $methodCount, 'crap' => $method['crap'], 'type' => 'method', 'visibility' => $method['visibility'], 'name' => $methodName];
             }
             if (!empty($class['package']['namespace'])) {
                 $namespace = $class['package']['namespace'];
             }
             $xmlClass = $xmlDocument->createElement('class');
             $xmlClass->setAttribute('name', $className);
             $xmlClass->setAttribute('namespace', $namespace);
             if (!empty($class['package']['fullPackage'])) {
                 $xmlClass->setAttribute('fullPackage', $class['package']['fullPackage']);
             }
             if (!empty($class['package']['category'])) {
                 $xmlClass->setAttribute('category', $class['package']['category']);
             }
             if (!empty($class['package']['package'])) {
                 $xmlClass->setAttribute('package', $class['package']['package']);
             }
             if (!empty($class['package']['subpackage'])) {
                 $xmlClass->setAttribute('subpackage', $class['package']['subpackage']);
             }
             $xmlFile->appendChild($xmlClass);
             $xmlMetrics = $xmlDocument->createElement('metrics');
             $xmlMetrics->setAttribute('complexity', $class['ccn']);
             $xmlMetrics->setAttribute('methods', $classMethods);
             $xmlMetrics->setAttribute('coveredmethods', $coveredMethods);
             $xmlMetrics->setAttribute('conditionals', 0);
             $xmlMetrics->setAttribute('coveredconditionals', 0);
             $xmlMetrics->setAttribute('statements', $classStatements);
             $xmlMetrics->setAttribute('coveredstatements', $coveredClassStatements);
             $xmlMetrics->setAttribute('elements', $classMethods + $classStatements);
             $xmlMetrics->setAttribute('coveredelements', $coveredMethods + $coveredClassStatements);
             $xmlClass->appendChild($xmlMetrics);
         }
         foreach ($coverage as $line => $data) {
             if ($data === null || isset($lines[$line])) {
                 continue;
             }
             $lines[$line] = ['count' => count($data), 'type' => 'stmt'];
         }
         ksort($lines);
         foreach ($lines as $line => $data) {
             $xmlLine = $xmlDocument->createElement('line');
             $xmlLine->setAttribute('num', $line);
             $xmlLine->setAttribute('type', $data['type']);
             if (isset($data['name'])) {
                 $xmlLine->setAttribute('name', $data['name']);
             }
             if (isset($data['visibility'])) {
                 $xmlLine->setAttribute('visibility', $data['visibility']);
             }
             if (isset($data['ccn'])) {
                 $xmlLine->setAttribute('complexity', $data['ccn']);
             }
             if (isset($data['crap'])) {
                 $xmlLine->setAttribute('crap', $data['crap']);
             }
             $xmlLine->setAttribute('count', $data['count']);
             $xmlFile->appendChild($xmlLine);
         }
         $linesOfCode = $item->getLinesOfCode();
         $xmlMetrics = $xmlDocument->createElement('metrics');
         $xmlMetrics->setAttribute('loc', $linesOfCode['loc']);
         $xmlMetrics->setAttribute('ncloc', $linesOfCode['ncloc']);
         $xmlMetrics->setAttribute('classes', $item->getNumClassesAndTraits());
         $xmlMetrics->setAttribute('methods', $item->getNumMethods());
         $xmlMetrics->setAttribute('coveredmethods', $item->getNumTestedMethods());
         $xmlMetrics->setAttribute('conditionals', 0);
         $xmlMetrics->setAttribute('coveredconditionals', 0);
         $xmlMetrics->setAttribute('statements', $item->getNumExecutableLines());
         $xmlMetrics->setAttribute('coveredstatements', $item->getNumExecutedLines());
         $xmlMetrics->setAttribute('elements', $item->getNumMethods() + $item->getNumExecutableLines());
         $xmlMetrics->setAttribute('coveredelements', $item->getNumTestedMethods() + $item->getNumExecutedLines());
         $xmlFile->appendChild($xmlMetrics);
         if ($namespace == 'global') {
             $xmlProject->appendChild($xmlFile);
         } else {
             if (!isset($packages[$namespace])) {
                 $packages[$namespace] = $xmlDocument->createElement('package');
                 $packages[$namespace]->setAttribute('name', $namespace);
                 $xmlProject->appendChild($packages[$namespace]);
             }
             $packages[$namespace]->appendChild($xmlFile);
         }
     }
     $linesOfCode = $report->getLinesOfCode();
     $xmlMetrics = $xmlDocument->createElement('metrics');
     $xmlMetrics->setAttribute('files', count($report));
     $xmlMetrics->setAttribute('loc', $linesOfCode['loc']);
     $xmlMetrics->setAttribute('ncloc', $linesOfCode['ncloc']);
     $xmlMetrics->setAttribute('classes', $report->getNumClassesAndTraits());
     $xmlMetrics->setAttribute('methods', $report->getNumMethods());
     $xmlMetrics->setAttribute('coveredmethods', $report->getNumTestedMethods());
     $xmlMetrics->setAttribute('conditionals', 0);
     $xmlMetrics->setAttribute('coveredconditionals', 0);
     $xmlMetrics->setAttribute('statements', $report->getNumExecutableLines());
     $xmlMetrics->setAttribute('coveredstatements', $report->getNumExecutedLines());
     $xmlMetrics->setAttribute('elements', $report->getNumMethods() + $report->getNumExecutableLines());
     $xmlMetrics->setAttribute('coveredelements', $report->getNumTestedMethods() + $report->getNumExecutedLines());
     $xmlProject->appendChild($xmlMetrics);
     $buffer = $xmlDocument->saveXML();
     if ($target !== null) {
         if (!is_dir(dirname($target))) {
             mkdir(dirname($target), 0777, true);
         }
         file_put_contents($target, $buffer);
     }
     return $buffer;
 }
Beispiel #11
0
 /**
  * @AfterScenario
  */
 public function stopCoverage()
 {
     self::$coverage->stop();
 }
Beispiel #12
0
 protected function getCoverageForClassWithAnonymousFunction()
 {
     $filter = new Filter();
     $filter->addFileToWhitelist(TEST_FILES_PATH . 'source_with_class_and_anonymous_function.php');
     $coverage = new CodeCoverage($this->setUpXdebugStubForClassWithAnonymousFunction(), $filter);
     $coverage->start('ClassWithAnonymousFunction', true);
     $coverage->stop();
     return $coverage;
 }
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @package    PHPUnit_Selenium
 * @author     Sebastian Bergmann <*****@*****.**>
 * @copyright  2010-2013 Sebastian Bergmann <*****@*****.**>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @link       http://www.phpunit.de/
 * @since      File available since Release 1.0.0
 */
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Report\PHP as PhpReport;
require_once 'libraries/vendor/autoload.php';
$coverage = new CodeCoverage();
$filter = $coverage->filter();
$files = getenv('PHPUNIT_COVERAGE_DATA_DIRECTORY') . '/logs/*.php';
foreach (glob($files) as $file) {
    /** @var CodeCoverage $cc */
    $cc = (function ($filename) {
        $coverage = null;
        include $filename;
        unlink($filename);
        return $coverage;
    })($file);
    $filter->addFilesToWhitelist($cc->filter()->getWhitelistedFiles());
    $coverage->merge($cc);
}
echo "Writing PHP report ...\n";
$writer = new PhpReport();
 /**
  * Merges the data from another instance.
  *
  * @param CodeCoverage $that
  */
 public function merge(CodeCoverage $that)
 {
     $this->filter->setWhitelistedFiles(array_merge($this->filter->getWhitelistedFiles(), $that->filter()->getWhitelistedFiles()));
     foreach ($that->data as $file => $lines) {
         if (!isset($this->data[$file])) {
             if (!$this->filter->isFiltered($file)) {
                 $this->data[$file] = $lines;
             }
             continue;
         }
         foreach ($lines as $line => $data) {
             if ($data !== null) {
                 if (!isset($this->data[$file][$line])) {
                     $this->data[$file][$line] = $data;
                 } else {
                     $this->data[$file][$line] = array_unique(array_merge($this->data[$file][$line], $data));
                 }
             }
         }
     }
     $this->tests = array_merge($this->tests, $that->getTests());
 }
Beispiel #15
0
 /**
  * Runs a TestCase.
  *
  * @param PHPUnit_Framework_Test $test
  */
 public function run(PHPUnit_Framework_Test $test)
 {
     PHPUnit_Framework_Assert::resetCount();
     if ($test instanceof PHPUnit_Framework_TestCase) {
         $test->setRegisterMockObjectsFromTestArgumentsRecursively($this->registerMockObjectsFromTestArgumentsRecursively);
     }
     $error = false;
     $failure = false;
     $warning = false;
     $incomplete = false;
     $risky = false;
     $skipped = false;
     $this->startTest($test);
     $errorHandlerSet = false;
     if ($this->convertErrorsToExceptions) {
         $oldErrorHandler = set_error_handler(['PHPUnit_Util_ErrorHandler', 'handleError'], E_ALL | E_STRICT);
         if ($oldErrorHandler === null) {
             $errorHandlerSet = true;
         } else {
             restore_error_handler();
         }
     }
     $collectCodeCoverage = $this->codeCoverage !== null && !$test instanceof PHPUnit_Framework_WarningTestCase;
     if ($collectCodeCoverage) {
         $this->codeCoverage->start($test);
     }
     $monitorFunctions = $this->beStrictAboutResourceUsageDuringSmallTests && !$test instanceof PHPUnit_Framework_WarningTestCase && $test->getSize() == PHPUnit_Util_Test::SMALL && function_exists('xdebug_start_function_monitor');
     if ($monitorFunctions) {
         xdebug_start_function_monitor(ResourceOperations::getFunctions());
     }
     PHP_Timer::start();
     try {
         if (!$test instanceof PHPUnit_Framework_WarningTestCase && $test->getSize() != PHPUnit_Util_Test::UNKNOWN && $this->enforceTimeLimit && extension_loaded('pcntl') && class_exists('PHP_Invoker')) {
             switch ($test->getSize()) {
                 case PHPUnit_Util_Test::SMALL:
                     $_timeout = $this->timeoutForSmallTests;
                     break;
                 case PHPUnit_Util_Test::MEDIUM:
                     $_timeout = $this->timeoutForMediumTests;
                     break;
                 case PHPUnit_Util_Test::LARGE:
                     $_timeout = $this->timeoutForLargeTests;
                     break;
             }
             $invoker = new PHP_Invoker();
             $invoker->invoke([$test, 'runBare'], [], $_timeout);
         } else {
             $test->runBare();
         }
     } catch (PHPUnit_Framework_MockObject_Exception $e) {
         $e = new PHPUnit_Framework_Warning($e->getMessage());
         $warning = true;
     } catch (PHPUnit_Framework_AssertionFailedError $e) {
         $failure = true;
         if ($e instanceof PHPUnit_Framework_RiskyTestError) {
             $risky = true;
         } elseif ($e instanceof PHPUnit_Framework_IncompleteTestError) {
             $incomplete = true;
         } elseif ($e instanceof PHPUnit_Framework_SkippedTestError) {
             $skipped = true;
         }
     } catch (PHPUnit_Framework_Warning $e) {
         $warning = true;
     } catch (PHPUnit_Framework_Exception $e) {
         $error = true;
     } catch (Throwable $e) {
         $e = new PHPUnit_Framework_ExceptionWrapper($e);
         $error = true;
     } catch (Exception $e) {
         $e = new PHPUnit_Framework_ExceptionWrapper($e);
         $error = true;
     }
     $time = PHP_Timer::stop();
     $test->addToAssertionCount(PHPUnit_Framework_Assert::getCount());
     if ($monitorFunctions) {
         $blacklist = new PHPUnit_Util_Blacklist();
         $functions = xdebug_get_monitored_functions();
         xdebug_stop_function_monitor();
         foreach ($functions as $function) {
             if (!$blacklist->isBlacklisted($function['filename'])) {
                 $this->addFailure($test, new PHPUnit_Framework_RiskyTestError(sprintf('%s() used in %s:%s', $function['function'], $function['filename'], $function['lineno'])), $time);
             }
         }
     }
     if ($this->beStrictAboutTestsThatDoNotTestAnything && $test->getNumAssertions() == 0) {
         $risky = true;
     }
     if ($collectCodeCoverage) {
         $append = !$risky && !$incomplete && !$skipped;
         $linesToBeCovered = [];
         $linesToBeUsed = [];
         if ($append && $test instanceof PHPUnit_Framework_TestCase) {
             try {
                 $linesToBeCovered = PHPUnit_Util_Test::getLinesToBeCovered(get_class($test), $test->getName(false));
                 $linesToBeUsed = PHPUnit_Util_Test::getLinesToBeUsed(get_class($test), $test->getName(false));
             } catch (PHPUnit_Framework_InvalidCoversTargetException $cce) {
                 $this->addWarning($test, new PHPUnit_Framework_Warning($cce->getMessage()), $time);
             }
         }
         try {
             $this->codeCoverage->stop($append, $linesToBeCovered, $linesToBeUsed);
         } catch (UnintentionallyCoveredCodeException $cce) {
             $this->addFailure($test, new PHPUnit_Framework_UnintentionallyCoveredCodeError('This test executed code that is not listed as code to be covered or used:' . PHP_EOL . $cce->getMessage()), $time);
         } catch (CoveredCodeNotExecutedException $cce) {
             $this->addFailure($test, new PHPUnit_Framework_CoveredCodeNotExecutedException('This test did not execute all the code that is listed as code to be covered:' . PHP_EOL . $cce->getMessage()), $time);
         } catch (MissingCoversAnnotationException $cce) {
             $this->addFailure($test, new PHPUnit_Framework_MissingCoversAnnotationException('This test does not have a @covers annotation but is expected to have one'), $time);
         } catch (CodeCoverageException $cce) {
             $error = true;
             if (!isset($e)) {
                 $e = $cce;
             }
         }
     }
     if ($errorHandlerSet === true) {
         restore_error_handler();
     }
     if ($error === true) {
         $this->addError($test, $e, $time);
     } elseif ($failure === true) {
         $this->addFailure($test, $e, $time);
     } elseif ($warning === true) {
         $this->addWarning($test, $e, $time);
     } elseif ($this->beStrictAboutTestsThatDoNotTestAnything && $test->getNumAssertions() == 0) {
         $this->addFailure($test, new PHPUnit_Framework_RiskyTestError('This test did not perform any assertions'), $time);
     } elseif ($this->beStrictAboutOutputDuringTests && $test->hasOutput()) {
         $this->addFailure($test, new PHPUnit_Framework_OutputError(sprintf('This test printed output: %s', $test->getActualOutput())), $time);
     } elseif ($this->beStrictAboutTodoAnnotatedTests && $test instanceof PHPUnit_Framework_TestCase) {
         $annotations = $test->getAnnotations();
         if (isset($annotations['method']['todo'])) {
             $this->addFailure($test, new PHPUnit_Framework_RiskyTestError('Test method is annotated with @todo'), $time);
         }
     }
     $this->endTest($test, $time);
 }
 /**
  * @param PHPUnit_Framework_Test $suite
  * @param array                  $arguments
  * @param bool                   $exit
  *
  * @return PHPUnit_Framework_TestResult
  */
 public function doRun(PHPUnit_Framework_Test $suite, array $arguments = [], $exit = true)
 {
     if (isset($arguments['configuration'])) {
         $GLOBALS['__PHPUNIT_CONFIGURATION_FILE'] = $arguments['configuration'];
     }
     $this->handleConfiguration($arguments);
     $this->processSuiteFilters($suite, $arguments);
     if (isset($arguments['bootstrap'])) {
         $GLOBALS['__PHPUNIT_BOOTSTRAP'] = $arguments['bootstrap'];
     }
     if ($arguments['backupGlobals'] === true) {
         $suite->setBackupGlobals(true);
     }
     if ($arguments['backupStaticAttributes'] === true) {
         $suite->setBackupStaticAttributes(true);
     }
     if ($arguments['beStrictAboutChangesToGlobalState'] === true) {
         $suite->setbeStrictAboutChangesToGlobalState(true);
     }
     if (is_integer($arguments['repeat']) && $arguments['repeat'] > 0) {
         $_suite = new PHPUnit_Framework_TestSuite();
         foreach (range(1, $arguments['repeat']) as $step) {
             $_suite->addTest($suite);
         }
         $suite = $_suite;
         unset($_suite);
     }
     $result = $this->createTestResult();
     if (!$arguments['convertErrorsToExceptions']) {
         $result->convertErrorsToExceptions(false);
     }
     if (!$arguments['convertNoticesToExceptions']) {
         PHPUnit_Framework_Error_Notice::$enabled = false;
     }
     if (!$arguments['convertWarningsToExceptions']) {
         PHPUnit_Framework_Error_Warning::$enabled = false;
     }
     if ($arguments['stopOnError']) {
         $result->stopOnError(true);
     }
     if ($arguments['stopOnFailure']) {
         $result->stopOnFailure(true);
     }
     if ($arguments['stopOnWarning']) {
         $result->stopOnWarning(true);
     }
     if ($arguments['stopOnIncomplete']) {
         $result->stopOnIncomplete(true);
     }
     if ($arguments['stopOnRisky']) {
         $result->stopOnRisky(true);
     }
     if ($arguments['stopOnSkipped']) {
         $result->stopOnSkipped(true);
     }
     if ($arguments['registerMockObjectsFromTestArgumentsRecursively']) {
         $result->setRegisterMockObjectsFromTestArgumentsRecursively(true);
     }
     if ($this->printer === null) {
         if (isset($arguments['printer']) && $arguments['printer'] instanceof PHPUnit_Util_Printer) {
             $this->printer = $arguments['printer'];
         } else {
             $printerClass = 'PHPUnit_TextUI_ResultPrinter';
             if (isset($arguments['printer']) && is_string($arguments['printer']) && class_exists($arguments['printer'], false)) {
                 $class = new ReflectionClass($arguments['printer']);
                 if ($class->isSubclassOf('PHPUnit_TextUI_ResultPrinter')) {
                     $printerClass = $arguments['printer'];
                 }
             }
             $this->printer = new $printerClass(isset($arguments['stderr']) ? 'php://stderr' : null, $arguments['verbose'], $arguments['colors'], $arguments['debug'], $arguments['columns'], $arguments['reverseList']);
         }
     }
     $this->printer->write(PHPUnit_Runner_Version::getVersionString() . "\n");
     self::$versionStringPrinted = true;
     if ($arguments['verbose']) {
         $runtime = $this->runtime->getNameWithVersion();
         if ($this->runtime->hasXdebug()) {
             $runtime .= sprintf(' with Xdebug %s', phpversion('xdebug'));
         }
         $this->writeMessage('Runtime', $runtime);
         if (isset($arguments['configuration'])) {
             $this->writeMessage('Configuration', $arguments['configuration']->getFilename());
         }
         foreach ($arguments['loadedExtensions'] as $extension) {
             $this->writeMessage('Extension', $extension);
         }
         foreach ($arguments['notLoadedExtensions'] as $extension) {
             $this->writeMessage('Extension', $extension);
         }
     }
     foreach ($arguments['listeners'] as $listener) {
         $result->addListener($listener);
     }
     $result->addListener($this->printer);
     if (isset($arguments['testdoxHTMLFile'])) {
         $result->addListener(new PHPUnit_Util_TestDox_ResultPrinter_HTML($arguments['testdoxHTMLFile'], $arguments['testdoxGroups'], $arguments['testdoxExcludeGroups']));
     }
     if (isset($arguments['testdoxTextFile'])) {
         $result->addListener(new PHPUnit_Util_TestDox_ResultPrinter_Text($arguments['testdoxTextFile'], $arguments['testdoxGroups'], $arguments['testdoxExcludeGroups']));
     }
     if (isset($arguments['testdoxXMLFile'])) {
         $result->addListener(new PHPUnit_Util_TestDox_ResultPrinter_XML($arguments['testdoxXMLFile']));
     }
     $codeCoverageReports = 0;
     if (isset($arguments['coverageClover'])) {
         $codeCoverageReports++;
     }
     if (isset($arguments['coverageCrap4J'])) {
         $codeCoverageReports++;
     }
     if (isset($arguments['coverageHtml'])) {
         $codeCoverageReports++;
     }
     if (isset($arguments['coveragePHP'])) {
         $codeCoverageReports++;
     }
     if (isset($arguments['coverageText'])) {
         $codeCoverageReports++;
     }
     if (isset($arguments['coverageXml'])) {
         $codeCoverageReports++;
     }
     if (isset($arguments['noCoverage'])) {
         $codeCoverageReports = 0;
     }
     if ($codeCoverageReports > 0) {
         if (!$this->runtime->canCollectCodeCoverage()) {
             $this->writeMessage('Error', 'No code coverage driver is available');
             $codeCoverageReports = 0;
         } elseif (!isset($arguments['whitelist']) && !$this->codeCoverageFilter->hasWhitelist()) {
             $this->writeMessage('Error', 'No whitelist configured, no code coverage will be generated');
             $codeCoverageReports = 0;
         }
     }
     $this->printer->write("\n");
     if ($codeCoverageReports > 0) {
         $codeCoverage = new CodeCoverage(null, $this->codeCoverageFilter);
         $codeCoverage->setUnintentionallyCoveredSubclassesWhitelist([SebastianBergmann\Comparator\Comparator::class]);
         $codeCoverage->setAddUncoveredFilesFromWhitelist($arguments['addUncoveredFilesFromWhitelist']);
         $codeCoverage->setCheckForUnintentionallyCoveredCode($arguments['strictCoverage']);
         $codeCoverage->setCheckForMissingCoversAnnotation($arguments['strictCoverage']);
         $codeCoverage->setProcessUncoveredFilesFromWhitelist($arguments['processUncoveredFilesFromWhitelist']);
         if (isset($arguments['forceCoversAnnotation'])) {
             $codeCoverage->setForceCoversAnnotation($arguments['forceCoversAnnotation']);
         }
         if (isset($arguments['disableCodeCoverageIgnore'])) {
             $codeCoverage->setDisableIgnoredLines(true);
         }
         if (isset($arguments['whitelist'])) {
             $this->codeCoverageFilter->addDirectoryToWhitelist($arguments['whitelist']);
         }
         $result->setCodeCoverage($codeCoverage);
     }
     if ($codeCoverageReports > 1) {
         if (isset($arguments['cacheTokens'])) {
             $codeCoverage->setCacheTokens($arguments['cacheTokens']);
         }
     }
     if (isset($arguments['teamcityLogfile'])) {
         $result->addListener(new PHPUnit_Util_Log_TeamCity($arguments['teamcityLogfile']));
     }
     if (isset($arguments['junitLogfile'])) {
         $result->addListener(new PHPUnit_Util_Log_JUnit($arguments['junitLogfile'], $arguments['reportUselessTests']));
     }
     $result->beStrictAboutTestsThatDoNotTestAnything($arguments['reportUselessTests']);
     $result->beStrictAboutOutputDuringTests($arguments['disallowTestOutput']);
     $result->beStrictAboutTodoAnnotatedTests($arguments['disallowTodoAnnotatedTests']);
     $result->beStrictAboutResourceUsageDuringSmallTests($arguments['beStrictAboutResourceUsageDuringSmallTests']);
     $result->enforceTimeLimit($arguments['enforceTimeLimit']);
     $result->setTimeoutForSmallTests($arguments['timeoutForSmallTests']);
     $result->setTimeoutForMediumTests($arguments['timeoutForMediumTests']);
     $result->setTimeoutForLargeTests($arguments['timeoutForLargeTests']);
     if ($suite instanceof PHPUnit_Framework_TestSuite) {
         $suite->setRunTestInSeparateProcess($arguments['processIsolation']);
     }
     $suite->run($result);
     unset($suite);
     $result->flushListeners();
     if ($this->printer instanceof PHPUnit_TextUI_ResultPrinter) {
         $this->printer->printResult($result);
     }
     if (isset($codeCoverage)) {
         if (isset($arguments['coverageClover'])) {
             $this->printer->write("\nGenerating code coverage report in Clover XML format ...");
             try {
                 $writer = new CloverReport();
                 $writer->process($codeCoverage, $arguments['coverageClover']);
                 $this->printer->write(" done\n");
                 unset($writer);
             } catch (CodeCoverageException $e) {
                 $this->printer->write(" failed\n" . $e->getMessage() . "\n");
             }
         }
         if (isset($arguments['coverageCrap4J'])) {
             $this->printer->write("\nGenerating Crap4J report XML file ...");
             try {
                 $writer = new Crap4jReport($arguments['crap4jThreshold']);
                 $writer->process($codeCoverage, $arguments['coverageCrap4J']);
                 $this->printer->write(" done\n");
                 unset($writer);
             } catch (CodeCoverageException $e) {
                 $this->printer->write(" failed\n" . $e->getMessage() . "\n");
             }
         }
         if (isset($arguments['coverageHtml'])) {
             $this->printer->write("\nGenerating code coverage report in HTML format ...");
             try {
                 $writer = new HtmlReport($arguments['reportLowUpperBound'], $arguments['reportHighLowerBound'], sprintf(' and <a href="https://phpunit.de/">PHPUnit %s</a>', PHPUnit_Runner_Version::id()));
                 $writer->process($codeCoverage, $arguments['coverageHtml']);
                 $this->printer->write(" done\n");
                 unset($writer);
             } catch (CodeCoverageException $e) {
                 $this->printer->write(" failed\n" . $e->getMessage() . "\n");
             }
         }
         if (isset($arguments['coveragePHP'])) {
             $this->printer->write("\nGenerating code coverage report in PHP format ...");
             try {
                 $writer = new PhpReport();
                 $writer->process($codeCoverage, $arguments['coveragePHP']);
                 $this->printer->write(" done\n");
                 unset($writer);
             } catch (CodeCoverageException $e) {
                 $this->printer->write(" failed\n" . $e->getMessage() . "\n");
             }
         }
         if (isset($arguments['coverageText'])) {
             if ($arguments['coverageText'] == 'php://stdout') {
                 $outputStream = $this->printer;
                 $colors = $arguments['colors'] && $arguments['colors'] != PHPUnit_TextUI_ResultPrinter::COLOR_NEVER;
             } else {
                 $outputStream = new PHPUnit_Util_Printer($arguments['coverageText']);
                 $colors = false;
             }
             $processor = new TextReport($arguments['reportLowUpperBound'], $arguments['reportHighLowerBound'], $arguments['coverageTextShowUncoveredFiles'], $arguments['coverageTextShowOnlySummary']);
             $outputStream->write($processor->process($codeCoverage, $colors));
         }
         if (isset($arguments['coverageXml'])) {
             $this->printer->write("\nGenerating code coverage report in PHPUnit XML format ...");
             try {
                 $writer = new XmlReport();
                 $writer->process($codeCoverage, $arguments['coverageXml']);
                 $this->printer->write(" done\n");
                 unset($writer);
             } catch (CodeCoverageException $e) {
                 $this->printer->write(" failed\n" . $e->getMessage() . "\n");
             }
         }
     }
     if ($exit) {
         if ($result->wasSuccessful()) {
             if ($arguments['failOnRisky'] && !$result->allHarmless()) {
                 exit(self::FAILURE_EXIT);
             }
             if ($arguments['failOnWarning'] && $result->warningCount() > 0) {
                 exit(self::FAILURE_EXIT);
             }
             exit(self::SUCCESS_EXIT);
         }
         if ($result->errorCount() > 0) {
             exit(self::EXCEPTION_EXIT);
         }
         if ($result->failureCount() > 0) {
             exit(self::FAILURE_EXIT);
         }
     }
     return $result;
 }
Beispiel #17
0
 /**
  * @param CodeCoverage $coverage
  * @param CodeCoverage $that
  */
 private function mergeCoverage(CodeCoverage $coverage, CodeCoverage $that)
 {
     $filter = $coverage->filter();
     $filter->setWhitelistedFiles(array_merge($filter->getWhitelistedFiles(), $that->filter()->getWhitelistedFiles()));
     $thisData = $coverage->getData(true);
     $thatData = $that->getData(true);
     foreach ($thatData as $file => $lines) {
         if (!$this->hasCoverage($thatData, $file)) {
             continue;
         }
         if (!$this->hasCoverage($thisData, $file)) {
             if (!$filter->isFiltered($file)) {
                 $thisData[$file] = $lines;
             }
             continue;
         }
         foreach ($lines as $line => $data) {
             if ($data !== null) {
                 if (!isset($thisData[$file][$line])) {
                     $thisData[$file][$line] = $data;
                 } else {
                     $thisData[$file][$line] = array_unique(array_merge($thisData[$file][$line], $data));
                 }
             }
         }
     }
     $coverage->setData($thisData);
     $coverage->setTests(array_merge($coverage->getTests(), $that->getTests()));
 }
Beispiel #18
0
 public function __construct()
 {
     parent::__construct(new FakeDriver());
 }
Beispiel #19
0
 /**
  * @param CodeCoverage $coverage
  * @param string       $target
  * @param string       $name
  *
  * @return string
  */
 public function process(CodeCoverage $coverage, $target = null, $name = null)
 {
     $document = new \DOMDocument('1.0', 'UTF-8');
     $document->formatOutput = true;
     $root = $document->createElement('crap_result');
     $document->appendChild($root);
     $project = $document->createElement('project', is_string($name) ? $name : '');
     $root->appendChild($project);
     $root->appendChild($document->createElement('timestamp', date('Y-m-d H:i:s', (int) $_SERVER['REQUEST_TIME'])));
     $stats = $document->createElement('stats');
     $methodsNode = $document->createElement('methods');
     $report = $coverage->getReport();
     unset($coverage);
     $fullMethodCount = 0;
     $fullCrapMethodCount = 0;
     $fullCrapLoad = 0;
     $fullCrap = 0;
     foreach ($report as $item) {
         $namespace = 'global';
         if (!$item instanceof File) {
             continue;
         }
         $file = $document->createElement('file');
         $file->setAttribute('name', $item->getPath());
         $classes = $item->getClassesAndTraits();
         foreach ($classes as $className => $class) {
             foreach ($class['methods'] as $methodName => $method) {
                 $crapLoad = $this->getCrapLoad($method['crap'], $method['ccn'], $method['coverage']);
                 $fullCrap += $method['crap'];
                 $fullCrapLoad += $crapLoad;
                 $fullMethodCount++;
                 if ($method['crap'] >= $this->threshold) {
                     $fullCrapMethodCount++;
                 }
                 $methodNode = $document->createElement('method');
                 if (!empty($class['package']['namespace'])) {
                     $namespace = $class['package']['namespace'];
                 }
                 $methodNode->appendChild($document->createElement('package', $namespace));
                 $methodNode->appendChild($document->createElement('className', $className));
                 $methodNode->appendChild($document->createElement('methodName', $methodName));
                 $methodNode->appendChild($document->createElement('methodSignature', htmlspecialchars($method['signature'])));
                 $methodNode->appendChild($document->createElement('fullMethod', htmlspecialchars($method['signature'])));
                 $methodNode->appendChild($document->createElement('crap', $this->roundValue($method['crap'])));
                 $methodNode->appendChild($document->createElement('complexity', $method['ccn']));
                 $methodNode->appendChild($document->createElement('coverage', $this->roundValue($method['coverage'])));
                 $methodNode->appendChild($document->createElement('crapLoad', round($crapLoad)));
                 $methodsNode->appendChild($methodNode);
             }
         }
     }
     $stats->appendChild($document->createElement('name', 'Method Crap Stats'));
     $stats->appendChild($document->createElement('methodCount', $fullMethodCount));
     $stats->appendChild($document->createElement('crapMethodCount', $fullCrapMethodCount));
     $stats->appendChild($document->createElement('crapLoad', round($fullCrapLoad)));
     $stats->appendChild($document->createElement('totalCrap', $fullCrap));
     if ($fullMethodCount > 0) {
         $crapMethodPercent = $this->roundValue(100 * $fullCrapMethodCount / $fullMethodCount);
     } else {
         $crapMethodPercent = 0;
     }
     $stats->appendChild($document->createElement('crapMethodPercent', $crapMethodPercent));
     $root->appendChild($stats);
     $root->appendChild($methodsNode);
     $buffer = $document->saveXML();
     if ($target !== null) {
         if (!is_dir(dirname($target))) {
             mkdir(dirname($target), 0777, true);
         }
         file_put_contents($target, $buffer);
     }
     return $buffer;
 }