public function testHandleEvent() { $this->if($adapter = new atoum\test\adapter())->and($adapter->extension_loaded = true)->and($adapter->exec = function ($command) { switch ($command) { case 'git log -1 --pretty=format:\'{"id":"%H","author_name":"%aN","author_email":"%ae","committer_name":"%cN","committer_email":"%ce","message":"%s"}\'': return '{"id":"7282ea7620b45fcba0f9d3bfd484ab146aba2bd0","author_name":"mageekguy","author_email":"*****@*****.**","comitter_name":"mageekguy","comitter_email":"*****@*****.**"}'; case 'git rev-parse --abbrev-ref HEAD': return 'master'; default: return null; } })->and($report = new testedClass($sourceDir = uniqid(), $token = '51bb597d202b4', $adapter))->and($score = new \mock\mageekguy\atoum\score())->and($coverage = new \mock\mageekguy\atoum\score\coverage())->and($writer = new \mock\mageekguy\atoum\writers\http())->and($writer->getMockController()->writeAsynchronousReport = function () use($writer) { return $writer; })->then->when(function () use($report, $writer) { $report->addWriter($writer)->handleEvent(atoum\runner::runStop, new \mageekguy\atoum\runner()); })->mock($writer)->call('writeAsynchronousReport')->withArguments($report)->once()->if($adapter->date = '2013-05-13 10:00:00 +0000')->and($adapter->file_get_contents = '<?php')->and($observable = new \mock\mageekguy\atoum\runner())->and($observable->getMockController()->getScore = $score)->and($score->getMockController()->getCoverage = $coverage)->and($coverage->getMockController()->getClasses = array())->and($filepath = join(DIRECTORY_SEPARATOR, array(__DIR__, 'coveralls', 'resources', '1.json')))->and($report = new testedClass($sourceDir, $token, $adapter))->and($report->addWriter($writer))->then->object($report->handleEvent(atoum\runner::runStop, $observable))->isIdenticalTo($report)->castToString($report)->isEqualToContentsOfFile($filepath)->mock($writer)->call('writeAsynchronousReport')->withArguments($report)->once()->if($coverage->getMockController()->getClasses = array())->and($classController = new mock\controller())->and($classController->disableMethodChecking())->and($classController->__construct = function () { })->and($classController->getName = $className = 'bar')->and($classController->getFileName = $classFile = 'foo/bar.php')->and($classController->getTraits = array())->and($classController->getStartLine = 1)->and($classController->getEndLine = 12)->and($class = new \mock\reflectionClass(uniqid(), $classController))->and($methodController = new mock\controller())->and($methodController->__construct = function () { })->and($methodController->getName = $methodName = 'baz')->and($methodController->isAbstract = false)->and($methodController->getFileName = $classFile)->and($methodController->getDeclaringClass = $class)->and($methodController->getStartLine = 4)->and($methodController->getEndLine = 8)->and($classController->getMethods = array(new \mock\reflectionMethod($className, $methodName, $methodController)))->and($coverage->getMockController()->getClasses = array($className => $classFile, 'foo' => 'bar/foo.php'))->and($xdebugData = array($classFile => array(3 => 1, 4 => 1, 5 => -2, 6 => 0, 7 => -1, 8 => 1, 9 => 1)))->and($filepath = join(DIRECTORY_SEPARATOR, array(__DIR__, 'coveralls', 'resources', '2' . (defined('PHP_WINDOWS_VERSION_MAJOR') === true ? '-windows' : '') . '.json')))->and($coverage->setReflectionClassFactory(function () use($class) { return $class; }))->and($coverage->addXdebugDataForTest($this, $xdebugData))->then->object($report->handleEvent(atoum\runner::runStop, $observable))->isIdenticalTo($report)->castToString($report)->isEqualToContentsOfFile($filepath)->mock($writer)->call('writeAsynchronousReport')->withArguments($report)->twice()->if($finder = function () use(&$branch) { return 'feature'; })->and($report->setBranchFinder($finder))->and($filepath = join(DIRECTORY_SEPARATOR, array(__DIR__, 'coveralls', 'resources', '3' . (defined('PHP_WINDOWS_VERSION_MAJOR') === true ? '-windows' : '') . '.json')))->then->object($report->handleEvent(atoum\runner::runStop, $observable))->isIdenticalTo($report)->castToString($report)->isEqualToContentsOfFile($filepath)->mock($writer)->call('writeAsynchronousReport')->withArguments($report)->thrice()->if($report->setBranchFinder(function () use(&$branch) { return $branch = uniqid(); }))->and($report->handleEvent(atoum\runner::runStop, $observable))->then->castToString($report)->contains('"branch":"' . $branch . '"')->if($report->setBranchFinder(function () { }))->and($report->handleEvent(atoum\runner::runStop, $observable))->then->castToString($report)->notContains('"branch":')->if($report->setBranchFinder(function () { return ''; }))->and($report->handleEvent(atoum\runner::runStop, $observable))->then->castToString($report)->notContains('"branch":'); }
public function testGetMockedClassCodeForUnknownClass() { $this->if($generator = new testedClass())->and($adapter = new atoum\test\adapter())->and($adapter->class_exists = false)->and($generator->setAdapter($adapter))->then->string($generator->getMockedClassCode($unknownClass = uniqid()))->isEqualTo('namespace mock {' . PHP_EOL . 'final class ' . $unknownClass . ' implements \\mageekguy\\atoum\\mock\\aggregator' . PHP_EOL . '{' . PHP_EOL . $this->getMockControllerMethods() . "\t" . 'public function __construct(\\mageekguy\\atoum\\mock\\controller $mockController = null)' . PHP_EOL . "\t" . '{' . PHP_EOL . "\t\t" . 'if ($mockController === null)' . PHP_EOL . "\t\t" . '{' . PHP_EOL . "\t\t\t" . '$mockController = \\mageekguy\\atoum\\mock\\controller::get();' . PHP_EOL . "\t\t" . '}' . PHP_EOL . "\t\t" . 'if ($mockController !== null)' . PHP_EOL . "\t\t" . '{' . PHP_EOL . "\t\t\t" . '$this->setMockController($mockController);' . PHP_EOL . "\t\t" . '}' . PHP_EOL . "\t\t" . '$this->getMockController()->disableMethodChecking();' . PHP_EOL . "\t\t" . 'if (isset($this->getMockController()->__construct) === true)' . PHP_EOL . "\t\t" . '{' . PHP_EOL . "\t\t\t" . '$this->getMockController()->invoke(\'__construct\', func_get_args());' . PHP_EOL . "\t\t" . '}' . PHP_EOL . "\t" . '}' . PHP_EOL . "\t" . 'public function __call($methodName, $arguments)' . PHP_EOL . "\t" . '{' . PHP_EOL . "\t\t" . 'if (isset($this->getMockController()->{$methodName}) === true)' . PHP_EOL . "\t\t" . '{' . PHP_EOL . "\t\t\t" . '$return = $this->getMockController()->invoke($methodName, $arguments);' . PHP_EOL . "\t\t\t" . 'return $return;' . PHP_EOL . "\t\t" . '}' . PHP_EOL . "\t\t" . 'else' . PHP_EOL . "\t\t" . '{' . PHP_EOL . "\t\t\t" . '$this->getMockController()->addCall($methodName, $arguments);' . PHP_EOL . "\t\t" . '}' . PHP_EOL . "\t" . '}' . PHP_EOL . "\t" . 'public static function getMockedMethods()' . PHP_EOL . "\t" . '{' . PHP_EOL . "\t\t" . 'return ' . var_export(array('__call'), true) . ';' . PHP_EOL . "\t" . '}' . PHP_EOL . '}' . PHP_EOL . '}')->if($unknownClass = __NAMESPACE__ . '\\dummy')->and($generator->generate($unknownClass))->and($mockedUnknownClass = '\\mock\\' . $unknownClass)->and($dummy = new $mockedUnknownClass())->and($dummyController = new atoum\mock\controller())->and($dummyController->notControlNextNewMock())->and($calls = new \mock\mageekguy\atoum\test\adapter\calls())->and($dummyController->setCalls($calls))->and($dummyController->control($dummy))->then->when(function () use($dummy) { $dummy->bar(); })->mock($calls)->call('addCall')->withArguments(new atoum\test\adapter\call('bar', array(), new decorators\addClass($dummy)))->once()->when(function () use($dummy) { $dummy->bar(); })->mock($calls)->call('addCall')->withArguments(new atoum\test\adapter\call('bar', array(), new decorators\addClass($dummy)))->twice(); }
public function testHandleEvent() { $this->if($adapter = new atoum\test\adapter())->if($adapter->extension_loaded = true)->and($report = new testedClass($adapter))->and($score = new \mock\mageekguy\atoum\score())->and($coverage = new \mock\mageekguy\atoum\score\coverage())->and($writer = new \mock\mageekguy\atoum\writers\file())->and($writer->getMockController()->write = $writer)->then->when(function () use($report, $writer) { $report->addWriter($writer)->handleEvent(atoum\runner::runStop, new \mageekguy\atoum\runner()); })->mock($writer)->call('writeAsynchronousReport')->withArguments($report)->once()->and($adapter->time = 762476400)->and($adapter->uniqid = 'foo')->and($observable = new \mock\mageekguy\atoum\runner())->and($observable->getMockController()->getScore = $score)->and($score->getMockController()->getCoverage = $coverage)->and($coverage->getMockController()->getClasses = array())->and($filepath = join(DIRECTORY_SEPARATOR, array(__DIR__, 'clover', 'resources', '1.xml')))->and($report = new testedClass($adapter))->then->object($report->handleEvent(atoum\runner::runStop, $observable))->isIdenticalTo($report)->castToString($report)->isEqualToContentsOfFile($filepath)->if($coverage->getMockController()->getClasses = array())->and($classController = new mock\controller())->and($classController->disableMethodChecking())->and($classController->__construct = function () { })->and($classController->getName = $className = 'bar')->and($classController->getFileName = $classFile = 'foo/bar.php')->and($classController->getTraits = array())->and($classController->getStartLine = 1)->and($classController->getEndLine = 12)->and($class = new \mock\reflectionClass(uniqid(), $classController))->and($methodController = new mock\controller())->and($methodController->__construct = function () { })->and($methodController->getName = $methodName = 'baz')->and($methodController->isAbstract = false)->and($methodController->getFileName = $classFile)->and($methodController->getDeclaringClass = $class)->and($methodController->getStartLine = 4)->and($methodController->getEndLine = 8)->and($classController->getMethods = array(new \mock\reflectionMethod($className, $methodName, $methodController)))->and($coverage->getMockController()->getClasses = array($className => $classFile, 'foo' => 'bar/foo.php'))->and($xdebugData = array($classFile => array(3 => 1, 4 => 1, 5 => 1, 6 => 0, 7 => 1, 8 => 1, 9 => 1)))->and($filepath = join(DIRECTORY_SEPARATOR, array(__DIR__, 'clover', 'resources', '2.xml')))->and($coverage->setReflectionClassFactory(function () use($class) { return $class; }))->and($coverage->addXdebugDataForTest($this, $xdebugData))->then->object($report->handleEvent(atoum\runner::runStop, $observable))->isIdenticalTo($report)->castToString($report)->isEqualToContentsOfFile($filepath); }
protected function getNextMockController() { $controller = mock\controller::get(false); if ($controller === null) { $controller = new mock\controller(); } return $controller; }
public function test__toString() { $this->if($scoreCoverage = new score\coverage())->and($score = new \mock\mageekguy\atoum\runner\score())->and($score->getMockController()->getCoverage = function () use($scoreCoverage) { return $scoreCoverage; })->and($runner = new atoum\runner())->and($runner->setScore($score))->and($defaultField = new tests\coverage\cli())->and($customField = new tests\coverage\cli())->and($customField->setTitlePrompt($titlePrompt = new prompt(uniqid())))->and($customField->setTitleColorizer($titleColorizer = new colorizer(uniqid(), uniqid())))->and($customField->setClassPrompt($classPrompt = new prompt(uniqid())))->and($customField->setMethodPrompt($methodPrompt = new prompt(uniqid())))->and($customField->setCoverageColorizer($coverageColorizer = new colorizer(uniqid(), uniqid())))->and($customField->setLocale($locale = new locale()))->then->castToString($defaultField)->isEmpty()->castToString($customField)->isEmpty()->if($defaultField->handleEvent(atoum\runner::runStart, $runner))->and($customField->handleEvent(atoum\runner::runStart, $runner))->then->castToString($defaultField)->isEmpty()->castToString($customField)->isEmpty()->if($defaultField->handleEvent(atoum\runner::runStop, $runner))->and($customField->handleEvent(atoum\runner::runStop, $runner))->then->castToString($defaultField)->isEmpty()->castToString($customField)->isEmpty()->if($classController = new mock\controller())->and($classController->disableMethodChecking())->and($classController->__construct = function () { })->and($classController->getName = function () use(&$className) { return $className; })->and($classController->getFileName = function () use(&$classFile) { return $classFile; })->and($classController->getTraits = array())->and($classController->getStartLine = 1)->and($classController->getEndLine = 12)->and($class = new \mock\reflectionClass(uniqid(), $classController))->and($methodController = new mock\controller())->and($methodController->__construct = function () { })->and($methodController->isAbstract = false)->and($methodController->getFileName = function () use(&$classFile) { return $classFile; })->and($methodController->getDeclaringClass = $class)->and($methodController->getName = function () use(&$methodName) { return $methodName; })->and($methodController->getStartLine = 6)->and($methodController->getEndLine = 8)->and($classController->getMethods = array(new \mock\reflectionMethod(uniqid(), uniqid(), $methodController)))->and($className = uniqid())->and($methodName = uniqid())->and($scoreCoverage->setReflectionClassFactory(function () use($class) { return $class; }))->and($scoreCoverage->addXdebugDataForTest($this, $xdebugData = array($classFile = uniqid() => array(5 => 1, 6 => 2, 7 => 3, 8 => 2, 9 => 1), uniqid() => array(5 => 2, 6 => 3, 7 => 4, 8 => 3, 9 => 2))))->and($defaultField = new tests\coverage\cli())->and($customField = new tests\coverage\cli())->and($customField->setTitlePrompt($titlePrompt = new prompt(uniqid())))->and($customField->setTitleColorizer($titleColorizer = new colorizer(uniqid(), uniqid())))->and($customField->setClassPrompt($classPrompt = new prompt(uniqid())))->and($customField->setMethodPrompt($methodPrompt = new prompt(uniqid())))->and($customField->setCoverageColorizer($coverageColorizer = new colorizer(uniqid(), uniqid())))->and($customField->setLocale($locale = new locale()))->then->castToString($defaultField)->isEmpty()->castToString($customField)->isEmpty()->if($defaultField->handleEvent(atoum\runner::runStart, $runner))->and($customField->handleEvent(atoum\runner::runStart, $runner))->then->castToString($defaultField)->isEmpty()->castToString($customField)->isEmpty()->if($defaultField->handleEvent(atoum\runner::runStop, $runner))->and($customField->handleEvent(atoum\runner::runStop, $runner))->then->castToString($defaultField)->isEqualTo($defaultField->getTitlePrompt() . sprintf($defaultField->getLocale()->_('Code coverage value: %3.2f%%'), $scoreCoverage->getValue() * 100) . PHP_EOL . $defaultField->getClassPrompt() . sprintf($defaultField->getLocale()->_('Class %s: %3.2f%%'), $className, $scoreCoverage->getValueForClass($className) * 100.0) . PHP_EOL . $defaultField->getMethodPrompt() . sprintf($defaultField->getLocale()->_('%s::%s(): %3.2f%%'), $className, $methodName, $scoreCoverage->getValueForMethod($className, $methodName) * 100.0) . PHP_EOL)->castToString($customField)->isEqualTo($titlePrompt . sprintf($locale->_('%s: %s'), $titleColorizer->colorize($locale->_('Code coverage value')), $coverageColorizer->colorize(sprintf('%3.2f%%', $scoreCoverage->getValue() * 100.0))) . PHP_EOL . $classPrompt . sprintf($locale->_('%s: %s'), $titleColorizer->colorize(sprintf($locale->_('Class %s'), $className)), $coverageColorizer->colorize(sprintf('%3.2f%%', $scoreCoverage->getValueForClass($className) * 100.0))) . PHP_EOL . $methodPrompt . sprintf($locale->_('%s: %s'), $titleColorizer->colorize(sprintf($locale->_('%s::%s()'), $className, $methodName)), $coverageColorizer->colorize(sprintf('%3.2f%%', $scoreCoverage->getValueForClass($className, $methodName) * 100.0))) . PHP_EOL)->if($defaultField->hideMethodsCoverageDetails())->and($defaultField->handleEvent(atoum\runner::runStop, $runner))->then->castToString($defaultField)->isEqualTo($defaultField->getTitlePrompt() . sprintf($defaultField->getLocale()->_('Code coverage value: %3.2f%%'), $scoreCoverage->getValue() * 100) . PHP_EOL . $defaultField->getClassPrompt() . sprintf($defaultField->getLocale()->_('Class %s: %3.2f%%'), $className, $scoreCoverage->getValueForClass($className) * 100.0) . PHP_EOL)->if($defaultField->hideClassesCoverageDetails())->and($defaultField->handleEvent(atoum\runner::runStop, $runner))->then->castToString($defaultField)->isEqualTo($defaultField->getTitlePrompt() . sprintf($defaultField->getLocale()->_('Code coverage value: %3.2f%%'), $scoreCoverage->getValue() * 100) . PHP_EOL)->if($customField->hideClassesCoverageDetails())->and($customField->handleEvent(atoum\runner::runStop, $runner))->then->castToString($customField)->isEqualTo($customField->getTitlePrompt() . sprintf($customField->getLocale()->_('Code coverage value: %3.2f%%'), $scoreCoverage->getValue() * 100) . PHP_EOL); }
public function testReset() { $this->given($linker = new testedClass())->and(controller::setLinker($linker))->then->if($linker->link($controller = new \mock\mageekguy\atoum\mock\controller(), $mock = new \mock\foo()))->then->object($linker->reset())->isIdenticalTo($linker)->variable($linker->getController($mock))->isNull()->variable($linker->getMock($controller))->isNull(); }
public function testGetIterator() { $this->if($iterator = new testedClass($controller = new mock\controller()))->then->object($iterator->getIterator())->isEqualTo(new \arrayIterator($iterator->getMethods()))->if($controller->control(new \mock\mageekguy\atoum\tests\units\mock\controller\foo()))->then->object($iterator->getIterator())->isEqualTo(new \arrayIterator($iterator->getMethods())); }
public function testGetCoverageForMethod() { $this->if($coverage = new testedClass())->then->array($coverage->getCoverageForClass(uniqid()))->isEmpty()->if($classController = new mock\controller())->and($classController->disableMethodChecking())->and($classController->__construct = function () { })->and($classController->getName = function () use(&$className) { return $className; })->and($classController->getFileName = function () use(&$classFile) { return $classFile; })->and($classController->getTraits = array())->and($classController->getStartLine = 1)->and($classController->getEndLine = 12)->and($class = new \mock\reflectionClass(uniqid(), $classController))->and($methodController = new mock\controller())->and($methodController->__construct = function () { })->and($methodController->getName = function () use(&$methodName) { return $methodName; })->and($methodController->isAbstract = false)->and($methodController->getFileName = function () use(&$classFile) { return $classFile; })->and($methodController->getDeclaringClass = function () use($class) { return $class; })->and($methodController->getStartLine = 4)->and($methodController->getEndLine = 8)->and($classController->getMethods = array(new \mock\reflectionMethod(uniqid(), uniqid(), $methodController)))->and($classFile = uniqid())->and($className = uniqid())->and($methodName = uniqid())->and($xdebugData = array($classFile => array(3 => -2, 4 => 1, 5 => -1, 6 => -1, 7 => -1, 8 => -2, 9 => -1), uniqid() => array(5 => 2, 6 => 3, 7 => 4, 8 => 3, 9 => 2)))->and($expected = array(4 => 1, 5 => -1, 6 => -1, 7 => -1, 8 => -2))->and($coverage = new testedClass())->and($coverage->setReflectionClassFactory(function () use($class) { return $class; }))->and($coverage->addXdebugDataForTest($this, $xdebugData))->then->array($coverage->getCoverageForMethod($className, $methodName))->isEqualTo($expected); }
public function runTestMethod($testMethod, array $tags = array()) { if ($this->methodIsIgnored($testMethod, $tags) === false) { $this->mockAutoloader->setMockGenerator($this->mockGenerator)->register(); set_error_handler(array($this, 'errorHandler')); ini_set('display_errors', 'stderr'); ini_set('log_errors', 'Off'); ini_set('log_errors_max_len', '0'); $this->currentMethod = $testMethod; $this->executeOnFailure = array(); $this->phpMocker->setDefaultNamespace($this->getTestedClassNamespace()); try { foreach ($this->getMethodPhpVersions($testMethod) as $phpVersion => $operator) { if (version_compare(phpversion(), $phpVersion, $operator) === false) { throw new test\exceptions\skip('PHP version ' . PHP_VERSION . ' is not ' . $operator . ' to ' . $phpVersion); } } foreach ($this->getMandatoryMethodExtensions($testMethod) as $mandatoryExtension) { try { call_user_func($this->phpExtensionFactory, $mandatoryExtension)->requireExtension(); } catch (atoum\php\exception $exception) { throw new test\exceptions\skip($exception->getMessage()); } } try { ob_start(); test\adapter::setStorage($this->testAdapterStorage); mock\controller::setLinker($this->mockControllerLinker); $this->testAdapterStorage->add(php\mocker::getAdapter()); $this->beforeTestMethod($this->currentMethod); $this->mockGenerator->testedClassIs($this->getTestedClassName()); try { $testedClass = new \reflectionClass($testedClassName = $this->getTestedClassName()); } catch (\exception $exception) { throw new exceptions\runtime('Tested class \'' . $testedClassName . '\' does not exist for test class \'' . $this->getClass() . '\''); } if ($testedClass->isAbstract() === true) { $testedClass = new \reflectionClass($testedClassName = $this->mockGenerator->getDefaultNamespace() . '\\' . $testedClassName); } $this->factoryBuilder->build($testedClass, $instance)->addToAssertionManager($this->assertionManager, 'newTestedInstance', function () use($testedClass) { throw new exceptions\runtime('Tested class ' . $testedClass->getName() . ' has no constructor or its constructor has at least one mandatory argument'); }); $this->factoryBuilder->build($testedClass)->addToAssertionManager($this->assertionManager, 'newInstance', function () use($testedClass) { throw new exceptions\runtime('Tested class ' . $testedClass->getName() . ' has no constructor or its constructor has at least one mandatory argument'); }); $this->assertionManager->setPropertyHandler('testedInstance', function () use(&$instance) { if ($instance === null) { throw new exceptions\runtime('Use $this->newTestedInstance before using $this->testedInstance'); } return $instance; }); if ($this->codeCoverageIsEnabled() === true) { $options = XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE; if ($this->branchesAndPathsCoverageIsEnabled() === true) { $options |= XDEBUG_CC_BRANCH_CHECK; } xdebug_start_code_coverage($options); } $assertionNumber = $this->score->getAssertionNumber(); $time = microtime(true); $memory = memory_get_usage(true); if (isset($this->dataProviders[$testMethod]) === false) { $this->{$testMethod}(); $this->asserterCallManager->check(); } else { $data = $this->{$this->dataProviders[$testMethod]}(); if (is_array($data) === false && $data instanceof \traversable === false) { throw new test\exceptions\runtime('Data provider ' . $this->getClass() . '::' . $this->dataProviders[$testMethod] . '() must return an array or an iterator'); } $reflectedTestMethod = call_user_func($this->reflectionMethodFactory, $this, $testMethod); $numberOfArguments = $reflectedTestMethod->getNumberOfRequiredParameters(); foreach ($data as $key => $arguments) { if (is_array($arguments) === false) { $arguments = array($arguments); } if (sizeof($arguments) != $numberOfArguments) { throw new test\exceptions\runtime('Data provider ' . $this->getClass() . '::' . $this->dataProviders[$testMethod] . '() not provide enough arguments at key ' . $key . ' for test method ' . $this->getClass() . '::' . $testMethod . '()'); } $this->score->setDataSet($key, $this->dataProviders[$testMethod]); $reflectedTestMethod->invokeArgs($this, $arguments); $this->asserterCallManager->check(); $this->score->unsetDataSet(); } } $this->mockControllerLinker->reset(); $this->testAdapterStorage->reset(); $memoryUsage = memory_get_usage(true) - $memory; $duration = microtime(true) - $time; $this->score->addMemoryUsage($this->path, $this->class, $this->currentMethod, $memoryUsage)->addDuration($this->path, $this->class, $this->currentMethod, $duration)->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); if ($this->codeCoverageIsEnabled() === true) { $this->score->getCoverage()->addXdebugDataForTest($this, xdebug_get_code_coverage()); xdebug_stop_code_coverage(); } if ($assertionNumber == $this->score->getAssertionNumber() && $this->methodIsNotVoid($this->currentMethod) === false) { $this->score->addVoidMethod($this->path, $this->class, $this->currentMethod); } } catch (\exception $exception) { $this->score->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); throw $exception; } } catch (asserter\exception $exception) { foreach ($this->executeOnFailure as $closure) { ob_start(); $closure(); $this->score->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); } if ($this->score->failExists($exception) === false) { $this->addExceptionToScore($exception); } } catch (test\exceptions\runtime $exception) { $this->score->addRuntimeException($this->path, $this->class, $this->currentMethod, $exception); } catch (test\exceptions\skip $exception) { list($file, $line) = $this->getBacktrace($exception->getTrace()); $this->score->addSkippedMethod($file, $this->class, $this->currentMethod, $line, $exception->getMessage()); } catch (test\exceptions\stop $exception) { } catch (exception $exception) { list($file, $line) = $this->getBacktrace($exception->getTrace()); $this->errorHandler(E_USER_ERROR, $exception->getMessage(), $file, $line); } catch (\exception $exception) { $this->addExceptionToScore($exception); } $this->afterTestMethod($this->currentMethod); $this->currentMethod = null; restore_error_handler(); ini_restore('display_errors'); ini_restore('log_errors'); ini_restore('log_errors_max_len'); $this->mockAutoloader->unregister(); } return $this; }
{ if ($factory === null) { $factory = function ($methodName, $mock) { return new mock\controller\invoker($methodName, $mock); }; } return $factory($methodName, $this->getMock()); } protected function setInvoker($methodName, \closure $factory = null) { $invoker = parent::setInvoker($methodName, $factory); $mock = $this->getMock(); if ($mock !== null) { $invoker->setMock($this->getMock()); } if ($this->autoBind === true) { $invoker->bindTo($mock); } return $invoker; } protected function buildCall($function, array $arguments) { $call = parent::buildCall($function, $arguments); if ($this->mockClass !== null) { $call->setDecorator(new decorators\addClass($this->mockClass)); } return $call; } } controller::setLinker();
public function runTestMethod($testMethod, array $tags = array()) { if ($this->methodIsIgnored($testMethod, $tags) === false) { $mockGenerator = $this->getMockGenerator(); $mockNamespacePattern = '/^' . preg_quote($mockGenerator->getDefaultNamespace()) . '\\\\/i'; $mockAutoloader = function ($class) use($mockGenerator, $mockNamespacePattern) { $mockedClass = preg_replace($mockNamespacePattern, '', $class); if ($mockedClass !== $class) { $mockGenerator->generate($mockedClass); } }; if (spl_autoload_register($mockAutoloader, true, true) === false) { throw new \runtimeException('Unable to register mock autoloader'); } set_error_handler(array($this, 'errorHandler')); ini_set('display_errors', 'stderr'); ini_set('log_errors', 'Off'); ini_set('log_errors_max_len', '0'); $this->currentMethod = $testMethod; $this->executeOnFailure = array(); $this->phpMocker->setDefaultNamespace($this->getTestedClassNamespace()); try { foreach ($this->getMethodPhpVersions($testMethod) as $phpVersion => $operator) { if (version_compare(phpversion(), $phpVersion, $operator) === false) { throw new test\exceptions\skip('PHP version ' . PHP_VERSION . ' is not ' . $operator . ' to ' . $phpVersion); } } foreach ($this->getMandatoryMethodExtensions($testMethod) as $mandatoryExtension) { $this->extension($mandatoryExtension)->isLoaded(); } try { ob_start(); if ($this->adapter->class_exists($testedClassName = $this->getTestedClassName()) === false) { throw new exceptions\runtime('Tested class \'' . $testedClassName . '\' does not exist for test class \'' . $this->getClass() . '\''); } test\adapter::setStorage($this->testAdapterStorage); mock\controller::setLinker($this->mockControllerLinker); $this->testAdapterStorage->add(php\mocker::getAdapter()); $this->beforeTestMethod($this->currentMethod); if ($this->codeCoverageIsEnabled() === true) { xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); } $assertionNumber = $this->score->getAssertionNumber(); $time = microtime(true); $memory = memory_get_usage(true); if (isset($this->dataProviders[$testMethod]) === false) { $this->{$testMethod}(); asserters\adapter\call::areEvaluated(); } else { $data = $this->{$this->dataProviders[$testMethod]}(); if (is_array($data) === false && $data instanceof \traversable === false) { throw new test\exceptions\runtime('Data provider ' . $this->getClass() . '::' . $this->dataProviders[$testMethod] . '() must return an array or an iterator'); } $reflectedTestMethod = call_user_func($this->reflectionMethodFactory, $this, $testMethod); $numberOfArguments = $reflectedTestMethod->getNumberOfRequiredParameters(); foreach ($data as $key => $arguments) { if (is_array($arguments) === false) { $arguments = array($arguments); } if (sizeof($arguments) != $numberOfArguments) { throw new test\exceptions\runtime('Data provider ' . $this->getClass() . '::' . $this->dataProviders[$testMethod] . '() not provide enough arguments at key ' . $key . ' for test method ' . $this->getClass() . '::' . $testMethod . '()'); } $this->score->setDataSet($key, $this->dataProviders[$testMethod]); $reflectedTestMethod->invokeArgs($this, $arguments); asserters\adapter\call::areEvaluated(); $this->score->unsetDataSet(); } } $this->mockControllerLinker->reset(); $this->testAdapterStorage->reset(); $memoryUsage = memory_get_usage(true) - $memory; $duration = microtime(true) - $time; $this->score->addMemoryUsage($this->path, $this->class, $this->currentMethod, $memoryUsage)->addDuration($this->path, $this->class, $this->currentMethod, $duration)->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); if ($this->codeCoverageIsEnabled() === true) { $this->score->getCoverage()->addXdebugDataForTest($this, xdebug_get_code_coverage()); xdebug_stop_code_coverage(); } if ($assertionNumber == $this->score->getAssertionNumber() && $this->methodIsNotVoid($this->currentMethod) === false) { $this->score->addVoidMethod($this->path, $this->class, $this->currentMethod); } } catch (\exception $exception) { $this->score->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); throw $exception; } } catch (asserter\exception $exception) { foreach ($this->executeOnFailure as $closure) { ob_start(); $closure(); $this->score->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); } if ($this->score->failExists($exception) === false) { $this->addExceptionToScore($exception); } } catch (test\exceptions\runtime $exception) { $this->score->addRuntimeException($this->path, $this->class, $this->currentMethod, $exception); } catch (test\exceptions\skip $exception) { list($file, $line) = $this->getBacktrace($exception->getTrace()); $this->score->addSkippedMethod($file, $this->class, $this->currentMethod, $line, $exception->getMessage()); } catch (test\exceptions\stop $exception) { } catch (exception $exception) { list($file, $line) = $this->getBacktrace($exception->getTrace()); $this->errorHandler(E_USER_ERROR, $exception->getMessage(), $file, $line); } catch (\exception $exception) { $this->addExceptionToScore($exception); } $this->afterTestMethod($this->currentMethod); $this->currentMethod = null; restore_error_handler(); ini_restore('display_errors'); ini_restore('log_errors'); ini_restore('log_errors_max_len'); if (spl_autoload_unregister($mockAutoloader) === false) { throw new \runtimeException('Unable to unregister mock autoloader'); } } return $this; }
function beforeTestMethod($method) { mock\controller::disableAutoBindForNewMock(); $this->mockGenerator->allIsInterface(); return parent::beforeTestMethod($method); }
public function testResetCalls() { $this->if($mockController = new testedClass())->and($mockController->{$method = uniqid()} = function () { })->then->array($mockController->getCalls())->isEmpty()->if($mockController->invoke($method, array()))->then->array($mockController->getCalls())->isNotEmpty()->object($mockController->resetCalls())->isIdenticalTo($mockController)->array($mockController->getCalls())->isEmpty(); }
public function testCreatePhar() { $builder = new \mock\mageekguy\atoum\scripts\builder(uniqid(), $adapter = new atoum\test\adapter()); $builder->setTaggerEngine($taggerEngine = new \mock\mageekguy\atoum\scripts\tagger\engine())->disablePharCreation(); $taggerEngine->getMockController()->tagVersion = function () { }; $this->assert->boolean($builder->createPhar())->isTrue(); $builder->enablePharCreation(); $vcsController = new mock\controller(); $vcsController->__construct = function () { }; $vcsController->getNextRevisions = array(); $vcsController->exportRepository = function () { }; $builder->setVcs($vcs = new \mock\mageekguy\atoum\scripts\builder\vcs(null, $vcsController)); $this->assert->exception(function () use($builder) { $builder->createPhar(); })->isInstanceOf('mageekguy\\atoum\\exceptions\\logic')->hasMessage('Unable to create phar, destination directory is undefined'); $builder->setDestinationDirectory($destinationDirectory = uniqid()); $this->assert->exception(function () use($builder) { $builder->createPhar(); })->isInstanceOf('mageekguy\\atoum\\exceptions\\logic')->hasMessage('Unable to create phar, working directory is undefined'); $builder->setWorkingDirectory($workingDirectory = uniqid()); $builder->setPhpPath($php = uniqid())->setPharGeneratorScript($pharGeneratorScript = uniqid()); $builderController = $builder->getMockController(); $builderController->writeErrorInErrorsDirectory = function () { }; $adapter->file_get_contents = false; $this->assert->boolean($builder->createPhar())->isTrue(); $vcsController->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $builder->disableUnitTestChecking(); $adapter->proc_open = false; $this->assert->boolean($builder->createPhar())->isFalse()->mock($builder)->call('writeErrorInErrorsDirectory')->withArguments('Unable to execute \'' . escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory) . '\'')->once()->mock($vcs)->call('setRevision')->withArguments($revision)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); $adapter->proc_open = function ($bin, $descriptors, &$stream) use(&$stdErr, &$pipes, &$resource) { $pipes = array(2 => $stdErr = uniqid()); $stream = $pipes; return $resource = uniqid(); }; $adapter->stream_get_contents = function () { return ''; }; $adapter->fclose = function () { }; $adapter->proc_close = function () { }; $adapter->date = $date = uniqid(); $vcsController->resetCalls()->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $this->assert->boolean($builder->createPhar())->isTrue()->mock($taggerEngine)->call('setVersion')->withArguments('nightly-' . $revision . '-' . $date)->once()->call('tagVersion')->atLeastOnce()->adapter($adapter)->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->once()->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->call('date')->withArguments('YmdHi')->atLeastOnce()->mock($vcs)->call('setRevision')->withArguments($revision)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); $adapter->resetCalls(); $builder->getMockController()->resetCalls(); $vcsController->resetCalls()->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $this->assert->boolean($builder->createPhar($tag = uniqid()))->isTrue()->mock($taggerEngine)->call('setVersion')->withArguments($tag)->once()->call('tagVersion')->once()->adapter($adapter)->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->once()->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->call('date')->never()->mock($vcs)->call('setRevision')->withArguments($revision)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); $adapter->resetCalls(); $builder->getMockController()->resetCalls(); $vcsController->resetCalls()->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $adapter->stream_get_contents = function () use(&$stdErrContents) { return $stdErrContents = uniqid(); }; $this->assert->boolean($builder->createPhar())->isFalse()->adapter($adapter)->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->once()->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->mock($builder)->call('writeErrorInErrorsDirectory')->withArguments($stdErrContents)->once()->mock($vcs)->call('setRevision')->withArguments($revision)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); $builder->setRevisionFile($revisionFile = uniqid()); $adapter->stream_get_contents = function () { return ''; }; $adapter->file_get_contents = false; $adapter->file_put_contents = function () { }; $vcsController->resetCalls()->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $this->assert->boolean($builder->createPhar())->isTrue()->adapter($adapter)->call('file_get_contents')->withArguments($revisionFile)->once()->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->once()->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->mock($vcs)->call('setRevision')->withArguments($revision)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); $adapter->file_get_contents = false; $adapter->file_put_contents = function () { }; $vcsController->resetCalls()->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $this->assert->boolean($builder->createPhar())->isTrue()->adapter($adapter)->call('file_get_contents')->withArguments($revisionFile)->once()->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->once()->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->call('file_put_contents')->withArguments($revisionFile, $revision, \LOCK_EX)->once()->mock($vcs)->call('setRevision')->withArguments($revision)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); $vcsController->resetCalls()->getNextRevisions = function () use(&$revision) { static $i = 0; return ++$i > 1 ? array() : array($revision = rand(1, PHP_INT_MAX)); }; $adapter->file_put_contents = false; $this->assert->exception(function () use($builder) { $builder->createPhar(); })->isInstanceOf('mageekguy\\atoum\\exceptions\\runtime')->hasMessage('Unable to save last revision in file \'' . $revisionFile . '\''); $vcsController->resetCalls(); $vcsController->getNextRevisions[1] = array(1, 2, 3); $vcsController->getNextRevisions[2] = array(2, 3); $vcsController->getNextRevisions[3] = array(3); $vcsController->getNextRevisions[4] = array(); $adapter->file_put_contents = function () { }; $this->assert->boolean($builder->createPhar())->isTrue()->adapter($adapter)->call('file_get_contents')->withArguments($revisionFile)->once()->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->exactly(3)->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->call('file_put_contents')->withArguments($revisionFile, 3, \LOCK_EX)->once()->mock($vcs)->call('setRevision')->withArguments(1)->once()->call('setRevision')->withArguments(2)->once()->call('setRevision')->withArguments(3)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->atLeastOnce()->call('exportRepository')->atLeastOnce(); $vcsController->resetCalls(); $vcsController->getNextRevisions[1] = array(4); $vcsController->getNextRevisions[2] = array(); $adapter->file_get_contents = 1; $this->assert->boolean($builder->createPhar())->isTrue()->adapter($adapter)->call('file_get_contents')->withArguments($revisionFile)->once()->call('proc_open')->withArguments(escapeshellarg($php) . ' -d phar.readonly=0 -f ' . escapeshellarg($workingDirectory . \DIRECTORY_SEPARATOR . $pharGeneratorScript) . ' -- -d ' . escapeshellarg($destinationDirectory), array(2 => array('pipe', 'w')), $pipes)->once()->call('stream_get_contents')->withArguments($stdErr)->once()->call('fclose')->withArguments($stdErr)->once()->call('proc_close')->withArguments($resource)->once()->call('file_put_contents')->withArguments($revisionFile, 4, \LOCK_EX)->once()->mock($vcs)->call('setRevision')->withArguments(4)->once()->call('setWorkingDirectory')->withArguments($workingDirectory)->once()->call('exportRepository')->once(); }
public function testGetForMock() { $this->if($mockController = new testedClass())->and($mockController->control($mock = new \mock\object()))->then->object(testedClass::getForMock($mock))->isIdenticalTo($mockController)->if($otherMockController = new testedClass())->and($otherMockController->control($otherMock = new \mock\object()))->then->object(testedClass::getForMock($mock))->isIdenticalTo($mockController)->object(testedClass::getForMock($otherMock))->isIdenticalTo($otherMockController); }