Example #1
0
 public function run()
 {
     foreach ($this->steps as $k => $step) {
         $this->currentStep = $k;
         $this->test->runStep($step);
     }
 }
Example #2
0
 public function runStep(Step $step)
 {
     $this->steps[] = $step;
     $result = $this->test->runStep($step);
     $step->executed = true;
     return $result;
 }
Example #3
0
 public function _failed(\Codeception\TestCase $test, $fail)
 {
     if (!$this->client || !$this->client->getInternalResponse()) {
         return;
     }
     file_put_contents(\Codeception\Configuration::logDir() . basename($test->getFileName()) . '.page.debug.html', $this->client->getInternalResponse()->getContent());
 }
Example #4
0
 public function testTearDown()
 {
     $events = array();
     $this->dispatcher->addListener('test.after', function ($e) use(&$events) {
         $events[] = $e->getName();
     });
     $this->testcase->tearDown();
     $this->assertEquals($events, array('test.after'));
 }
Example #5
0
 public function runStep()
 {
     if (empty($this->steps)) {
         return;
     }
     $step = $this->lastStep();
     if (!$step->executed) {
         $result = $this->test->runStep($step);
         $this->currentStep++;
         $step->executed = true;
         return $result;
     }
 }
Example #6
0
 /**
  * @group core
  */
 public function testRunStep()
 {
     $assertions =& $this->moduleContainer->getModule('EmulateModuleHelper')->assertions;
     $step = new \Codeception\Step\Action('seeEquals', array(5, 5));
     $this->testcase->runStep($step);
     $this->assertEquals(1, $assertions);
     $step = new \Codeception\Step\Action('seeEquals', array(5, 6));
     try {
         $this->testcase->runStep($step);
     } catch (Exception $e) {
         $this->assertInstanceOf('PHPUnit_Framework_ExpectationFailedException', $e);
     }
     $this->assertEquals(1, $assertions);
 }
Example #7
0
 public function _failed(TestCase $test, $fail)
 {
     if (!$this->client || !$this->client->getInternalResponse()) {
         return;
     }
     $this->_savePageSource(codecept_output_dir() . str_replace(['::', '\\', '/'], ['.', '.', '.'], TestCase::getTestSignature($test)) . '.fail.html');
 }
Example #8
0
 /**
  * Setups common environment for a test case.
  *
  * @since 1.0.0
  *
  * @access protected
  * @param \Codeception\TestCase $testCase The test case object.
  * @param string $name Test case name.
  * @param string $file The file name.
  */
 protected function _setupTestCase(TestCase $testCase, $name, $file)
 {
     $testCase->setBackupGlobals(false);
     $testCase->setBackupStaticAttributes(false);
     $testCase->setRunTestInSeparateProcess(false);
     $testCase->setInIsolation(false);
     $testCase->setPreserveGlobalState(false);
     if ($testCase instanceof Configurable) {
         $testCase->configName($name);
         $testCase->configFile($file);
         $testCase->initConfig();
     }
 }
Example #9
0
 public function __construct($dispatcher, array $data = array(), $dataName = '')
 {
     parent::__construct($dispatcher, $data, $dataName);
     $this->testClass = $data['class'];
     $this->testMethod = $data['method'];
     $this->static = $data['static'];
     $this->signature = $data['signature'];
 }
Example #10
0
 public function _failed(TestCase $test, $fail)
 {
     if (!$this->client || !$this->client->getInternalResponse()) {
         return;
     }
     $filename = str_replace(['::', '\\', '/'], ['.', '', ''], TestCase::getTestSignature($test)) . '.fail.html';
     file_put_contents(codecept_output_dir($filename), $this->client->getInternalResponse()->getContent());
 }
Example #11
0
 /**
  * @group core
  */
 public function testCeptNamings()
 {
     $cept = new \Codeception\TestCase\Cept();
     $cept->configName('LoginCept.php')->config('testFile', 'tests/acceptance/LoginCept.php');
     $this->assertEquals('tests/acceptance/LoginCept.php', \Codeception\TestCase::getTestFileName($cept));
     $this->assertEquals('tests/acceptance/LoginCept.php', \Codeception\TestCase::getTestFullName($cept));
     $this->assertEquals('LoginCept', \Codeception\TestCase::getTestSignature($cept));
 }
Example #12
0
 /**
  * @group core
  */
 public function testCestNamings()
 {
     $cept = new \Codeception\TestCase\Cest();
     $klass = new stdClass();
     $cept->config('testClassInstance', $klass)->config('testMethod', 'user')->config('testFile', 'tests/acceptance/LoginCest.php');
     $this->assertEquals('tests/acceptance/LoginCest.php:user', \Codeception\TestCase::getTestFullName($cept));
     $this->assertEquals('tests/acceptance/LoginCest.php', \Codeception\TestCase::getTestFileName($cept));
     $this->assertEquals('stdClass::user', \Codeception\TestCase::getTestSignature($cept));
 }
