/** * @test * * @covers ::all */ public function canObtainAllPaths() { $paths = $this->makeFilesPaths(rand(3, 10)); $collection = $this->makeFilesCollection($paths); Debug::debug($collection); $this->assertSame($paths, $collection->all()); }
/** * * @param \Symfony\Component\BrowserKit\Request $request * * @return \Symfony\Component\BrowserKit\Response */ public function doRequest($request) { $_COOKIE = $request->getCookies(); $_SERVER = $request->getServer(); $_FILES = $request->getFiles(); $_REQUEST = $request->getParameters(); $_POST = $_GET = array(); if (strtoupper($request->getMethod()) == 'GET') { $_GET = $request->getParameters(); } else { $_POST = $request->getParameters(); } $uri = $request->getUri(); $pathString = parse_url($uri, PHP_URL_PATH); $queryString = parse_url($uri, PHP_URL_QUERY); $_SERVER['REQUEST_URI'] = $queryString === null ? $pathString : $pathString . '?' . $queryString; $_SERVER['REQUEST_METHOD'] = strtoupper($request->getMethod()); parse_str($queryString, $params); foreach ($params as $k => $v) { $_GET[$k] = $v; } $app = $this->startApp(); $app->getResponse()->on(YiiResponse::EVENT_AFTER_PREPARE, array($this, 'processResponse')); $this->headers = array(); $this->statusCode = null; ob_start(); $app->handleRequest($app->getRequest())->send(); $content = ob_get_clean(); // catch "location" header and display it in debug, otherwise it would be handled // by symfony browser-kit and not displayed. if (isset($this->headers['location'])) { Debug::debug("[Headers] " . json_encode($this->headers)); } return new Response($content, $this->statusCode, $this->headers); }
public function testValidatorBase() { $validator = new Validator(__DIR__ . '/../_data/'); $report = $validator->validate(["shopId" => 1, "serviceType" => "2", "order" => ["number" => "VAL0001", "date" => "2014-03-01"], "from" => ["name" => "YuTIn", "address" => "Taiwan, Taipei", "phone" => "0963066000"], "to" => ["name" => "YuTIn", "address" => "Taiwan, Taipei", "phone" => "0963066000"]], 'schema'); Debug::debug($validator->getMessage()); $this->assertTrue($report); }
/** * Creates an output path, if it does not already exist */ public function createOutputPath() { if (!file_exists($this->outputPath())) { mkdir($this->outputPath(), 0755, true); Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath())); } }
private function listEntities($entityType) { Debug::debug("List {$entityType}"); $response = $this->sendRequest("{$entityType}", null, 'GET'); PHPUnit_Framework_Assert::assertGreaterThan(0, count($response->data)); return $response; }
public function thumbnail($pathToImage, $width, $height) { try { $this->openImage = $this->imagine->open(FileHelper::normalizePath($pathToImage))->thumbnail(new \Imagine\Image\Box($width, $height)); } catch (\Exception $ex) { \Codeception\Util\Debug::debug($ex->getMessage()); } }
public function __construct($options) { $this->debug = $options['debug'] || $options['verbosity'] >= OutputInterface::VERBOSITY_VERY_VERBOSE; $this->steps = $this->debug || $options['steps']; $this->output = new Output($options); if ($this->debug) { Debug::setOutput($this->output); } }
/** * Debug CRUD event result * @param \dlds\giixer\components\events\GxCrudEvent $e * @throws \yii\db\Exception */ public function debugCrud(\dlds\giixer\components\events\GxCrudEvent $e) { if (!$e->model) { throw new \yii\db\Exception('Crud errors debug failed.'); } \Codeception\Util\Debug::debug('Input:'); \Codeception\Util\Debug::debug($e->input); \Codeception\Util\Debug::debug('Errors:'); \Codeception\Util\Debug::debug($e->model->getErrors()); }
public function log($message, $level, $category = 'application') { if (!in_array($level, [\yii\log\Logger::LEVEL_INFO, \yii\log\Logger::LEVEL_WARNING, \yii\log\Logger::LEVEL_ERROR])) { return; } if (strpos($category, 'yii\\db\\Command') === 0) { return; // don't log queries } Debug::debug("[{$category}] {$message} "); }
public function testSchemaValidity() { $em = \Codeception\Module\Doctrine2::$em; $schema = new \Doctrine\ORM\Tools\SchemaValidator($em); $errors = $schema->validateMapping(); $valid = count($errors) == 0; if (!$valid) { \Codeception\Util\Debug::debug($errors); } $this->assertEquals(true, $valid); }
protected function _testToAbsUrl($d, $base) { $path = ''; $port = ''; extract(parse_url($base)); $root = (@$scheme ? $scheme . ':' : '') . '//' . $host . (@$port ? ':' . $port : ''); //remove non-directory (file) part from the end of $path $path = preg_replace('@/([^/]*\\.)+[^/]*$@', '', $path); $clearBase = $root . $path; Debug::debug("\nTesting NLSDownloader::toAbsUrl() with base\nbase={$base}"); Debug::debug('root=' . $root); Debug::debug('clearBase=' . $clearBase); Debug::debug(parse_url($base)); //Absolute urls $rel = 'http://google.com'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($rel, $abs, 'Absolute URL mapped to itself'); //Protocol-relative urls $rel = '//google.com/somefile.txt'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($scheme . ':' . $rel, $abs); //Queries $rel = '?x=1&y=2#somefragment'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($clearBase . $rel, $abs); //Fragments $rel = '#somefragment'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($clearBase . $rel, $abs); //Root-relative urls $rel = '/somepath2'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($root . $rel, $abs); $rel = '/somepath2/a/'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($root . $rel, $abs); $rel = '/somepath2/a.txt'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($root . $rel, $abs); //Relative urls $rel = 'somepath2'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals(rtrim($clearBase, '/') . '/' . $rel, $abs); $rel = 'somepath2/a/./../a'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals(rtrim($clearBase, '/') . '/somepath2/a', $abs); if (preg_match('@\\.css$@', $base)) { $rel = '../img/bg.png'; $abs = $d->toAbsUrl($rel, $base); $this->assertEquals($root . '/img/bg.png', $abs); } }
/** * * @param \Symfony\Component\BrowserKit\Request $request * * @return \Symfony\Component\BrowserKit\Response */ public function doRequest($request) { $_COOKIE = $request->getCookies(); $_SERVER = $request->getServer(); $_FILES = $this->remapFiles($request->getFiles()); $_REQUEST = $this->remapRequestParameters($request->getParameters()); $_POST = $_GET = array(); if (strtoupper($request->getMethod()) == 'GET') { $_GET = $_REQUEST; } else { $_POST = $_REQUEST; } $uri = $request->getUri(); $pathString = parse_url($uri, PHP_URL_PATH); $queryString = parse_url($uri, PHP_URL_QUERY); $_SERVER['REQUEST_URI'] = $queryString === null ? $pathString : $pathString . '?' . $queryString; $_SERVER['REQUEST_METHOD'] = strtoupper($request->getMethod()); parse_str($queryString, $params); foreach ($params as $k => $v) { $_GET[$k] = $v; } $app = $this->startApp(); $app->getResponse()->on(YiiResponse::EVENT_AFTER_PREPARE, array($this, 'processResponse')); $this->headers = array(); $this->statusCode = null; ob_start(); $yiiRequest = $app->getRequest(); $yiiRequest->setRawBody($request->getContent()); try { $app->handleRequest($yiiRequest)->send(); } catch (\Exception $e) { if ($e instanceof HttpException) { // we shouldn't discard existing output as PHPUnit preform output level verification since PHPUnit 4.2. $app->errorHandler->discardExistingOutput = false; $app->errorHandler->handleException($e); } elseif ($e instanceof ExitException) { // nothing to do } else { // for exceptions not related to Http, we pass them to Codeception throw $e; } } $content = ob_get_clean(); // catch "location" header and display it in debug, otherwise it would be handled // by symfony browser-kit and not displayed. if (isset($this->headers['location'])) { Debug::debug("[Headers] " . json_encode($this->headers)); } return new Response($content, $this->statusCode, $this->headers); }
public function testSetLanguageUrl() { $app = \Yii::$app; /** @var \bl\locale\UrlManager $urlManager */ $urlManager = clone $app->urlManager; \Codeception\Util\Debug::debug("Before parse request app language: {$app->language}"); $urlManager->detectInCookie = false; $urlManager->detectInSession = false; $language = 'uk-UA'; $url = "{$language}/site/index"; $request = $app->request; $request->setPathInfo($url); $parse = $urlManager->parseRequest($request); \Codeception\Util\Debug::debug("After parse request app language: {$app->language}"); $this->tester->assertEquals($language, \Yii::$app->language); }
/** * Create a directory recursive * * @param $path */ public function createDirectoryRecursive($path) { // @todo UNIX ONLY? if (substr($path, 0, 1) !== '/') { $path = \Codeception\Configuration::projectDir() . $path; } elseif (!strstr($path, \Codeception\Configuration::projectDir())) { throw new \InvalidArgumentException('Can\'t create directroy "' . $path . '" as it is outside of the project root "' . \Codeception\Configuration::projectDir() . '"'); } if (!is_dir(dirname($path))) { self::createDirectoryRecursive(dirname($path)); } if (!is_dir($path)) { \Codeception\Util\Debug::debug('Directory "' . $path . '" does not exist. Try to create it ...'); mkdir($path); } }
public function testHideDefaoultLanguage() { $mockApp = $this->app; /** @var \bl\locale\UrlManager $urlManager */ $urlManager = clone $mockApp->urlManager; $urlManager->showDefault = false; $url = 'site/index'; \Codeception\Util\Debug::debug("Default language: {$mockApp->sourceLanguage}"); $actual = $urlManager->createUrl([$url, $urlManager->languageKey => 'en-US']); $expected = implode('/', ['', $url]); \Codeception\Util\Debug::debug("Hiden default language: {$actual}"); $this->tester->assertEquals($expected, $actual); $language = 'ru-RU'; $actual = $urlManager->createUrl([$url, $urlManager->languageKey => $language]); $expected = implode('/', ['', $language, $url]); \Codeception\Util\Debug::debug("Change language: {$actual}"); $this->tester->assertEquals($actual, $expected); }
public function __construct($options) { $this->options = $options; $this->debug = $options['debug'] || $options['verbosity'] >= OutputInterface::VERBOSITY_VERY_VERBOSE; $this->steps = $this->debug || $options['steps']; $this->rawStackTrace = $options['verbosity'] === OutputInterface::VERBOSITY_DEBUG; $this->output = new Output($options); if ($this->debug) { Debug::setOutput($this->output); } foreach (['html', 'xml', 'tap', 'json'] as $report) { if (!$this->options[$report]) { continue; } $path = $this->absolutePath($this->options[$report]); $this->reports[] = sprintf("- <bold>%s</bold> report generated in <comment>file://%s</comment>", strtoupper($report), $path); } }
/** * @test */ public function canExecuteScripts() { // Get a log mock $log = $this->makeLogMock(); $log->shouldReceive('info')->withAnyArgs(); $targetA = $this->outputPath() . 'lsOutput.txt'; $targetB = $this->outputPath() . 'lsAhlOutput.txt'; $handler = $this->makeScriptsHandler($log); $scripts = [new CliScript(['script' => 'ls > ' . $targetA]), new CliScript(['script' => 'ls -ahl > ' . $targetB])]; $handler->processElement($scripts); $this->assertFileExists($targetA, 'First script did not output!'); $this->assertFileExists($targetB, 'Second script did not output!'); $contentA = file_get_contents($targetA); $contentB = file_get_contents($targetB); Debug::debug($contentA); Debug::debug($contentB); $this->assertNotEmpty($contentA, 'First output file has no content'); $this->assertNotEmpty($contentB, 'Second output file has no content'); }
public function execute(InputInterface $input, OutputInterface $output) { $suiteName = $input->getArgument('suite'); $this->output = $output; $config = Configuration::config($input->getOption('config')); $settings = Configuration::suiteSettings($suiteName, $config); $options = $input->getOptions(); $options['debug'] = true; $options['silent'] = true; $options['interactive'] = false; $options['colors'] = true; Debug::setOutput(new Output($options)); $this->codecept = new Codecept($options); $dispatcher = $this->codecept->getDispatcher(); $suiteManager = new SuiteManager($dispatcher, $suiteName, $settings); $suiteManager->initialize(); $this->suite = $suiteManager->getSuite(); $moduleContainer = $suiteManager->getModuleContainer(); $this->actions = array_keys($moduleContainer->getActions()); $this->test = (new Cept())->configDispatcher($dispatcher)->configModules($moduleContainer)->configName('')->config('file', '')->initConfig(); $scenario = new Scenario($this->test); if (isset($config["namespace"])) { $settings['class_name'] = $config["namespace"] . '\\' . $settings['class_name']; } $actor = $settings['class_name']; $I = new $actor($scenario); $this->listenToSignals(); $output->writeln("<info>Interactive console started for suite {$suiteName}</info>"); $output->writeln("<info>Try Codeception commands without writing a test</info>"); $output->writeln("<info>type 'exit' to leave console</info>"); $output->writeln("<info>type 'actions' to see all available actions for this suite</info>"); $suiteEvent = new SuiteEvent($this->suite, $this->codecept->getResult(), $settings); $dispatcher->dispatch(Events::SUITE_BEFORE, $suiteEvent); $dispatcher->dispatch(Events::TEST_PARSED, new TestEvent($this->test)); $dispatcher->dispatch(Events::TEST_BEFORE, new TestEvent($this->test)); $output->writeln("\n\n<comment>\$I</comment> = new {$settings['class_name']}(\$scenario);"); $scenario->stopIfBlocked(); $this->executeCommands($input, $output, $I, $settings['bootstrap']); $dispatcher->dispatch(Events::TEST_AFTER, new TestEvent($this->test)); $dispatcher->dispatch(Events::SUITE_AFTER, new SuiteEvent($this->suite)); $output->writeln("<info>Bye-bye!</info>"); }
public function __construct($options) { $this->prepareOptions($options); $this->output = new Output($options); $this->messageFactory = new MessageFactory($this->output); if ($this->debug) { Debug::setOutput($this->output); } $this->detectWidth(); if ($this->options['ansi'] && !$this->isWin()) { $this->chars['success'] = '✔'; $this->chars['fail'] = '✖'; } foreach (['html', 'xml', 'tap', 'json'] as $report) { if (!$this->options[$report]) { continue; } $path = $this->absolutePath($this->options[$report]); $this->reports[] = sprintf("- <bold>%s</bold> report generated in <comment>file://%s</comment>", strtoupper($report), $path); } }
/** * @test * * @throws \Codeception\Exception\ConfigurationException */ public function hasInstalledVimConfigurationInTargetDirectory() { $target = Configuration::outputDir() . 'vimConfigTest'; $this->cleanupFolder($target); Debug::debug('<info>Preparing command...</info>'); $command = $this->getCommand(); Debug::debug('<info>Preparing question helper...</info>'); $this->mockQuestionHelper($command, function ($test, $order, ConfirmationQuestion $question) { // Pick the first choice if ($order == 0) { return true; } throw new UnhandledQuestionException(); }); Debug::debug('<info>Executing...</info>'); $tester = new \Symfony\Component\Console\Tester\CommandTester($command); $tester->execute([VimConfigurationInstallCommand::TARGET_DIR_ARGUMENT => $target]); $output = $tester->getDisplay(); Debug::debug($output); $finder = new Finder(); $count = $finder->directories()->ignoreDotFiles(false)->in($target)->count(); $this->assertNotEquals(0, $count, 'No files have been copied!'); }
/** * @test * * @covers ::execute * @covers ::configure * @covers ::findTemplates * @covers ::getTemplatesList * @covers ::formatTemplatesList * @covers ::createTemplate */ public function hasCopiedFilesIntoTargetLocation() { $target = Configuration::outputDir() . 'tmp'; // Eventual pre-cleanup $this->cleanupFolder($target); Debug::debug('<info>Preparing command...</info>'); $command = $this->getCommand(); Debug::debug('<info>Preparing question helper...</info>'); $this->mockQuestionHelper($command, function ($test, $order, Question $question) { // Pick the first choice if ($order == 0) { return true; } throw new UnhandledQuestionException(); }); Debug::debug('<info>Executing...</info>'); $tester = new \Symfony\Component\Console\Tester\CommandTester($command); $tester->execute([TemplateCommand::ARGUMENT_PATH_NAME => $target]); $output = $tester->getDisplay(); Debug::debug($output); $finder = new Finder(); $count = $finder->directories()->in($target)->count(); $this->assertNotEquals(0, $count, 'No files have been copied!'); }
/** * Pauses test execution in debug mode. * To proceed test press "ENTER" in console. * * This method is useful while writing tests, since it allows you to inspect the current page in the middle of a test case. */ public function pauseExecution() { Debug::pause(); }
protected function loadDump($dbName) { if (empty($this->dumpFiles[$dbName])) { return; } try { \Codeception\Util\Debug::debug("Loading dump for {$dbName} < {$this->dumpFiles[$dbName]}"); $this->drivers[$dbName]->load($this->dumpFiles[$dbName]); } catch (\Exception $e) { throw new \Codeception\Exception\Module(__CLASS__, $e->getMessage()); } }
/** * Registers debug message which will be printed if --debug argument is passed to the command. * * @since 1.0.1 * * @param mixed $data The debug data, it will be serialized if we need to display it. */ function codecept_debug($data) { \Codeception\Util\Debug::debug($data); }
/** * Prepare a full Drush command, to include executable and alias. * * @param string $cmd * The Drush command, without executable and alias, e.g. "pml". The arguments should be escaped. * * @return string * The prepared Drush command to run, complete with executable and alias. */ protected function prepareDrushCommand($cmd) { $baseCmd = sprintf("drush -y %s", escapeshellarg($this->alias)); $cmd = "{$baseCmd} {$cmd}"; Debug::debug($cmd); return $cmd; }
public function testSeeHeaders() { $response = new \Symfony\Component\BrowserKit\Response("", 200, ['Cache-Control' => ['no-cache', 'no-store'], 'Content_Language' => 'en-US']); $this->module->client->mockResponse($response); $this->module->sendGET('/'); $this->module->seeHttpHeader('Cache-Control'); $this->module->seeHttpHeader('content_language', 'en-US'); $this->module->seeHttpHeader('Content-Language', 'en-US'); $this->module->dontSeeHttpHeader('Content-Language', 'en-RU'); $this->module->dontSeeHttpHeader('Content-Language1'); $this->module->seeHttpHeaderOnce('Content-Language'); \Codeception\Util\Debug::debug($this->module->grabHttpHeader('Cache-Control', false)); $this->assertEquals('en-US', $this->module->grabHttpHeader('Content-Language')); $this->assertEquals('no-cache', $this->module->grabHttpHeader('Cache-Control')); $this->assertEquals(['no-cache', 'no-store'], $this->module->grabHttpHeader('Cache-Control', false)); }
/** * Assert that a custom defined default value is returned, * when nothing else has been specified, by invoking * the `get-default-property` and `get-property` methods * * @param string $traitClassPath * @param string $getDefaultPropertyMethodName * @param string $getPropertyMethodName * @param mixed $defaultValue * @param string $failMessage */ public function assertReturnsCustomDefaultValue($traitClassPath, $getDefaultPropertyMethodName, $getPropertyMethodName, $defaultValue, $failMessage = 'Incorrect default value returned') { if (is_object($defaultValue)) { Debug::debug(' - mocking ' . $getDefaultPropertyMethodName . '(), must return; ' . get_class($defaultValue)); } else { Debug::debug(' - mocking ' . $getDefaultPropertyMethodName . '(), must return; ' . var_export($defaultValue, true)); } $traitMock = $this->getTraitMock($traitClassPath, [$getDefaultPropertyMethodName]); $traitMock->expects($this->any())->method($getDefaultPropertyMethodName)->willReturn($defaultValue); Debug::debug(' - ' . $getPropertyMethodName . '()'); $this->assertSame($defaultValue, $traitMock->{$getPropertyMethodName}(), $failMessage); }
public function testBatchDeleteForNoIncrementIdModel() { /** @var User[] $inputModels */ $inputModels = []; for ($i = 0; $i < 10; $i++) { $m = $inputModels[] = new User(); $m->username = "******" . rand(10000, 99999); $m->password = $m->username; } /** @var User[] $savedReturn */ $savedReturn = []; DbHelper::batchSave($inputModels, [], DbHelper::SAVE_MODE_AUTO, $savedReturn); /** @var User[] $savedUsers */ $savedUsers = $savedReturn['inserted']; $department = new Department(); $department->name = "Department testBatchSaveForNoIncrementIdField"; $department->save(false); /** @var UserDepartmentAssignment[] $inputModels */ $inputModels = []; $ids = []; $sql = ''; foreach ($savedUsers as $savedUser) { $m = $inputModels[] = new UserDepartmentAssignment(); $m->userId = $savedUser->id; $m->departmentId = $department->id; $ids[] = ['userId' => $savedUser->id, 'departmentId' => $department->id]; if ($sql != '') { $sql = $sql . ' OR '; } $sql = $sql . "(`userId`={$savedUser->id} AND `departmentId`={$department->id})"; } DbHelper::batchSave($inputModels, [], DbHelper::SAVE_MODE_AUTO); $return = DbHelper::batchDelete(UserDepartmentAssignment::tableName(), $ids); Debug::debug('Batch insert 10 UserDepartmentAssignment records. return=' . Json::encode($return)); $this->assertEquals(10, $return); $sql = 'SELECT * FROM ' . UserDepartmentAssignment::tableName() . ' WHERE ' . $sql; $return = UserDepartmentAssignment::findBySql($sql)->count(); $this->assertEquals(0, $return); }
/** * @test * @covers ::__debugInfo * @covers ::toArray */ public function debugInformationDoesNotContainUnsetProperties() { $data = ['age' => $this->faker->randomDigit, 'name' => $this->faker->name]; $dto = new DummyDto($data); unset($dto->name); $debugInformation = $dto->__debugInfo(); Debug::debug($debugInformation); $keys = array_keys($debugInformation); $this->assertNotContains('name', $keys); }
/** * @depends testEscapeQuotes **/ public function testInfoScript() { $start = microtime(false); $conn = $this->module->setConnection('remote1', 1); $res = $conn->executeCommand('EVAL', [$this->buildInfoScript('Queue:YProxy'), 0]); $end = microtime(false) - $start; Debug::debug($res); Debug::debug('time - ' . $end); }