/** * @param array $requestArguments * @param bool $failOnFailure * @return Response */ protected function fetchFrontendResponse(array $requestArguments, $failOnFailure = true) { if (!empty($requestArguments['url'])) { $requestUrl = '/' . ltrim($requestArguments['url'], '/'); } else { $requestUrl = '/?' . GeneralUtility::implodeArrayForUrl('', $requestArguments); } if (property_exists($this, 'instancePath')) { $instancePath = $this->instancePath; } else { $instancePath = ORIGINAL_ROOT . 'typo3temp/functional-' . substr(sha1(get_class($this)), 0, 7); } $arguments = array('documentRoot' => $instancePath, 'requestUrl' => 'http://localhost' . $requestUrl); $template = new \Text_Template(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Fixtures/Frontend/request.tpl'); $template->setVar(array('arguments' => var_export($arguments, true), 'originalRoot' => ORIGINAL_ROOT)); $php = \PHPUnit_Util_PHP::factory(); $response = $php->runJob($template->render()); $result = json_decode($response['stdout'], true); if ($result === null) { $this->fail('Frontend Response is empty'); } if ($failOnFailure && $result['status'] === Response::STATUS_Failure) { $this->fail('Frontend Response has failure:' . LF . $result['error']); } $response = new Response($result['status'], $result['content'], $result['error']); return $response; }
/** * @param PHP_CodeCoverage_Report_Node_File $node * @param string $file */ public function render(PHP_CodeCoverage_Report_Node_File $node, $file) { $template = new Text_Template($this->templatePath . 'file.html', '{{', '}}'); $template->setVar(array('items' => $this->renderItems($node), 'lines' => $this->renderSource($node))); $this->setCommonTemplateVariables($template, $node); $template->renderTo($file); }
/** * @param FileNode $node * @param string $file */ public function render(FileNode $node, $file) { $template = new \Text_Template($this->templatePath . 'file.html', '{{', '}}'); $template->setVar(['items' => $this->renderItems($node), 'lines' => $this->renderSource($node)]); $this->setCommonTemplateVariables($template, $node); $template->renderTo($file); }
/** * @param Release $release * @param bool $latest * * @return string */ private function renderRelease(Release $release, $latest = false) { $item = new \Text_Template(__DIR__ . '/../templates/item.html'); $manifest = ''; if (!empty($release->manifest())) { $manifest = sprintf(' class="phar" data-title="Manifest" data-content="<ul>%s</ul>" data-placement="bottom" data-html="true"', implode('', array_map(function ($item) { return '<li>' . $item . '</li>'; }, $release->manifest()))); } $item->setVar(['domain' => $this->domain(), 'package' => $release->package(), 'version' => $release->version(), 'date' => $release->date(), 'size' => $release->size(), 'sha256' => $release->sha256(), 'strongOpen' => $latest ? '<strong>' : '', 'strongClose' => $latest ? '</strong>' : '', 'manifest' => $manifest]); return $item->render(); }
/** * @param ReleaseCollection $releases */ public function render(ReleaseCollection $releases) { $feedTemplate = new \Text_Template(__DIR__ . '/../templates/feed.xml'); $feedItemTemplate = new \Text_Template(__DIR__ . '/../templates/item.xml'); $rdfList = ''; $rdfItems = ''; foreach ($releases->latestReleasesSortedByDate() as $release) { $rdfList .= sprintf(' <rdf:li rdf:resource="%s/%s-%s.phar"/>' . "\n", $this->domain(), $release->package(), $release->version()); $feedItemTemplate->setVar(['domain' => $this->domain(), 'package' => $release->package(), 'version' => $release->version(), 'date' => $release->date(), 'content' => '']); $rdfItems .= $feedItemTemplate->render(); } $feedTemplate->setVar(['items_list' => $rdfList, 'items' => $rdfItems, 'domain' => $this->domain(), 'email' => $this->email()]); $feedTemplate->renderTo($this->target()); }
/** * @param PrintResultEvent $printResultEvent * @throws \Codeception\Exception\ModuleRequireException */ public function resultPrintAfter(PrintResultEvent $printResultEvent) { if (count($this->failedIdentifiers) > 0) { $items = ''; $itemTemplate = new \Text_Template($this->config['templateFolder'] . 'Item.html'); foreach ($this->failedIdentifiers as $vars) { $itemTemplate->setVar($vars); $items .= $itemTemplate->render(); } $pageTemplate = new \Text_Template($this->config['templateFolder'] . 'Page.html'); $pageTemplate->setVar(array('items' => $items)); $reportPath = $this->fileSystemUtil->getFailImageDirectory() . 'index.html'; $pageTemplate->renderTo($reportPath); $printResultEvent->getPrinter()->write('Report has been created: ' . $reportPath . "\n"); } }
/** * @param Tombstone $tombstone * * @return string */ private function renderInvokers(Tombstone $tombstone) { $invokers = array(); foreach ($tombstone->getVampires() as $vampire) { $invokers[] = $vampire->getInvoker(); } $invokers = array_unique($invokers); $invokersString = ''; foreach ($invokers as $invoker) { $this->invokerTemplate->setVar(array('invoker' => $invoker ?: 'global scope')); $invokersString .= $this->invokerTemplate->render(); } return $invokersString; }
/** * parse a given template name with given hash of key-value pairs * * @param string $name * @param array $hash * @return string */ public static function getParsedTemplateByNameAndHash($name, array $hash = array()) { $tpl = new \Text_Template(self::getTemplateFileByName($name)); $tpl->setVar($hash); return $tpl->render(); }
/** * @param PHP_CodeCoverage_Report_HTML_Node_Directory $root * @param string $file * @param string $title */ protected function renderDashboard(PHP_CodeCoverage_Report_HTML_Node_Directory $root, $file, $title) { $classes = $this->classes($root); $template = new Text_Template(PHP_CodeCoverage_Report_HTML::$templatePath . 'dashboard.html'); $template->setVar(array('title' => $title, 'charset' => $this->options['charset'], 'date' => date('D M j G:i:s T Y', $_SERVER['REQUEST_TIME']), 'version' => '@package_version@', 'php_version' => PHP_VERSION, 'generator' => $this->options['generator'], 'least_tested_methods' => $this->leastTestedMethods($classes), 'top_project_risks' => $this->topProjectRisks($classes), 'cc_values' => $this->classComplexity($classes), 'ccd_values' => $this->classCoverageDistribution($classes), 'backlink' => basename(str_replace('.dashboard', '', $file)))); $template->renderTo($file); }
/** * Define constants after including files. */ function prepareTemplate(Text_Template $template) { $template->setVar(array('constants' => '')); $template->setVar(array('wp_constants' => PHPUnit_Util_GlobalState::getConstantsAsString())); parent::prepareTemplate($template); }
/** * Renders this node. * * @param string $target * @param string $title * @param string $charset * @param integer $lowUpperBound * @param integer $highLowerBound * @param string $generator */ public function render($target, $title, $charset = 'UTF-8', $lowUpperBound = 35, $highLowerBound = 70, $generator = '') { if ($this->yui) { $template = new Text_Template(PHP_CodeCoverage_Report_HTML::$templatePath . 'file.html'); $yuiTemplate = new Text_Template(PHP_CodeCoverage_Report_HTML::$templatePath . 'yui_item.js'); } else { $template = new Text_Template(PHP_CodeCoverage_Report_HTML::$templatePath . 'file_no_yui.html'); } $i = 1; $lines = ''; foreach ($this->codeLines as $line) { $css = ''; if (!isset($this->ignoredLines[$i]) && isset($this->executedLines[$i])) { $count = ''; // Array: Line is executable and was executed. // count(Array) = Number of tests that hit this line. if (is_array($this->executedLines[$i])) { $color = 'lineCov'; $numTests = count($this->executedLines[$i]); $count = sprintf('%8d', $numTests); if ($this->yui) { $buffer = ''; $testCSS = ''; foreach ($this->executedLines[$i] as $test) { switch ($test['status']) { case 0: $testCSS = ' class=\\"testPassed\\"'; break; case 1: case 2: $testCSS = ' class=\\"testIncomplete\\"'; break; case 3: $testCSS = ' class=\\"testFailure\\"'; break; case 4: $testCSS = ' class=\\"testError\\"'; break; default: $testCSS = ''; } $buffer .= sprintf('<li%s>%s</li>', $testCSS, addslashes(htmlspecialchars($test['id']))); } if ($numTests > 1) { $header = $numTests . ' tests cover'; } else { $header = '1 test covers'; } $header .= ' line ' . $i; $yuiTemplate->setVar(array('line' => $i, 'header' => $header, 'tests' => $buffer), FALSE); $this->yuiPanelJS .= $yuiTemplate->render(); } } else { if ($this->executedLines[$i] == -1) { $color = 'lineNoCov'; $count = sprintf('%8d', 0); } else { $color = 'lineDeadCode'; $count = ' '; } } $css = sprintf('<span class="%s"> %s : ', $color, $count); } $fillup = array_shift($this->codeLinesFillup); if ($fillup > 0) { $line .= str_repeat(' ', $fillup); } $lines .= sprintf('<span class="lineNum" id="container%d"><a name="%d"></a>' . '<a href="#%d" id="line%d">%8d</a> </span>%s%s%s' . "\n", $i, $i, $i, $i, $i, !empty($css) ? $css : ' : ', !$this->highlight ? htmlspecialchars($line) : $line, !empty($css) ? '</span>' : ''); $i++; } $items = ''; foreach ($this->classes as $className => $classData) { if ($classData['executedLines'] == $classData['executableLines']) { $numTestedClasses = 1; $testedClassesPercent = 100; } else { $numTestedClasses = 0; $testedClassesPercent = 0; } $numMethods = 0; $numTestedMethods = 0; foreach ($classData['methods'] as $method) { if ($method['executableLines'] > 0) { $numMethods++; if ($method['executedLines'] == $method['executableLines']) { $numTestedMethods++; } } } $items .= $this->doRenderItem(array('name' => sprintf('<b><a href="#%d">%s</a></b>', $classData['startLine'], $className), 'numClasses' => 1, 'numTestedClasses' => $numTestedClasses, 'testedClassesPercent' => sprintf('%01.2f', $testedClassesPercent), 'numMethods' => $numMethods, 'numTestedMethods' => $numTestedMethods, 'testedMethodsPercent' => PHP_CodeCoverage_Util::percent($numTestedMethods, $numMethods, TRUE), 'numExecutableLines' => $classData['executableLines'], 'numExecutedLines' => $classData['executedLines'], 'executedLinesPercent' => PHP_CodeCoverage_Util::percent($classData['executedLines'], $classData['executableLines'], TRUE)), $lowUpperBound, $highLowerBound); foreach ($classData['methods'] as $methodData) { if ($methodData['executableLines'] > 0) { if ($methodData['executedLines'] == $methodData['executableLines']) { $numTestedMethods = 1; $testedMethodsPercent = 100; } else { $numTestedMethods = 0; $testedMethodsPercent = 0; } $items .= $this->doRenderItem(array('name' => sprintf(' <a href="#%d">%s</a>', $methodData['startLine'], htmlspecialchars($methodData['signature'])), 'numClasses' => '', 'numTestedClasses' => '', 'testedClassesPercent' => '', 'numMethods' => 1, 'numTestedMethods' => $numTestedMethods, 'testedMethodsPercent' => sprintf('%01.2f', $testedMethodsPercent), 'numExecutableLines' => $methodData['executableLines'], 'numExecutedLines' => $methodData['executedLines'], 'executedLinesPercent' => PHP_CodeCoverage_Util::percent($methodData['executedLines'], $methodData['executableLines'], TRUE), 'crap' => PHP_CodeCoverage_Util::crap($methodData['ccn'], PHP_CodeCoverage_Util::percent($methodData['executedLines'], $methodData['executableLines']))), $lowUpperBound, $highLowerBound, 'method_item.html'); } } } $this->setTemplateVars($template, $title, $charset, $generator); $template->setVar(array('lines' => $lines, 'total_item' => $this->renderTotalItem($lowUpperBound, $highLowerBound, FALSE), 'items' => $items, 'yuiPanelJS' => $this->yuiPanelJS)); $cleanId = PHP_CodeCoverage_Util::getSafeFilename($this->getId()); $template->renderTo($target . $cleanId . '.html'); $this->yuiPanelJS = ''; $this->executedLines = array(); }
/** * we need process isolation to prevent "headers already sent" * * but process isolation triggers another error, because phpunit tries to load all previously included files * where throw_exception.php should not be called * * however disabled globalState prevents constants in bootstrap.php to be loaded * * that is why we need this ugly hack method * * @param \Text_Template $template */ protected function prepareTemplate(\Text_Template $template) { $template->setVar(array('iniSettings' => '', 'constants' => '', 'included_files' => '', 'globals' => '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], TRUE) . ";\n")); }
/** * Runs the test case and collects the results in a TestResult object. * If no TestResult object is passed a new one will be created. * * @param PHPUnit_Framework_TestResult $result * @return PHPUnit_Framework_TestResult * @throws InvalidArgumentException */ public function run(PHPUnit_Framework_TestResult $result = NULL) { if ($result === NULL) { $result = $this->createResult(); } $this->setExpectedExceptionFromAnnotation(); $this->setUseErrorHandlerFromAnnotation(); $this->setUseOutputBufferingFromAnnotation(); if ($this->useErrorHandler !== NULL) { $oldErrorHandlerSetting = $result->getConvertErrorsToExceptions(); $result->convertErrorsToExceptions($this->useErrorHandler); } $this->result = $result; if (!empty($this->dependencies) && !$this->inIsolation) { $className = get_class($this); $passed = $this->result->passed(); $passedKeys = array_keys($passed); $numKeys = count($passedKeys); for ($i = 0; $i < $numKeys; $i++) { $pos = strpos($passedKeys[$i], ' with data set'); if ($pos !== FALSE) { $passedKeys[$i] = substr($passedKeys[$i], 0, $pos); } } $passedKeys = array_flip(array_unique($passedKeys)); foreach ($this->dependencies as $dependency) { if (strpos($dependency, '::') === FALSE) { $dependency = $className . '::' . $dependency; } if (!isset($passedKeys[$dependency])) { $result->addError($this, new PHPUnit_Framework_SkippedTestError(sprintf('This test depends on "%s" to pass.', $dependency)), 0); return; } else { if (isset($passed[$dependency])) { $this->dependencyInput[] = $passed[$dependency]; } else { $this->dependencyInput[] = NULL; } } } } if ($this->runTestInSeparateProcess === TRUE && $this->inIsolation !== TRUE && !$this instanceof PHPUnit_Extensions_SeleniumTestCase && !$this instanceof PHPUnit_Extensions_PhptTestCase) { $class = new ReflectionClass($this); $template = new Text_Template(sprintf('%s%sProcess%sTestCaseMethod.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)); if ($this->preserveGlobalState) { $constants = PHPUnit_Util_GlobalState::getConstantsAsString(); $globals = PHPUnit_Util_GlobalState::getGlobalsAsString(); $includedFiles = PHPUnit_Util_GlobalState::getIncludedFilesAsString(); } else { $constants = ''; $globals = ''; $includedFiles = ''; } if ($result->getCollectCodeCoverageInformation()) { $coverage = 'TRUE'; } else { $coverage = 'FALSE'; } $data = addcslashes(serialize($this->data), "'"); $dependencyInput = addcslashes(serialize($this->dependencyInput), "'"); $includePath = addslashes(get_include_path()); $template->setVar(array('filename' => $class->getFileName(), 'className' => $class->getName(), 'methodName' => $this->name, 'collectCodeCoverageInformation' => $coverage, 'data' => $data, 'dataName' => $this->dataName, 'dependencyInput' => $dependencyInput, 'constants' => $constants, 'globals' => $globals, 'include_path' => $includePath, 'included_files' => $includedFiles)); $this->prepareTemplate($template); PHPUnit_Util_PHP::runJob($template->render(), $this, $result); } else { $result->run($this); } if ($this->useErrorHandler !== NULL) { $result->convertErrorsToExceptions($oldErrorHandlerSetting); } $this->result = NULL; return $result; }
/** * Define constants after requires/includes * * See http://kpayne.me/2012/07/02/phpunit-process-isolation-and-constant-already-defined/ * for more details * * @param \Text_Template $template */ public function prepareTemplate(\Text_Template $template) { $template->setVar(['globals' => '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = \'' . $GLOBALS['__PHPUNIT_BOOTSTRAP'] . '\';']); parent::prepareTemplate($template); }
/** * Generates the class' source. * * @return mixed */ public function generate() { $methods = ''; foreach ($this->findTestedMethods() as $method) { $methodTemplate = new Text_Template(sprintf('%s%sTemplate%sMethod.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)); $methodTemplate->setVar(array('methodName' => $method)); $methods .= $methodTemplate->render(); } $classTemplate = new Text_Template(sprintf('%s%sTemplate%sClass.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)); $classTemplate->setVar(array('className' => $this->outClassName['fullyQualifiedClassName'], 'methods' => $methods, 'date' => date('Y-m-d'), 'time' => date('H:i:s'))); return $classTemplate->render(); }
/** * @param string $templateDir * @param string $className * @param string $methodName * @param string $modifier * @param string $arguments_decl * @param string $arguments_call * @param string $reference * @param boolean $static * @return string */ protected static function generateMockedMethodDefinition($templateDir, $className, $methodName, $modifier = 'public', $arguments_decl = '', $arguments_call = '', $reference = '', $static = FALSE) { if ($static) { $template = new Text_Template($templateDir . 'mocked_static_method.tpl'); } else { $template = new Text_Template($templateDir . 'mocked_object_method.tpl'); } $template->setVar(array('arguments_decl' => $arguments_decl, 'arguments_call' => $arguments_call, 'arguments_count' => !empty($arguments_call) ? count(explode(',', $arguments_call)) : 0, 'class_name' => $className, 'method_name' => $methodName, 'modifier' => $modifier, 'reference' => $reference)); return $template->render(); }
/** * Runs the test case and collects the results in a TestResult object. * If no TestResult object is passed a new one will be created. * * @param PHPUnit_Framework_TestResult $result * @return PHPUnit_Framework_TestResult * @throws PHPUnit_Framework_Exception */ public function run(PHPUnit_Framework_TestResult $result = NULL) { if ($result === NULL) { $result = $this->createResult(); } if (!$this instanceof PHPUnit_Framework_Warning) { $this->setTestResultObject($result); $this->setUseErrorHandlerFromAnnotation(); $this->setUseOutputBufferingFromAnnotation(); } if ($this->useErrorHandler !== NULL) { $oldErrorHandlerSetting = $result->getConvertErrorsToExceptions(); $result->convertErrorsToExceptions($this->useErrorHandler); } if (!$this->handleDependencies()) { return; } if ($this->runTestInSeparateProcess === TRUE && $this->inIsolation !== TRUE && !$this instanceof PHPUnit_Extensions_SeleniumTestCase && !$this instanceof PHPUnit_Extensions_PhptTestCase) { $class = new ReflectionClass($this); $template = new Text_Template(sprintf('%s%sProcess%sTestCaseMethod.tpl', __DIR__, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)); if ($this->preserveGlobalState) { $constants = PHPUnit_Util_GlobalState::getConstantsAsString(); $globals = PHPUnit_Util_GlobalState::getGlobalsAsString(); $includedFiles = PHPUnit_Util_GlobalState::getIncludedFilesAsString(); } else { $constants = ''; $globals = ''; $includedFiles = ''; } if ($result->getCollectCodeCoverageInformation()) { $coverage = 'TRUE'; } else { $coverage = 'FALSE'; } if ($result->isStrict()) { $strict = 'TRUE'; } else { $strict = 'FALSE'; } $data = var_export(serialize($this->data), TRUE); $dependencyInput = var_export(serialize($this->dependencyInput), TRUE); $includePath = var_export(get_include_path(), TRUE); // must do these fixes because TestCaseMethod.tpl has unserialize('{data}') in it, and we can't break BC // the lines above used to use addcslashes() rather than var_export(), which breaks null byte escape sequences $data = "'." . $data . ".'"; $dependencyInput = "'." . $dependencyInput . ".'"; $includePath = "'." . $includePath . ".'"; $template->setVar(array('filename' => $class->getFileName(), 'className' => $class->getName(), 'methodName' => $this->name, 'collectCodeCoverageInformation' => $coverage, 'data' => $data, 'dataName' => $this->dataName, 'dependencyInput' => $dependencyInput, 'constants' => $constants, 'globals' => $globals, 'include_path' => $includePath, 'included_files' => $includedFiles, 'strict' => $strict)); $this->prepareTemplate($template); $php = PHPUnit_Util_PHP::factory(); $php->runJob($template->render(), $this, $result); } else { $result->run($this); } if ($this->useErrorHandler !== NULL) { $result->convertErrorsToExceptions($oldErrorHandlerSetting); } $this->result = NULL; return $result; }
/** * Runs the test case and collects the results in a TestResult object. * If no TestResult object is passed a new one will be created. * * @param PHPUnit_Framework_TestResult $result * @return PHPUnit_Framework_TestResult * @throws InvalidArgumentException */ public function run(PHPUnit_Framework_TestResult $result = NULL) { if ($result === NULL) { $result = $this->createResult(); } $this->result = $result; $this->setExpectedExceptionFromAnnotation(); $this->setUseErrorHandlerFromAnnotation(); $this->setUseOutputBufferingFromAnnotation(); if ($this->useErrorHandler !== NULL) { $oldErrorHandlerSetting = $result->getConvertErrorsToExceptions(); $result->convertErrorsToExceptions($this->useErrorHandler); } if (!$this->handleDependencies()) { return; } if ($this->runTestInSeparateProcess === TRUE && $this->inIsolation !== TRUE && !$this instanceof PHPUnit_Extensions_SeleniumTestCase && !$this instanceof PHPUnit_Extensions_PhptTestCase) { $class = new ReflectionClass($this); $template = new Text_Template( sprintf( '%s%sProcess%sTestCaseMethod.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR ) ); if ($this->preserveGlobalState) { $constants = PHPUnit_Util_GlobalState::getConstantsAsString(); $globals = PHPUnit_Util_GlobalState::getGlobalsAsString(); $includedFiles = PHPUnit_Util_GlobalState::getIncludedFilesAsString(); } else { $constants = ''; $globals = ''; $includedFiles = ''; } if ($result->getCollectCodeCoverageInformation()) { $coverage = 'TRUE'; } else { $coverage = 'FALSE'; } if ($result->isStrict()) { $strict = 'TRUE'; } else { $strict = 'FALSE'; } $data = addcslashes(serialize($this->data), "'"); $dependencyInput = addcslashes( serialize($this->dependencyInput), "'" ); $includePath = addslashes(get_include_path()); $template->setVar( array( 'filename' => $class->getFileName(), 'className' => $class->getName(), 'methodName' => $this->name, 'collectCodeCoverageInformation' => $coverage, 'data' => $data, 'dataName' => $this->dataName, 'dependencyInput' => $dependencyInput, 'constants' => $constants, 'globals' => $globals, 'include_path' => $includePath, 'included_files' => $includedFiles, 'strict' => $strict ) ); $this->prepareTemplate($template); PHPUnit_Util_PHP::runJob($template->render(), $this, $result); } else { $result->run($this); } if ($this->useErrorHandler !== NULL) { $result->convertErrorsToExceptions($oldErrorHandlerSetting); } $this->result = NULL; return $result; }
/** * {@inheritdoc} */ protected function prepareTemplate(\Text_Template $template) { $bootstrap_globals = ''; // Fix missing bootstrap.php when $preserveGlobalState is FALSE. // @see https://github.com/sebastianbergmann/phpunit/pull/797 $bootstrap_globals .= '$__PHPUNIT_BOOTSTRAP = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], TRUE) . ";\n"; // Avoid repetitive test namespace discoveries to improve performance. // @see /core/tests/bootstrap.php $bootstrap_globals .= '$namespaces = ' . var_export($GLOBALS['namespaces'], TRUE) . ";\n"; $template->setVar(array('constants' => '', 'included_files' => '', 'globals' => $bootstrap_globals)); }
/** * @param string $templateDir * @param string $className * @param string $methodName * @param bool $cloneArguments * @param string $modifier * @param string $arguments_decl * @param string $arguments_call * @param string $reference * @param bool $callOriginalMethods * @param bool $static * @return string */ protected function generateMockedMethodDefinition($templateDir, $className, $methodName, $cloneArguments = true, $modifier = 'public', $arguments_decl = '', $arguments_call = '', $reference = '', $callOriginalMethods = false, $static = false) { if ($static) { $templateFile = 'mocked_static_method.tpl'; } else { $templateFile = sprintf('%s_method.tpl', $callOriginalMethods ? 'proxied' : 'mocked'); } $template = new Text_Template($templateDir . $templateFile); $template->setVar(array('arguments_decl' => $arguments_decl, 'arguments_call' => $arguments_call, 'arguments_count' => !empty($arguments_call) ? count(explode(',', $arguments_call)) : 0, 'class_name' => $className, 'method_name' => $methodName, 'modifier' => $modifier, 'reference' => $reference, 'clone_arguments' => $cloneArguments ? 'TRUE' : 'FALSE')); return $template->render(); }
/** * Generates the test class' source. * * @param boolean $verbose * @return mixed */ public function generate($verbose = FALSE) { $class = new ReflectionClass( $this->inClassName['fullyQualifiedClassName'] ); $methods = ''; $incompleteMethods = ''; foreach ($class->getMethods() as $method) { if (!$method->isConstructor() && !$method->isAbstract() && $method->isPublic() && $method->getDeclaringClass()->getName() == $this->inClassName['fullyQualifiedClassName']) { $assertAnnotationFound = FALSE; if (preg_match_all('/@assert(.*)$/Um', $method->getDocComment(), $annotations)) { foreach ($annotations[1] as $annotation) { if (preg_match('/\((.*)\)\s+([^\s]*)\s+(.*)/', $annotation, $matches)) { switch ($matches[2]) { case '==': { $assertion = 'Equals'; } break; case '!=': { $assertion = 'NotEquals'; } break; case '===': { $assertion = 'Same'; } break; case '!==': { $assertion = 'NotSame'; } break; case '>': { $assertion = 'GreaterThan'; } break; case '>=': { $assertion = 'GreaterThanOrEqual'; } break; case '<': { $assertion = 'LessThan'; } break; case '<=': { $assertion = 'LessThanOrEqual'; } break; case 'throws': { $assertion = 'exception'; } break; default: { throw new PHPUnit_Framework_Exception( sprintf( 'Token "%s" could not be parsed in @assert annotation.', $matches[2] ) ); } } if ($assertion == 'exception') { $template = 'TestMethodException'; } else if ($assertion == 'Equals' && strtolower($matches[3]) == 'true') { $assertion = 'True'; $template = 'TestMethodBool'; } else if ($assertion == 'NotEquals' && strtolower($matches[3]) == 'true') { $assertion = 'False'; $template = 'TestMethodBool'; } else if ($assertion == 'Equals' && strtolower($matches[3]) == 'false') { $assertion = 'False'; $template = 'TestMethodBool'; } else if ($assertion == 'NotEquals' && strtolower($matches[3]) == 'false') { $assertion = 'True'; $template = 'TestMethodBool'; } else { $template = 'TestMethod'; } if ($method->isStatic()) { $template .= 'Static'; } $methodTemplate = new Text_Template( sprintf( '%s%sTemplate%s%s.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $template ) ); $origMethodName = $method->getName(); $methodName = ucfirst($origMethodName); if (isset($this->methodNameCounter[$methodName])) { $this->methodNameCounter[$methodName]++; } else { $this->methodNameCounter[$methodName] = 1; } if ($this->methodNameCounter[$methodName] > 1) { $methodName .= $this->methodNameCounter[$methodName]; } $methodTemplate->setVar( array( 'annotation' => trim($annotation), 'arguments' => $matches[1], 'assertion' => isset($assertion) ? $assertion : '', 'expected' => $matches[3], 'origMethodName' => $origMethodName, 'className' => $this->inClassName['fullyQualifiedClassName'], 'methodName' => $methodName ) ); $methods .= $methodTemplate->render(); $assertAnnotationFound = TRUE; } } } if (!$assertAnnotationFound) { $methodTemplate = new Text_Template( sprintf( '%s%sTemplate%sIncompleteTestMethod.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR ) ); $methodTemplate->setVar( array( 'methodName' => ucfirst($method->getName()) ) ); $incompleteMethods .= $methodTemplate->render(); } } } $classTemplate = new Text_Template( sprintf( '%s%sTemplate%sTestClass.tpl', dirname(__FILE__), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR ) ); if ($this->inSourceFile != '<internal>') { $requireClassFile = sprintf( "\n\nrequire_once '%s';", $this->inSourceFile ); } else { $requireClassFile = ''; } if ($this->outClassName['namespace'] != '') { $namespace = "\nnamespace " . $this->outClassName['namespace'] . ";\n"; } else { $namespace = ''; } $classTemplate->setVar( array( 'namespace' => $namespace, 'namespaceSeparator' => !empty($namespace) ? '\\' : '', 'className' => $this->inClassName['className'], 'testClassName' => $this->outClassName['className'], 'requireClassFile' => $requireClassFile, 'methods' => $methods . $incompleteMethods, 'date' => date('Y-m-d'), 'time' => date('H:i:s') ) ); if (!$verbose) { return $classTemplate->render(); } else { return array( 'code' => $classTemplate->render(), 'incomplete' => empty($methods) ); } }
/** * Cleans and returns a line. Removes php tag added to make highlight-string * work * * @param unknown_type $traceline * @param unknown_type $relativePosition * @param unknown_type $style * @return Ambigous <string, mixed> */ protected function getLine($traceline, $relativePosition, $style = 'normal') { $line = new \Text_Template($this->templateDir() . '/Line.html.dist'); $code = str_replace(array('<span style="color: #0000BB"><?php </span>', '<code>', '</code>'), '', highlight_string('<?php ' . Backtrace::readLine($traceline['file'], $traceline['line'] + $relativePosition), true)); $code = preg_replace('/\\n/', '', $code); $code = preg_replace('/<span style="color: #0000BB"><\\?php (.*)(<\\/span>+?)/', '$1', $code); $line->setVar(array('line' => $traceline['line'] + $relativePosition, 'class' => $style, 'code' => ' ' . $code)); return $line->render(); }
protected function prepareTemplate(\Text_Template $template) { $template->setFile(__DIR__ . '/TestCaseMethod.tpl'); }
/** * Handler for 'end run' event. * */ protected function endRun() { $scenariosTemplate = new Text_Template($this->templatePath . 'scenarios.html'); $scenariosTemplate->setVar(array('scenarios' => $this->scenarios, 'successfulScenarios' => $this->successful, 'failedScenarios' => $this->failed, 'skippedScenarios' => $this->skipped, 'incompleteScenarios' => $this->incomplete)); $this->write($scenariosTemplate->render()); }
protected function getCoverageBar($percent) { $level = $this->getColorLevel($percent); $template = new Text_Template($this->templatePath . 'coverage_bar.html', '{{', '}}'); $template->setVar(array('level' => $level, 'percent' => sprintf('%.2F', $percent))); return $template->render(); }
/** * @param string $wsdlFile * @param string $className * @param array $methods * @param array $options * * @return string * @throws PHPUnit_Framework_MockObject_RuntimeException */ public function generateClassFromWsdl($wsdlFile, $className, array $methods = array(), array $options = array()) { if ($this->soapLoaded === null) { $this->soapLoaded = extension_loaded('soap'); } if ($this->soapLoaded) { $options = array_merge($options, array('cache_wsdl' => WSDL_CACHE_NONE)); $client = new SoapClient($wsdlFile, $options); $_methods = array_unique($client->__getFunctions()); unset($client); sort($_methods); $templateDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR; $methodTemplate = new Text_Template($templateDir . 'wsdl_method.tpl'); $methodsBuffer = ''; foreach ($_methods as $method) { $nameStart = strpos($method, ' ') + 1; $nameEnd = strpos($method, '('); $name = substr($method, $nameStart, $nameEnd - $nameStart); if (empty($methods) || in_array($name, $methods)) { $args = explode(',', substr($method, $nameEnd + 1, strpos($method, ')') - $nameEnd - 1)); $numArgs = count($args); for ($i = 0; $i < $numArgs; $i++) { $args[$i] = substr($args[$i], strpos($args[$i], '$')); } $methodTemplate->setVar(array('method_name' => $name, 'arguments' => join(', ', $args))); $methodsBuffer .= $methodTemplate->render(); } } $optionsBuffer = 'array('; foreach ($options as $key => $value) { $optionsBuffer .= $key . ' => ' . $value; } $optionsBuffer .= ')'; $classTemplate = new Text_Template($templateDir . 'wsdl_class.tpl'); $namespace = ''; if (strpos($className, '\\') !== false) { $parts = explode('\\', $className); $className = array_pop($parts); $namespace = 'namespace ' . join('\\', $parts) . ';' . "\n\n"; } $classTemplate->setVar(array('namespace' => $namespace, 'class_name' => $className, 'wsdl' => $wsdlFile, 'options' => $optionsBuffer, 'methods' => $methodsBuffer)); return $classTemplate->render(); } else { throw new PHPUnit_Framework_MockObject_RuntimeException('The SOAP extension is required to generate a mock object ' . 'from WSDL.'); } }
/** * @param int $pageId * @param int $languageId * @param int $backendUserId * @param int $workspaceId * @param bool $failOnFailure * @return Response */ protected function getFrontendResponse($pageId, $languageId = 0, $backendUserId = 0, $workspaceId = 0, $failOnFailure = TRUE) { $pageId = (int) $pageId; $languageId = (int) $languageId; $additionalParameter = ''; if (!empty($backendUserId)) { $additionalParameter .= '&backendUserId=' . (int) $backendUserId; } if (!empty($workspaceId)) { $additionalParameter .= '&workspaceId=' . (int) $workspaceId; } $arguments = array('documentRoot' => $this->instancePath, 'requestUrl' => 'http://localhost/?id=' . $pageId . '&L=' . $languageId . $additionalParameter); $template = new \Text_Template(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Fixtures/Frontend/request.tpl'); $template->setVar(array('arguments' => var_export($arguments, TRUE), 'originalRoot' => ORIGINAL_ROOT)); $php = \PHPUnit_Util_PHP::factory(); $response = $php->runJob($template->render()); $result = json_decode($response['stdout'], TRUE); if ($result === FALSE) { $this->fail('Frontend Response is empty'); } if ($failOnFailure && $result['status'] === Response::STATUS_Failure) { $this->fail('Frontend Response has failure:' . LF . $result['error']); } $response = new Response($result['status'], $result['content'], $result['error']); return $response; }
/** * @param Text_Template $template * @param string $title * @param PHP_CodeCoverage_Report_Node $node */ protected function setCommonTemplateVariables(Text_Template $template, $title, PHP_CodeCoverage_Report_Node $node = NULL) { $link = ''; if ($node !== NULL) { $path = $node->getPathAsArray(); foreach ($path as $step) { $link .= sprintf('%s<a href="%s.html">%s</a>', !empty($link) ? '/' : '', $step->getId(), $step->getName()); } } $template->setVar(array('title' => $title, 'link' => $link, 'charset' => $this->charset, 'date' => $this->date, 'version' => '1.1.2', 'php_version' => PHP_VERSION, 'generator' => $this->generator, 'low_upper_bound' => $this->lowUpperBound, 'high_lower_bound' => $this->highLowerBound)); }
/** * Runs the test case and collects the results in a TestResult object. * If no TestResult object is passed a new one will be created. * * @param PHPUnit_Framework_TestResult $result * @return PHPUnit_Framework_TestResult * @throws PHPUnit_Framework_Exception */ public function run(PHPUnit_Framework_TestResult $result = null) { if ($result === null) { $result = $this->createResult(); } if (!$this instanceof PHPUnit_Framework_Warning) { $this->setTestResultObject($result); $this->setUseErrorHandlerFromAnnotation(); } if ($this->useErrorHandler !== null) { $oldErrorHandlerSetting = $result->getConvertErrorsToExceptions(); $result->convertErrorsToExceptions($this->useErrorHandler); } if (!$this instanceof PHPUnit_Framework_Warning && !$this->handleDependencies()) { return; } if ($this->runTestInSeparateProcess === true && $this->inIsolation !== true && !$this instanceof PHPUnit_Extensions_SeleniumTestCase && !$this instanceof PHPUnit_Extensions_PhptTestCase) { $class = new ReflectionClass($this); $template = new Text_Template(__DIR__ . '/../Util/PHP/Template/TestCaseMethod.tpl'); if ($this->preserveGlobalState) { $constants = PHPUnit_Util_GlobalState::getConstantsAsString(); $globals = PHPUnit_Util_GlobalState::getGlobalsAsString(); $includedFiles = PHPUnit_Util_GlobalState::getIncludedFilesAsString(); $iniSettings = PHPUnit_Util_GlobalState::getIniSettingsAsString(); } else { $constants = ''; if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) { $globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], true) . ";\n"; } else { $globals = ''; } $includedFiles = ''; $iniSettings = ''; } $coverage = $result->getCollectCodeCoverageInformation() ? 'true' : 'false'; $isStrictAboutTestsThatDoNotTestAnything = $result->isStrictAboutTestsThatDoNotTestAnything() ? 'true' : 'false'; $isStrictAboutOutputDuringTests = $result->isStrictAboutOutputDuringTests() ? 'true' : 'false'; $isStrictAboutTestSize = $result->isStrictAboutTestSize() ? 'true' : 'false'; $isStrictAboutTodoAnnotatedTests = $result->isStrictAboutTodoAnnotatedTests() ? 'true' : 'false'; if (defined('PHPUNIT_COMPOSER_INSTALL')) { $composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true); } else { $composerAutoload = '\'\''; } if (defined('__PHPUNIT_PHAR__')) { $phar = var_export(__PHPUNIT_PHAR__, true); } else { $phar = '\'\''; } $data = var_export(serialize($this->data), true); $dataName = var_export($this->dataName, true); $dependencyInput = var_export(serialize($this->dependencyInput), true); $includePath = var_export(get_include_path(), true); // must do these fixes because TestCaseMethod.tpl has unserialize('{data}') in it, and we can't break BC // the lines above used to use addcslashes() rather than var_export(), which breaks null byte escape sequences $data = "'." . $data . ".'"; $dataName = "'.(" . $dataName . ").'"; $dependencyInput = "'." . $dependencyInput . ".'"; $includePath = "'." . $includePath . ".'"; $template->setVar(array('composerAutoload' => $composerAutoload, 'phar' => $phar, 'filename' => $class->getFileName(), 'className' => $class->getName(), 'methodName' => $this->name, 'collectCodeCoverageInformation' => $coverage, 'data' => $data, 'dataName' => $dataName, 'dependencyInput' => $dependencyInput, 'constants' => $constants, 'globals' => $globals, 'include_path' => $includePath, 'included_files' => $includedFiles, 'iniSettings' => $iniSettings, 'isStrictAboutTestsThatDoNotTestAnything' => $isStrictAboutTestsThatDoNotTestAnything, 'isStrictAboutOutputDuringTests' => $isStrictAboutOutputDuringTests, 'isStrictAboutTestSize' => $isStrictAboutTestSize, 'isStrictAboutTodoAnnotatedTests' => $isStrictAboutTodoAnnotatedTests)); $this->prepareTemplate($template); $php = PHPUnit_Util_PHP::factory(); $php->runTestJob($template->render(), $this, $result); } else { $result->run($this); } if ($this->useErrorHandler !== null) { $result->convertErrorsToExceptions($oldErrorHandlerSetting); } $this->result = null; return $result; }
#!/usr/bin/env php <?php require dirname(__DIR__) . '/PHPUnit/Autoload.php'; $buffer = ''; $class = new ReflectionClass('PHPUnit_Framework_Assert'); $methods = array(); foreach ($class->getMethods() as $method) { $docblock = $method->getDocComment(); $name = $method->getName(); if (strpos($name, 'assert') === 0 || strpos($docblock, '@return PHPUnit_Framework_Constraint') !== FALSE) { $methods[$name] = array('class' => 'PHPUnit_Framework_Assert', 'docblock' => $docblock, 'sigDecl' => str_replace(array('= false', '= true'), array('= FALSE', '= TRUE'), PHPUnit_Util_Class::getMethodParameters($method)), 'sigCall' => PHPUnit_Util_Class::getMethodParameters($method, TRUE)); } } $class = new ReflectionClass('PHPUnit_Framework_TestCase'); foreach ($class->getMethods() as $method) { $docblock = $method->getDocComment(); $name = $method->getName(); if (strpos($docblock, '@return PHPUnit_Framework_MockObject_Matcher') !== FALSE || strpos($docblock, '@return PHPUnit_Framework_MockObject_Stub') !== FALSE) { $methods[$name] = array('class' => 'PHPUnit_Framework_TestCase', 'docblock' => $docblock, 'sigDecl' => str_replace(array('= false', '= true'), array('= FALSE', '= TRUE'), PHPUnit_Util_Class::getMethodParameters($method)), 'sigCall' => PHPUnit_Util_Class::getMethodParameters($method, TRUE)); } } ksort($methods); foreach ($methods as $name => $data) { $buffer .= sprintf("\n\n%s\nfunction %s(%s)\n{\n return call_user_func_array(\n '%s::%s',\n func_get_args()\n );\n}", str_replace(' ', '', $data['docblock']), $name, $data['sigDecl'], $data['class'], $name, $data['sigCall']); } $template = new Text_Template(dirname(__DIR__) . '/PHPUnit/Framework/Assert/Functions.php.in'); $template->setVar(array('functions' => $buffer)); $template->renderTo(dirname(__DIR__) . '/PHPUnit/Framework/Assert/Functions.php');