Example #13
0
 protected function getTestNames($tests)
 {
     $testNames = [];
     foreach ($tests as $test) {
         if ($test instanceof \PHPUnit_Framework_TestCase) {
             $testNames[] = \Codeception\TestCase::getTestSignature($test);
         }
     }
     return $testNames;
 }
Example #14
0
 public function _after(TestCase $test)
 {
     $this->debug(__CLASS__ . '::' . __FUNCTION__ . '()');
     $unfinished_transaction = $this->transaction_level > 0;
     if ($unfinished_transaction) {
         $this->debug("Unfinished transaction was found; rolling back (after test '{$test->getName(false)}')");
         // wrap up the transaction so that the clean-up below can succeed.
         // it is not possible to switch connectors mid-transaction.
         $this->rollbackTransaction();
     }
     foreach ($this->test_cleanup_actions as $cleanup_action) {
         $this->debugSection('cleanup', $cleanup_action->getDefinition());
         call_user_func($cleanup_action, $this);
     }
     if ($unfinished_transaction) {
         $this->fail("Unfinished transaction was found (after test '{$test->getName(false)}')");
     }
     $this->test_cleanup_actions = [];
     parent::_after($test);
 }
Example #15
0
 public function __construct(EventDispatcher $dispatcher, array $data = array(), $dataName = '')
 {
     parent::__construct('testCodecept', $data, $dataName);
     $this->dispatcher = $dispatcher;
     if (!isset($data['file'])) {
         throw new \Exception('File with test scenario not set. Use array(file => filepath) to set a scenario');
     }
     $this->name = $data['name'];
     $this->scenario = new \Codeception\Scenario($this);
     $this->testfile = $data['file'];
     $this->bootstrap = isset($data['bootstrap']) ? $data['bootstrap'] : null;
 }
Example #16
0
 protected function assertContainsTestName($name, $tests)
 {
     foreach ($tests as $test) {
         if ($test instanceof \PHPUnit_Framework_TestCase) {
             $testName = \Codeception\TestCase::getTestSignature($test);
             if ($testName == $name) {
                 return;
             }
             codecept_debug($testName);
         }
     }
     $this->fail("{$name} not found in tests");
 }
