public function run(\PHPUnit_Framework_TestResult $result = null) { if (!$result) { $result = new \PHPUnit_Framework_TestResult(); } $opt = null; \PHP_Timer::start(); $result->startTest($this); try { $opt = \Docopt::handle($this->doc, array('argv' => $this->argv, 'exit' => false)); } catch (\Exception $ex) { // gulp } $found = null; if ($opt) { if (!$opt->success) { $found = array('user-error'); } elseif (empty($opt->args)) { $found = array(); } else { $found = $opt->args; } } $time = \PHP_Timer::stop(); try { \PHPUnit_Framework_Assert::assertEquals($this->expect, $found); } catch (\PHPUnit_Framework_AssertionFailedError $e) { $result->addFailure($this, $e, $time); } $result->endTest($this, $time); return $result; }
public function run(\PHPUnit_Framework_TestResult $result = null) { if (!$result) { $result = new \PHPUnit_Framework_TestResult(); } $reader = new \Fulfil\Test\SpecTest\Reader(); $tests = $reader->read($testFile); foreach ($tests as $test) { foreach ($test->data as $case) { \PHP_Timer::start(); $result->startTest($this); try { $ctx = new \Fulfil\Context(); $test->test->apply($case->in, $ctx); $flat = $ctx->flatten(); } catch (\Exception $ex) { // yum } $time = \PHP_Timer::stop(); try { \PHPUnit_Framework_Assert::assertEquals($case->valid, $flat->valid); } catch (\PHPUnit_Framework_AssertionFailedError $e) { $result->addFailure($this, $e, $time); } $result->endTest($this, $time); } } return $result; }
/** * Example middleware invokable class. * * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request * @param \Psr\Http\Message\ResponseInterface $response PSR7 response * @param callable $next Next middleware * * @return \Psr\Http\Message\ResponseInterface */ public function __invoke(Request $request, Response $response, callable $next) { // Start the timer at the beginning of the request \PHP_Timer::start(); $response = $next($request, $response); // Log the results $this->logger->info($request->getUri()->getAuthority() . ' ' . $request->getHeaderLine('AUTH_PRINCIPAL') . ' ' . $request->getAttribute('ip_address') . ' ' . $request->getMethod() . ' ' . $request->getUri()->getPath() . ' ' . $response->getStatusCode() . ' ' . $request->getBody()->getSize() . ' ' . $response->getBody()->getSize() . ' ' . \PHP_Timer::stop()); return $response; }
public function testArrays() { $total = 1000000; $try1 = array_fill(0, $total, 1); $try1[rand(0, count($try1) - 1)] = null; $try2 = array_fill(0, $total, 1); $try2[rand(0, count($try1) - 1)] = null; $try2[(string) count($try2)] = 'value'; $uk = rand(0, $total); unset($try2[$uk]); print 'isSequentialFastest:' . PHP_EOL; \PHP_Timer::start(); $isHashFalse = !ArrayStructure::isSequentialFastest($try1); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; \PHP_Timer::start(); $isHashTrue = !ArrayStructure::isSequentialFastest($try2); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; $this->assertFalse($isHashFalse); $this->assertTrue($isHashTrue); print 'isSequentialSimple:' . PHP_EOL; \PHP_Timer::start(); $isSeqFalse = !ArrayStructure::isSequentialSimple($try1); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; \PHP_Timer::start(); $isSeqTrue = !ArrayStructure::isSequentialSimple($try2); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; $this->assertFalse($isSeqFalse); $this->assertTrue($isSeqTrue); print 'isSequentialExotic:' . PHP_EOL; \PHP_Timer::start(); $isSeqTrue = ArrayStructure::isSequentialExotic($try1); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; \PHP_Timer::start(); $isSeqFalse = ArrayStructure::isSequentialExotic($try2); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; $this->assertFalse($isSeqFalse); $this->assertTrue($isSeqTrue); print 'isAssoc:' . PHP_EOL; \PHP_Timer::start(); $isAssocFalse = ArrayStructure::isAssoc($try1); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; \PHP_Timer::start(); $isAssocTrue = ArrayStructure::isAssoc($try2); $time = \PHP_Timer::stop(); print \PHP_Timer::secondsToTimeString($time) . PHP_EOL; $this->assertFalse($isAssocFalse); $this->assertTrue($isAssocTrue); }
/** * Initializes printing constraints, prints header * information and starts the test timer * * @param Options $options */ public function start(Options $options) { $this->numTestsWidth = strlen((string) $this->totalCases); $this->maxColumn = 69 - 2 * $this->numTestsWidth; printf("\nRunning phpunit in %d process%s with %s%s\n\n", $options->processes, $options->processes > 1 ? 'es' : '', $options->phpunit, $options->functional ? '. Functional mode is on' : ''); if (isset($options->filtered['configuration'])) { printf("Configuration read from %s\n\n", $options->filtered['configuration']->getPath()); } $this->timer->start(); $this->colors = $options->colors; }
/** * Run the invocable, and its prerequisites, by calling the invoke method * * @param string $start */ public function run($start) { Timer::start(); $task = $this->buildfile->get($start); $nodes = $this->buildfile->get($start)->getAdjacencyList(); foreach ($nodes as $prerequisite) { $this->run($prerequisite); } $task->invoke(); $this->duration = Timer::stop(); }
/** * Initializes printing constraints, prints header * information and starts the test timer * * @param Options $options */ public function start(Options $options) { $this->numTestsWidth = strlen((string) $this->totalCases); $this->maxColumn = $this->numberOfColumns + (DIRECTORY_SEPARATOR == "\\" ? -1 : 0) - strlen($this->getProgress()); printf("\nRunning phpunit in %d process%s with %s%s\n\n", $options->processes, $options->processes > 1 ? 'es' : '', $options->phpunit, $options->functional ? '. Functional mode is ON.' : ''); if (isset($options->filtered['configuration'])) { printf("Configuration read from %s\n\n", $options->filtered['configuration']->getPath()); } $this->timer->start(); $this->colors = $options->colors; $this->processSkipped = $this->isSkippedIncompleTestCanBeTracked($options); }
/** * If the dispatcher is run when there is a non-empty queue, a payload will * be dispatched from that queue. */ public function testRun() { $dispatcher = new SyncDispatcher($this->queue, $this->worker); $dispatcher->setWorkerTimeout(1000); $this->queue->expects($this->any())->method('count')->willReturn(123); $this->queue->expects($this->once())->method('pop')->willReturn('test'); $this->worker->expects($this->once())->method('run')->with('test'); Timer::start(); $dispatcher->run(); $time = Timer::stop(); $this->assertEquals(1, $time, "Time not within 50ms of target.", 0.05); }
/** * Runs a test and collects its result in a TestResult instance. * * @param PHPUnit_Framework_TestResult $result * @return PHPUnit_Framework_TestResult */ public function run(PHPUnit_Framework_TestResult $result = null) { $sections = $this->parse(); $code = $this->render($sections['FILE']); if ($result === null) { $result = new PHPUnit_Framework_TestResult(); } $php = PHPUnit_Util_PHP::factory(); $skip = false; $time = 0; $settings = $this->settings; $result->startTest($this); if (isset($sections['INI'])) { $settings = array_merge($settings, $this->parseIniSection($sections['INI'])); } if (isset($sections['SKIPIF'])) { $jobResult = $php->runJob($sections['SKIPIF'], $settings); if (!strncasecmp('skip', ltrim($jobResult['stdout']), 4)) { if (preg_match('/^\\s*skip\\s*(.+)\\s*/i', $jobResult['stdout'], $message)) { $message = substr($message[1], 2); } else { $message = ''; } $result->addFailure($this, new PHPUnit_Framework_SkippedTestError($message), 0); $skip = true; } } if (!$skip) { PHP_Timer::start(); $jobResult = $php->runJob($code, $settings); $time = PHP_Timer::stop(); if (isset($sections['EXPECT'])) { $assertion = 'assertEquals'; $expected = $sections['EXPECT']; } else { $assertion = 'assertStringMatchesFormat'; $expected = $sections['EXPECTF']; } $output = preg_replace('/\\r\\n/', "\n", trim($jobResult['stdout'])); $expected = preg_replace('/\\r\\n/', "\n", trim($expected)); try { PHPUnit_Framework_Assert::$assertion($expected, $output); } catch (PHPUnit_Framework_AssertionFailedError $e) { $result->addFailure($this, $e, $time); } catch (Throwable $t) { $result->addError($this, $t, $time); } catch (Exception $e) { $result->addError($this, $e, $time); } } $result->endTest($this, $time); return $result; }
/** * When a payload is dispatched, a timeout should occur, after which the * worker associated with the dispatcher should consume the payload. */ public function testDispatchAction() { $dispatcher = new DaemonDispatcher($this->queue, $this->worker, 3); $dispatcher->setManager($this->manager); $dispatcher->setWorkerTimeout(1000); $this->worker->expects($this->once())->method('run')->with('testing'); Timer::start(); $dispatcher->getDispatchAction('testing')->__invoke(); $time = Timer::stop(); $this->assertEquals(1, $time, "Time not within 50ms of target.", 0.05); $this->assertEmpty($dispatcher->getManager()->count()); }
public function testPersistentResourceSimulation() { PHP_Timer::start(); $movie = new ffmpeg_movie(self::$moviePath, true); $movie = new ffmpeg_movie(self::$moviePath, true); $movie = new ffmpeg_movie(self::$moviePath, true); $elapsed = PHP_Timer::stop(); PHP_Timer::start(); $movie = new ffmpeg_movie(self::$moviePath); $movie = new ffmpeg_movie(self::$moviePath); $movie = new ffmpeg_movie(self::$moviePath); $elapsed1 = PHP_Timer::stop(); $this->assertGreaterThan($elapsed, $elapsed1, 'Persistent resource simulation should be faster'); }
public function run(PHPUnit_Framework_TestResult $result = null) { PHPUnit_Framework_Assert::resetCount(); if ($result === NULL) { $result = new PHPUnit_Framework_TestResult(); } $this->suite->publishTestArticles(); // Add articles needed by the tests. $backend = new ParserTestSuiteBackend(); $result->startTest($this); // Support the transition to PHPUnit 3.5 where PHPUnit_Util_Timer is replaced with PHP_Timer if (class_exists('PHP_Timer')) { PHP_Timer::start(); } else { PHPUnit_Util_Timer::start(); } $r = false; try { # Run the test. # On failure, the subclassed backend will throw an exception with # the details. $pt = new PHPUnitParserTest(); $r = $pt->runTest($this->test['test'], $this->test['input'], $this->test['result'], $this->test['options'], $this->test['config']); } catch (PHPUnit_Framework_AssertionFailedError $e) { // PHPUnit_Util_Timer -> PHP_Timer support (see above) if (class_exists('PHP_Timer')) { $result->addFailure($this, $e, PHP_Timer::stop()); } else { $result->addFailure($this, $e, PHPUnit_Util_Timer::stop()); } } catch (Exception $e) { // PHPUnit_Util_Timer -> PHP_Timer support (see above) if (class_exists('PHP_Timer')) { $result->addFailure($this, $e, PHP_Timer::stop()); } else { $result->addFailure($this, $e, PHPUnit_Util_Timer::stop()); } } // PHPUnit_Util_Timer -> PHP_Timer support (see above) if (class_exists('PHP_Timer')) { $result->endTest($this, PHP_Timer::stop()); } else { $result->endTest($this, PHPUnit_Util_Timer::stop()); } $backend->recorder->record($this->test['test'], $r); $this->addToAssertionCount(PHPUnit_Framework_Assert::getCount()); return $result; }
function podlove_validate_image_cache() { set_time_limit(5 * MINUTE_IN_SECONDS); PHP_Timer::start(); $cache_files = glob(trailingslashit(Image::cache_dir()) . "*" . DIRECTORY_SEPARATOR . "*" . DIRECTORY_SEPARATOR . "cache.yml"); foreach ($cache_files as $cache_file) { $cache = Yaml::parse(file_get_contents($cache_file)); $validator = new HttpHeaderValidator($cache['source'], $cache['etag'], $cache['last-modified']); $validator->validate(); if ($validator->hasChanged()) { wp_schedule_single_event(time(), 'podlove_refetch_cached_image', [$cache['source'], $cache['filename']]); } } $time = PHP_Timer::stop(); \Podlove\Log::get()->addInfo(sprintf('Finished validating %d images in %s', count($cache_files), PHP_Timer::secondsToTimeString($time))); }
public function testPersistentResourceSimulation() { PHP_Timer::start(); $provider = new FFmpegOutputProvider('ffmpeg', true); $provider->setMovieFile(self::$moviePath); $provider->getOutput(); $provider = clone $provider; $provider->getOutput(); $provider = clone $provider; $provider->getOutput(); $elapsed = PHP_Timer::stop(); PHP_Timer::start(); $provider = new FFmpegOutputProvider('ffmpeg', false); $provider->setMovieFile(self::$moviePath); $provider->getOutput(); $provider = clone $provider; $provider->getOutput(); $provider = clone $provider; $provider->getOutput(); $elapsed1 = PHP_Timer::stop(); $this->assertGreaterThan($elapsed, $elapsed1, 'Persistent resource simulation should be faster'); }
/** * Runs a test and collects its result in a TestResult instance. * Executes before/after hooks coming from traits. * * @param \PHPUnit_Framework_TestResult $result * @return \PHPUnit_Framework_TestResult */ public final function run(\PHPUnit_Framework_TestResult $result = null) { $this->testResult = $result; $result->startTest($this); foreach ($this->hooks as $hook) { if (method_exists($this, $hook . 'Start')) { $this->{$hook . 'Start'}(); } } $status = self::STATUS_PENDING; $time = 0; $e = null; if (!$this->ignored) { \PHP_Timer::start(); try { $this->test(); $status = self::STATUS_OK; } catch (\PHPUnit_Framework_AssertionFailedError $e) { $status = self::STATUS_FAIL; } catch (\PHPUnit_Framework_Exception $e) { $status = self::STATUS_ERROR; } catch (\Throwable $e) { $e = new \PHPUnit_Framework_ExceptionWrapper($e); $status = self::STATUS_ERROR; } catch (\Exception $e) { $e = new \PHPUnit_Framework_ExceptionWrapper($e); $status = self::STATUS_ERROR; } $time = \PHP_Timer::stop(); } foreach (array_reverse($this->hooks) as $hook) { if (method_exists($this, $hook . 'End')) { $this->{$hook . 'End'}($status, $time, $e); } } $result->endTest($this, $time); return $result; }
/** * * Compares two propel objects and notifies the PHPUnit / Kaltura's listeners * @param BaseObject $outputReference * @param BaseObject $newResult * @return array<> $newErrors, if the objects are equal */ public function comparePropelObjectsByFields($outputReference, $newResult, $validErrorFields) { //Gets the data peer of the object (used to geting all the obejct feilds) $dataPeer = $outputReference->getPeer(); $outputReferenceId = $outputReference->getId(); $newResultId = $newResult->getId(); //Gets all object feilds $fields = call_user_func(array($dataPeer, "getFieldNames"), BasePeer::TYPE_PHPNAME); $newErrors = array(); //Create the xml elements by all fields and their values foreach ($fields as $field) { PHP_Timer::start(); //If the field is in the valid failure list then we skip him if (in_array($field, $validErrorFields)) { continue; } else { $expectedValue = $outputReference->getByName($field); $actualValue = $newResult->getByName($field); //if this is an array we need to change it to a string $this->compareOnField($field, $actualValue, $expectedValue, "assertEquals"); } } return $newErrors; }
/** * Runs a TestCase. * * @param PHPUnit_Framework_Test $test */ public function run(PHPUnit_Framework_Test $test) { PHPUnit_Framework_Assert::resetCount(); $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_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) { $linesToBeCovered = PHPUnit_Util_Test::getLinesToBeCovered(get_class($test), $test->getName(false)); $linesToBeUsed = PHPUnit_Util_Test::getLinesToBeUsed(get_class($test), $test->getName(false)); } try { $this->codeCoverage->stop($append, $linesToBeCovered, $linesToBeUsed); } catch (PHP_CodeCoverage_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 (PHPUnit_Framework_InvalidCoversTargetException $cce) { $this->addFailure($test, new PHPUnit_Framework_InvalidCoversTargetError($cce->getMessage()), $time); } catch (PHP_CodeCoverage_Exception $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); }
/** * Runs a TestCase. * * @param PHPUnit_Framework_Test $test */ public function run(PHPUnit_Framework_Test $test) { PHPUnit_Framework_Assert::resetCount(); $error = FALSE; $failure = FALSE; $incomplete = FALSE; $skipped = FALSE; $this->startTest($test); $errorHandlerSet = FALSE; if ($this->convertErrorsToExceptions) { $oldErrorHandler = set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'), E_ALL | E_STRICT); if ($oldErrorHandler === NULL) { $errorHandlerSet = TRUE; } else { restore_error_handler(); } } if (self::$xdebugLoaded === NULL) { self::$xdebugLoaded = extension_loaded('xdebug'); self::$useXdebug = self::$xdebugLoaded; } $useXdebug = self::$useXdebug && $this->collectCodeCoverageInformation && !$test instanceof PHPUnit_Extensions_SeleniumTestCase && !$test instanceof PHPUnit_Framework_Warning; if ($useXdebug) { $this->codeCoverage->start($test); } PHP_Timer::start(); try { $test->runBare(); } catch (PHPUnit_Framework_AssertionFailedError $e) { $failure = TRUE; if ($e instanceof PHPUnit_Framework_IncompleteTestError) { $incomplete = TRUE; } else { if ($e instanceof PHPUnit_Framework_SkippedTestError) { $skipped = TRUE; } } } catch (Exception $e) { $error = TRUE; } $time = PHP_Timer::stop(); $test->addToAssertionCount(PHPUnit_Framework_Assert::getCount()); if ($this->strictMode && $test->getNumAssertions() == 0) { $incomplete = TRUE; } if ($useXdebug) { $data = $this->codeCoverage->stop(FALSE); if (!$incomplete && !$skipped) { if ($this->collectRawCodeCoverageInformation) { $this->rawCodeCoverageInformation[] = $data; } else { $filterGroups = array('DEFAULT', 'TESTS'); if (!defined('PHPUNIT_TESTSUITE')) { $filterGroups[] = 'PHPUNIT'; } $this->codeCoverage->append($data, $test, $filterGroups); } } unset($data); } if ($errorHandlerSet === TRUE) { restore_error_handler(); } if ($error === TRUE) { $this->addError($test, $e, $time); } else { if ($failure === TRUE) { $this->addFailure($test, $e, $time); } else { if ($this->strictMode && $test->getNumAssertions() == 0) { $this->addFailure($test, new PHPUnit_Framework_IncompleteTestError('This test did not perform any assertions'), $time); } } } $this->endTest($test, $time); }
/** * Runs a test and collects its result in a TestResult instance. * * @param PHPUnit_Framework_TestResult $result * @param array $options * @return PHPUnit_Framework_TestResult */ public function run(PHPUnit_Framework_TestResult $result = NULL, array $options = array()) { if (!class_exists('PEAR_RunTest', FALSE)) { throw new PHPUnit_Framework_Exception('Class PEAR_RunTest not found.'); } if (isset($GLOBALS['_PEAR_destructor_object_list']) && is_array($GLOBALS['_PEAR_destructor_object_list']) && !empty($GLOBALS['_PEAR_destructor_object_list'])) { $pearDestructorObjectListCount = count($GLOBALS['_PEAR_destructor_object_list']); } else { $pearDestructorObjectListCount = 0; } if ($result === NULL) { $result = new PHPUnit_Framework_TestResult(); } $coverage = $result->getCollectCodeCoverageInformation(); $options = array_merge($options, $this->options); if (!isset($options['include_path'])) { $options['include_path'] = get_include_path(); } if ($coverage) { $options['coverage'] = TRUE; } else { $options['coverage'] = FALSE; } $currentErrorReporting = error_reporting(E_ERROR | E_WARNING | E_PARSE); $runner = new PEAR_RunTest(new PHPUnit_Extensions_PhptTestCase_Logger(), $options); if ($coverage) { $runner->xdebug_loaded = TRUE; } else { $runner->xdebug_loaded = FALSE; } $result->startTest($this); PHP_Timer::start(); $buffer = $runner->run($this->filename, $options); $time = PHP_Timer::stop(); error_reporting($currentErrorReporting); $base = basename($this->filename); $path = dirname($this->filename); $coverageFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.xdebug', $base); $diffFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.diff', $base); $expFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.exp', $base); $logFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.log', $base); $outFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.out', $base); $phpFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.php', $base); if (is_object($buffer) && $buffer instanceof PEAR_Error) { $result->addError($this, new PHPUnit_Framework_Exception($buffer->getMessage()), $time); } else { if ($buffer == 'SKIPPED') { $result->addFailure($this, new PHPUnit_Framework_SkippedTestError(), 0); } else { if ($buffer != 'PASSED') { $expContent = file_get_contents($expFile); $outContent = file_get_contents($outFile); $result->addFailure($this, new PHPUnit_Framework_ComparisonFailure($expContent, $outContent, $expContent, $outContent), $time); } } } foreach (array($diffFile, $expFile, $logFile, $phpFile, $outFile) as $file) { if (file_exists($file)) { unlink($file); } } if ($coverage && file_exists($coverageFile)) { eval('$coverageData = ' . file_get_contents($coverageFile) . ';'); unset($coverageData[$phpFile]); $result->getCodeCoverage()->append($coverageData, $this); unlink($coverageFile); } $result->endTest($this, $time); // Do not invoke PEAR's destructor mechanism for PHP 4 // as it raises an E_STRICT. if ($pearDestructorObjectListCount == 0) { unset($GLOBALS['_PEAR_destructor_object_list']); } else { $count = count($GLOBALS['_PEAR_destructor_object_list']) - $pearDestructorObjectListCount; for ($i = 0; $i < $count; $i++) { array_pop($GLOBALS['_PEAR_destructor_object_list']); } } return $result; }
/** * Runs a TestCase. * * @param PHPUnit_Framework_Test $test */ public function run(PHPUnit_Framework_Test $test) { PHPUnit_Framework_Assert::resetCount(); $error = false; $failure = false; $incomplete = false; $risky = false; $skipped = false; $this->startTest($test); $errorHandlerSet = false; if ($this->convertErrorsToExceptions) { $oldErrorHandler = set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'), E_ALL | E_STRICT); if ($oldErrorHandler === null) { $errorHandlerSet = true; } else { restore_error_handler(); } } $collectCodeCoverage = $this->codeCoverage !== null && !$test instanceof PHPUnit_Extensions_SeleniumTestCase && !$test instanceof PHPUnit_Framework_Warning; if ($collectCodeCoverage) { // We need to blacklist test source files when no whitelist is used. if (!$this->codeCoverage->filter()->hasWhitelist()) { $classes = $this->getHierarchy(get_class($test), true); foreach ($classes as $class) { $this->codeCoverage->filter()->addFileToBlacklist($class->getFileName()); } } $this->codeCoverage->start($test); } PHP_Timer::start(); try { if (!$test instanceof PHPUnit_Framework_Warning && $this->beStrictAboutTestSize && 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(array($test, 'runBare'), array(), $_timeout); } else { $test->runBare(); } } 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_Exception $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 ($this->beStrictAboutTestsThatDoNotTestAnything && $test->getNumAssertions() == 0) { $risky = true; } if ($collectCodeCoverage) { $append = !$risky && !$incomplete && !$skipped; $linesToBeCovered = array(); $linesToBeUsed = array(); if ($append && $test instanceof PHPUnit_Framework_TestCase) { $linesToBeCovered = PHPUnit_Util_Test::getLinesToBeCovered(get_class($test), $test->getName(false)); $linesToBeUsed = PHPUnit_Util_Test::getLinesToBeUsed(get_class($test), $test->getName(false)); } try { $this->codeCoverage->stop($append, $linesToBeCovered, $linesToBeUsed); } catch (PHP_CodeCoverage_Exception_UnintentionallyCoveredCode $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 (PHPUnit_Framework_InvalidCoversTargetException $cce) { $this->addFailure($test, new PHPUnit_Framework_InvalidCoversTargetError($cce->getMessage()), $time); } catch (PHP_CodeCoverage_Exception $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 ($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); }
/** * Runs a TestCase. * * @param PHPUnit_Framework_Test $test */ public function run(PHPUnit_Framework_Test $test) { PHPUnit_Framework_Assert::resetCount(); $error = FALSE; $failure = FALSE; $incomplete = FALSE; $skipped = FALSE; $this->startTest($test); $errorHandlerSet = FALSE; if ($this->convertErrorsToExceptions) { $oldErrorHandler = set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'), E_ALL | E_STRICT); if ($oldErrorHandler === NULL) { $errorHandlerSet = TRUE; } else { restore_error_handler(); } } if (self::$xdebugLoaded === NULL) { self::$xdebugLoaded = extension_loaded('xdebug'); self::$useXdebug = self::$xdebugLoaded; } $useXdebug = self::$useXdebug && $this->codeCoverage !== NULL && !$test instanceof PHPUnit_Extensions_SeleniumTestCase && !$test instanceof PHPUnit_Framework_Warning; if ($useXdebug) { $this->codeCoverage->start($test); } PHP_Timer::start(); try { $test->runBare(); } catch (PHPUnit_Framework_AssertionFailedError $e) { $failure = TRUE; if ($e instanceof PHPUnit_Framework_IncompleteTestError) { $incomplete = TRUE; } else { if ($e instanceof PHPUnit_Framework_SkippedTestError) { $skipped = TRUE; } } } catch (Exception $e) { $error = TRUE; } $time = PHP_Timer::stop(); $test->addToAssertionCount(PHPUnit_Framework_Assert::getCount()); if ($this->strictMode && $test->getNumAssertions() == 0) { $incomplete = TRUE; } if ($useXdebug) { try { $this->codeCoverage->stop(!$incomplete && !$skipped); } catch (PHP_CodeCoverage_Exception $cce) { $error = TRUE; if (!isset($e)) { $e = $cce; } } } if ($errorHandlerSet === TRUE) { restore_error_handler(); } if ($error === TRUE) { $this->addError($test, $e, $time); } else { if ($failure === TRUE) { $this->addFailure($test, $e, $time); } else { if ($this->strictMode && $test->getNumAssertions() == 0) { $this->addFailure($test, new PHPUnit_Framework_IncompleteTestError('This test did not perform any assertions'), $time); } else { if ($this->strictMode && $test->hasOutput()) { $this->addFailure($test, new PHPUnit_Framework_OutputError(sprintf('This test printed output: %s', $test->getActualOutput())), $time); } } } } $this->endTest($test, $time); }
/** * This runs the actual test, and is intended to be run against the testsuite * that is output by the 'suite' function **/ public function run(\PHPUnit_Framework_TestResult $result = NULL) { if ($result === NULL) { $result = new \PHPUnit_Framework_TestResult(); } $this->_result = $result; $this->_result->startTest($this); \PHPUnit_Framework_Assert::resetCount(); \PHP_Timer::start(); $stop_time = NULL; try { //Run the before callbacks if ($this->_setup_callback !== null) { call_user_func($this->_setup_callback, $this); } foreach ($this->_before_chain as $current_before) { if ($current_before !== null) { call_user_func($current_before, $this); } } // Part of the shim to allow us to use PHPUnit's runTest method $refClass = new \ReflectionClass($this); for ($i = 0; $i < 20; $i++) { $refClass = $refClass->getParentClass(); if ($refClass->getName() === 'PHPUnit_Framework_TestCase') { break; } } $refProperty = $refClass->getProperty('name'); $refProperty->setAccessible(true); $refProperty->setValue($this, 'run_current_test'); $this->runTest(); $this->verifyMockObjects(); $this->addToAssertionCount(\PHPUnit_Framework_Assert::getCount()); if (!$this->assertion_count) { $this->markTestIncomplete('This spec does not have any expectation'); } //Run the after callbacks if ($this->_teardown_callback !== null) { call_user_func($this->_teardown_callback, $this); } } catch (\PHPUnit_Framework_AssertionFailedError $e) { $stop_time = \PHP_Timer::stop(); $this->_result->addFailure($this, $e, $stop_time); } catch (\Esperance\Error $e) { $stop_time = \PHP_Timer::stop(); $this->_result->addFailure($this, new \PHPUnit_Framework_AssertionFailedError($e->getMessage(), $e->getCode(), $e), $stop_time); } catch (\Exception $e) { $stop_time = \PHP_Timer::stop(); $this->_result->addError($this, $e, $stop_time); } if ($stop_time === NULL) { $stop_time = \PHP_Timer::stop(); } $this->_result->endTest($this, $stop_time); return $this->_result; }
/** * Run the test * * @param \PHPUnit_Framework_TestResult $result * @param Zept $zept * @return \PHPUnit_Framework_TestResult */ private function doRun(\PHPUnit_Framework_TestResult $result, Zept $zept) { $time = 0; \PHP_Timer::start(); try { $jobResult = $this->codeRunner->run($zept->getZephirCode(), $zept->getPhpCode(), $this->silent); $time = \PHP_Timer::stop(); $assertion = $zept->getAssertion(); \PHPUnit_Framework_Assert::$assertion($this->cleanString($zept->getExpected()), $this->cleanString($jobResult['stdout'])); } catch (\Exception $exception) { $result->addError($this, $exception, $time); } catch (\Throwable $throwable) { $result->addError($this, $throwable, $time); } $result->endTest($this, $time); $result->flushListeners(); return $result; }
* * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <*****@*****.**> * @author Marc McIntyre <*****@*****.**> * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ error_reporting(E_ALL | E_STRICT); // Optionally use PHP_Timer to print time/memory stats for the run. // Note that the reports are the ones who actually print the data // as they decide if it is ok to print this data to screen. @(include_once 'PHP/Timer.php'); if (class_exists('PHP_Timer', false) === true) { PHP_Timer::start(); } if (is_file(dirname(__FILE__) . '/../CodeSniffer/CLI.php') === true) { include_once dirname(__FILE__) . '/../CodeSniffer/CLI.php'; } else { //include_once 'PHP/CodeSniffer/CLI.php'; include_once 'CodeSniffer/CLI.php'; } $phpcs = new PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); $numErrors = $phpcs->process(); if ($numErrors === 0) { exit(0); } else { exit(1); }
/** * @covers PHP_Timer::start * @covers PHP_Timer::stop */ public function testStartStop() { PHP_Timer::start(); $this->assertInternalType('float', PHP_Timer::stop()); }
/** * Runs a test and collects its result in a TestResult instance. * * @param PHPUnit_Framework_TestResult $result * @return PHPUnit_Framework_TestResult */ public function run(PHPUnit_Framework_TestResult $result = null) { $sections = $this->parse(); $code = $this->render($sections['FILE']); if ($result === null) { $result = new PHPUnit_Framework_TestResult(); } $skip = false; $time = 0; $settings = $this->settings; $result->startTest($this); if (isset($sections['INI'])) { $settings = array_merge($settings, $this->parseIniSection($sections['INI'])); } // Redirects STDERR to STDOUT $this->phpUtil->setUseStderrRedirection(true); if (isset($sections['SKIPIF'])) { $jobResult = $this->phpUtil->runJob($sections['SKIPIF'], $settings); if (!strncasecmp('skip', ltrim($jobResult['stdout']), 4)) { if (preg_match('/^\\s*skip\\s*(.+)\\s*/i', $jobResult['stdout'], $message)) { $message = substr($message[1], 2); } else { $message = ''; } $result->addFailure($this, new PHPUnit_Framework_SkippedTestError($message), 0); $skip = true; } } if (!$skip) { PHP_Timer::start(); $jobResult = $this->phpUtil->runJob($code, $settings); $time = PHP_Timer::stop(); try { $this->assertPhptExpectation($sections, $jobResult['stdout']); } catch (PHPUnit_Framework_AssertionFailedError $e) { $result->addFailure($this, $e, $time); } catch (Throwable $t) { $result->addError($this, $t, $time); } catch (Exception $e) { $result->addError($this, $e, $time); } if (isset($sections['CLEAN'])) { $cleanCode = $this->render($sections['CLEAN']); $this->phpUtil->runJob($cleanCode, $this->settings); } } $result->endTest($this, $time); return $result; }
/** * First runs PHPUnit and then post processes the generated coverage data * to calculate the change coverage. * * @param array(string) $argv The raw command line arguments. * * @return integer */ public function run(array $argv) { $this->printVersionString(); try { $this->handleArguments($argv); $arguments = $this->extractPhpunitArguments($argv); } catch (InvalidArgumentException $e) { $exception = $e->getMessage(); $arguments = array('--help'); } $phpunit = new PHP_ChangeCoverage_PHPUnit($this->phpunitBinary); $phpunit->run($arguments); if ($phpunit->isHelp()) { $this->writeLine(); $this->writeLine(); $this->writeLine('Additional options added by PHP_ChangeCoverage'); $this->writeLine(); $this->writeLine(' --temp-dir Temporary directory for generated runtime data.'); $this->writeLine(' --phpunit-binary Optional path to phpunit\'s binary.'); $this->writeLine(' --modified-since Cover only lines that were changed since this date.'); $this->writeLine(' This option accepts textual date expressions.'); $this->writeLine(' --unmodified-as-covered Mark all unmodified lines as covered.'); if (isset($exception)) { $this->writeLine(); $this->writeLine($exception); return 2; } } else { if (file_exists($this->temporaryClover)) { PHP_Timer::start(); $report = $this->createCoverageReport(); $codeCoverage = $this->rebuildCoverageData($report); $this->writeCoverageClover($codeCoverage); $this->writeCoverageHtml($codeCoverage); PHP_Timer::stop(); $this->writeLine(PHP_Timer::resourceUsage()); unlink($this->temporaryClover); } } return $phpunit->getExitCode(); }
/** * Runs a TestCase. * * @param PHPUnit_Framework_Test $test */ public function run(PHPUnit_Framework_Test $test) { PHPUnit_Framework_Assert::resetCount(); $error = FALSE; $failure = FALSE; $incomplete = FALSE; $skipped = FALSE; $this->startTest($test); $errorHandlerSet = FALSE; if ($this->convertErrorsToExceptions) { $oldErrorHandler = set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'), E_ALL | E_STRICT); if ($oldErrorHandler === NULL) { $errorHandlerSet = TRUE; } else { restore_error_handler(); } } if (self::$xdebugLoaded === NULL) { self::$xdebugLoaded = extension_loaded('xdebug'); self::$useXdebug = self::$xdebugLoaded; } $useXdebug = self::$useXdebug && $this->codeCoverage !== NULL && !$test instanceof PHPUnit_Extensions_SeleniumTestCase && !$test instanceof PHPUnit_Framework_Warning; if ($useXdebug) { // We need to blacklist test source files when no whitelist is used. if (!$this->codeCoverage->filter()->hasWhitelist()) { $classes = PHPUnit_Util_Class::getHierarchy(get_class($test), TRUE); foreach ($classes as $class) { $this->codeCoverage->filter()->addFileToBlacklist($class->getFileName()); } } $this->codeCoverage->start($test); } PHP_Timer::start(); try { if (!$test instanceof PHPUnit_Framework_Warning && $this->strictMode && 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(array($test, 'runBare'), array(), $_timeout); } else { $test->runBare(); } } catch (PHPUnit_Framework_AssertionFailedError $e) { $failure = TRUE; if ($e instanceof PHPUnit_Framework_IncompleteTestError) { $incomplete = TRUE; } else { if ($e instanceof PHPUnit_Framework_SkippedTestError) { $skipped = TRUE; } } } catch (Exception $e) { $error = TRUE; } $time = PHP_Timer::stop(); $test->addToAssertionCount(PHPUnit_Framework_Assert::getCount()); if ($this->strictMode && $test->getNumAssertions() == 0) { $incomplete = TRUE; } if ($useXdebug) { try { $this->codeCoverage->stop(!$incomplete && !$skipped); } catch (PHP_CodeCoverage_Exception $cce) { $error = TRUE; if (!isset($e)) { $e = $cce; } } } if ($errorHandlerSet === TRUE) { restore_error_handler(); } if ($error === TRUE) { $this->addError($test, $e, $time); } else { if ($failure === TRUE) { $this->addFailure($test, $e, $time); } else { if ($this->strictMode && $test->getNumAssertions() == 0) { $this->addFailure($test, new PHPUnit_Framework_IncompleteTestError('This test did not perform any assertions'), $time); } else { if ($this->strictMode && $test->hasOutput()) { $this->addFailure($test, new PHPUnit_Framework_OutputError(sprintf('This test printed output: %s', $test->getActualOutput())), $time); } } } } $this->endTest($test, $time); }
/** * @param string $esHost * @param string $gameVersion * @param int $lastActiveTimestamp */ function main($esHost, $gameVersion, $lastActiveTimestamp) { $dsnList = mysqlDsnGenerator($gameVersion); $totalUserCount = 0; foreach ($dsnList as $mysqlOptions) { $userList = onShard($mysqlOptions, $lastActiveTimestamp); if (count($userList) === 0) { continue; } $totalUserCount += count($userList); PHP_Timer::start(); batchUpdateES($esHost, $gameVersion, $userList); appendLog('ES update[' . count($userList) . '] cost: ' . PHP_Timer::secondsToTimeString(PHP_Timer::stop())); } appendLog(sprintf('%s total user count [%d], from %s', PHP_Timer::resourceUsage(), $totalUserCount, date('Y/m/d H:i:s', $lastActiveTimestamp))); }
/** * Runs a test and collects its result in a TestResult instance. * * @param PHPUnit_Framework_TestResult $result * * @return PHPUnit_Framework_TestResult */ public function run(PHPUnit_Framework_TestResult $result = null) { $sections = $this->parse(); $code = $this->render($sections['FILE']); if ($result === null) { $result = new PHPUnit_Framework_TestResult(); } $skip = false; $xfail = false; $time = 0; $settings = $this->settings; $result->startTest($this); if (isset($sections['INI'])) { $settings = array_merge($settings, $this->parseIniSection($sections['INI'])); } if (isset($sections['ENV'])) { $env = $this->parseEnvSection($sections['ENV']); $this->phpUtil->setEnv($env); } // Redirects STDERR to STDOUT $this->phpUtil->setUseStderrRedirection(true); if ($result->enforcesTimeLimit()) { $this->phpUtil->setTimeout($result->getTimeoutForLargeTests()); } if (isset($sections['SKIPIF'])) { $jobResult = $this->phpUtil->runJob($sections['SKIPIF'], $settings); if (!strncasecmp('skip', ltrim($jobResult['stdout']), 4)) { if (preg_match('/^\\s*skip\\s*(.+)\\s*/i', $jobResult['stdout'], $message)) { $message = substr($message[1], 2); } else { $message = ''; } $result->addFailure($this, new PHPUnit_Framework_SkippedTestError($message), 0); $skip = true; } } if (isset($sections['XFAIL'])) { $xfail = trim($sections['XFAIL']); } if (!$skip) { if (isset($sections['STDIN'])) { $this->phpUtil->setStdin($sections['STDIN']); } if (isset($sections['ARGS'])) { $this->phpUtil->setArgs($sections['ARGS']); } PHP_Timer::start(); $jobResult = $this->phpUtil->runJob($code, $settings); $time = PHP_Timer::stop(); try { $this->assertPhptExpectation($sections, $jobResult['stdout']); } catch (PHPUnit_Framework_AssertionFailedError $e) { if ($xfail !== false) { $result->addFailure($this, new PHPUnit_Framework_IncompleteTestError($xfail, 0, $e), $time); } else { $result->addFailure($this, $e, $time); } } catch (Throwable $t) { $result->addError($this, $t, $time); } if ($result->allCompletelyImplemented() && $xfail !== false) { $result->addFailure($this, new PHPUnit_Framework_IncompleteTestError('XFAIL section but test passes'), $time); } $this->phpUtil->setStdin(''); $this->phpUtil->setArgs(''); if (isset($sections['CLEAN'])) { $cleanCode = $this->render($sections['CLEAN']); $this->phpUtil->runJob($cleanCode, $this->settings); } } $result->endTest($this, $time); return $result; }