Example #17
0
 public function saveFailed(PrintResultEvent $e)
 {
     $file = $this->getLogDir() . $this->config['file'];
     $result = $e->getResult();
     if ($result->wasSuccessful()) {
         if (is_file($file)) {
             unlink($file);
         }
         return;
     }
     $output = [];
     foreach ($result->failures() as $fail) {
         $output[] = $this->localizePath(TestCase::getTestFullName($fail->failedTest()));
     }
     foreach ($result->errors() as $fail) {
         $output[] = $this->localizePath(TestCase::getTestFullName($fail->failedTest()));
     }
     file_put_contents($file, implode("\n", $output));
 }
 public function run()
 {
     if (!class_exists('\\Codeception\\Lib\\TestLoader')) {
         throw new TaskException($this, "This task requires Codeception to be loaded. Please require autoload.php of Codeception");
     }
     $testLoader = new \Codeception\Lib\TestLoader($this->testsFrom);
     $testLoader->loadTests();
     $tests = $testLoader->getTests();
     $i = 0;
     $groups = [];
     $this->printTaskInfo("Processing " . count($tests) . " files");
     // splitting tests by groups
     foreach ($tests as $test) {
         $groups[$i % $this->numGroups + 1][] = \Codeception\TestCase::getTestFullName($test);
         $i++;
     }
     // saving group files
     foreach ($groups as $i => $tests) {
         $filename = $this->saveTo . $i;
         $this->printTaskInfo("Writing {$filename}");
         file_put_contents($filename, implode("\n", $tests));
     }
 }
 /**
  * Checks item in Memcached exists and the same as expected.
  *
  * @param string $referenceImageIdentifier
  * @param null|string $selector
  * @throws ModuleException
  */
 public function seeNoDifferenceToReferenceImage($referenceImageIdentifier, $selector = null)
 {
     if ($selector === null) {
         $selector = 'body';
     }
     $elements = $this->webDriver->_findElements($selector);
     if (count($elements) == 0) {
         throw new ElementNotFound($selector);
     } elseif (count($elements) > 1) {
         throw new ModuleException(__CLASS__, 'Multiple elements found for given selector "' . $selector . '" but need exactly one element!');
     }
     /** @var RemoteWebElement $element */
     $image = $this->_createScreenshot($referenceImageIdentifier, reset($elements));
     $windowSizeString = $this->moduleFileSystemUtil->getCurrentWindowSizeString($this->webDriver);
     $referenceImagePath = $this->moduleFileSystemUtil->getReferenceImagePath($referenceImageIdentifier, $windowSizeString);
     if (!file_exists($referenceImagePath)) {
         // Ensure that the target directory exists
         $this->moduleFileSystemUtil->createDirectoryRecursive(dirname($referenceImagePath));
         copy($image->getImageFilename(), $referenceImagePath);
         $this->currentTestCase->markTestIncomplete('Reference Image does not exist.
             Test is skipeed but will now copy reference image to target directory...');
     } else {
         $referenceImage = new \Imagick($referenceImagePath);
         /** @var \Imagick $comparedImage */
         list($comparedImage, $difference) = $referenceImage->compareImages($image, \Imagick::METRIC_MEANSQUAREERROR);
         $calculatedDifferenceValue = round((double) substr($difference, 0, 6) * 100, 2);
         $this->currentTestCase->getScenario()->comment('Difference between reference and current image is around ' . $calculatedDifferenceValue . '%');
         if ($calculatedDifferenceValue > $this->config['maxDifference']) {
             $failImagePath = $this->moduleFileSystemUtil->getFailImagePath($referenceImageIdentifier, $windowSizeString, 'diff');
             $this->moduleFileSystemUtil->createDirectoryRecursive(dirname($failImagePath));
             $image->writeImage($this->moduleFileSystemUtil->getFailImagePath($referenceImageIdentifier, $windowSizeString, 'fail'));
             $comparedImage->setImageFormat('png');
             $comparedImage->writeImage($failImagePath);
             $this->fail('Image does not match to the reference image.');
         }
     }
 }
 public function _before(\Codeception\TestCase $test)
 {
     $this->scenario = $test->getScenario();
 }
Example #21
0
 public function __construct(array $data = array(), $dataName = '')
 {
     parent::__construct('testCodecept', $data, $dataName);
 }
Example #22
0
 /**
  * Very magical function that generates Mock methods for expected assertions
  * Allows the declaration of seeMethodInvoked, seeMethodNotInvoked, etc, AFTER the 'execute' command
  *
  */
 protected function createMocks()
 {
     $scenario = $this->test->getScenario();
     $steps = $scenario->getSteps();
     if (!isset($steps[$scenario->getCurrentStep()])) {
         throw new \Exception("New steps were added to scenario in realtime. Can't proceed.\nRemove loops from your unit test to fix it");
     }
     for ($i = $scenario->getCurrentStep() + 1; $i < count($steps); $i++) {
         $step = $steps[$i];
         if (strpos($action = $step->getAction(), 'seeMethod') === 0) {
             $arguments = $step->getArguments(false);
             $mock = array_shift($arguments);
             $function = array_shift($arguments);
             $params = array_shift($arguments);
             foreach ($this->stubs as $stub) {
                 if (get_class($stub) == get_class($mock)) {
                     $mock = $stub;
                 }
             }
             $invoke = false;
             switch ($action) {
                 case 'seeMethodInvoked':
                 case 'seeMethodInvokedAtLeastOnce':
                     if (!$mock) {
                         throw new \InvalidArgumentException("Stub class not defined");
                     }
                     $invoke = new \PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce();
                     break;
                 case 'seeMethodInvokedOnce':
                     if (!$mock) {
                         throw new \InvalidArgumentException("Stub class not defined");
                     }
                     $invoke = new \PHPUnit_Framework_MockObject_Matcher_InvokedCount(1);
                     break;
                 case 'seeMethodNotInvoked':
                     if (!$mock) {
                         throw new \InvalidArgumentException("Stub class not defined");
                     }
                     $invoke = new \PHPUnit_Framework_MockObject_Matcher_InvokedCount(0);
                     break;
                 case 'seeMethodInvokedMultipleTimes':
                     if (!$mock) {
                         throw new \InvalidArgumentException("Stub class not defined");
                     }
                     $times = $params;
                     if (!is_int($times)) {
                         throw new \InvalidArgumentException("Invoked times count should be an integer");
                     }
                     $params = $arguments;
                     $invoke = new \PHPUnit_Framework_MockObject_Matcher_InvokedCount($times);
                     break;
                 default:
             }
             if ($invoke) {
                 $mockMethod = $mock->expects($invoke)->method($function);
                 $this->debug(get_class($invoke) . ' attached');
                 if ($params) {
                     call_user_func_array(array($mockMethod, 'with'), $params);
                     $this->debug('with ' . json_encode($params));
                 }
             }
         }
         if ($step->getAction() == 'executeTestedMethod') {
             break;
         }
         if ($step->getAction() == 'execute') {
             break;
         }
         if ($step->getAction() == 'executeTestedMethodOn') {
             break;
         }
         if ($step->getAction() == 'executeTestedMethodWith') {
             break;
         }
     }
 }
Example #23
0
 public function _failed(\Codeception\TestCase $test, $fail)
 {
     $output = \Codeception\Configuration::logDir() . DIRECTORY_SEPARATOR . basename($test->getFileName()) . '.page.debug.html';
     file_put_contents($output, $this->browser->getResponse()->getContent());
 }
Example #24
0
 /**
  * @param mixed  $exceptionName
  * @param string $exceptionMessage
  * @param int    $exceptionCode
  */
 public function setExpectedException($exceptionName, $exceptionMessage = '', $exceptionCode = null)
 {
     $this->test->setExpectedException($exceptionName, $exceptionMessage, $exceptionCode);
 }
Example #25
0
 public function _failed(\Codeception\TestCase $test, $error)
 {
     $this->_saveScreenshot(\Codeception\Configuration::logDir() . basename($test->getFileName()) . '.fail.png');
     $this->debug("Screenshot was saved into 'log' dir");
     $this->session->stop();
 }
Example #26
0
 protected function isExecutedInCurrentEnvironment(\Codeception\TestCase $test)
 {
     $envs = $test->getEnvironment();
     if (empty($envs)) {
         return true;
     }
     $currentEnvironments = explode(',', $this->env);
     foreach ($envs as $envList) {
         $envList = explode(',', $envList);
         if (count($envList) == count(array_intersect($currentEnvironments, $envList))) {
             return true;
         }
     }
     return false;
 }
Example #27
0
 protected function checkEnvironmentExists(\Codeception\TestCase $test)
 {
     $envs = $test->getEnvironment();
     if (empty($envs)) {
         return;
     }
     if (!isset($this->settings['env'])) {
         Notification::warning("Environments are not configured", TestCase::getTestFullName($test));
         return;
     }
     $availableEnvironments = array_keys($this->settings['env']);
     $listedEnvironments = explode(',', implode(',', $test->getEnvironment()));
     foreach ($listedEnvironments as $env) {
         if (!in_array($env, $availableEnvironments)) {
             Notification::warning("Environment {$env} was not configured but used in test", TestCase::getTestFullName($test));
         }
     }
 }
Example #28
0
 public function _failed(\Codeception\TestCase $test, $fail)
 {
     $filename = str_replace(['::', '\\', '/'], ['.', '', ''], \Codeception\TestCase::getTestSignature($test)) . '.fail.png';
     $this->_saveScreenshot(codecept_output_dir($filename));
     $this->debug("Screenshot was saved into '_output' dir");
 }
Example #29
0
 public function persist(TestEvent $e)
 {
     if (!$this->webDriverModule or !$this->dir) {
         return;
     }
     $indicatorHtml = '';
     $slideHtml = '';
     foreach ($this->slides as $i => $step) {
         $indicatorHtml .= (new Template($this->indicatorTemplate))->place('step', (int) $i)->place('isActive', (int) $i ? '' : 'class="active"')->produce();
         $slideHtml .= (new Template($this->slidesTemplate))->place('image', $i)->place('caption', $step->getHumanizedArguments())->place('isActive', (int) $i ? '' : 'active')->place('isError', $step->hasFailed() ? 'error' : '')->produce();
     }
     $html = (new Template($this->template))->place('indicators', $indicatorHtml)->place('slides', $slideHtml)->place('feature', ucfirst($e->getTest()->getFeature()))->place('test', TestCase::getTestSignature($e->getTest()))->produce();
     $indexFile = $this->dir . DIRECTORY_SEPARATOR . 'index.html';
     file_put_contents($indexFile, $html);
     $testName = TestCase::getTestSignature($e->getTest()) . ' - ' . ucfirst($e->getTest()->getFeature());
     $this->recordedTests[$testName] = substr($indexFile, strlen(codecept_output_dir()));
 }
Example #30
0
 public function _failed(TestCase $test, $fail)
 {
     $this->debugWebDriverLogs();
     $filename = str_replace(['::', '\\', '/'], ['.', '', ''], TestCase::getTestSignature($test)) . '.fail';
     $this->_saveScreenshot(codecept_output_dir() . $filename . '.png');
     $this->_savePageSource(codecept_output_dir() . $filename . '.html');
     $this->debug("Screenshot and page source were saved into '_output' dir");
 }