protected function setUp() { $this->app = $app = new Container(); $db_config = ['driver' => 'pdo_sqlite', 'dbname' => 'sqlite:///:memory:']; $models = ['post.model' => function () use($app) { return new Post($app); }, 'comment.model' => 'Comment']; $app['db'] = function () use($db_config) { $db = \Doctrine\DBAL\DriverManager::getConnection($db_config); $sql = file_get_contents(codecept_data_dir() . '/dump.sql'); $db->exec($sql); return $db; }; foreach ($models as $name => $class) { if (is_callable($class)) { $callable = $class; } else { $callable = function () use($class, $app) { return new $class($app); }; } $app[$name] = $app->factory($callable); } $this->loadFixtures(); }
public function testImageComparer(FunctionalTester $I) { $I->amInPath($this->workDir); copy(codecept_data_dir() . 'image1.png', $this->workDir . '/image1.png'); copy(codecept_data_dir() . 'image2.png', $this->workDir . '/image2.png'); copy(codecept_data_dir() . 'image3.png', $this->workDir . '/image3.png'); $comparer = new ImageComparer(); // Check difference between the same image. $difference = $comparer->difference('image1.png', 'image1.png', 'image.diff.png'); $I->assertTrue($difference === 0); $I->assertTrue(file_exists('image.diff.png')); unlink('image.diff.png'); // Compare different images. $difference = $comparer->difference('image1.png', 'image2.png', 'image.diff.png'); $I->assertTrue($difference > 0); codecept_debug($difference); $I->assertTrue(file_exists('image.diff.png')); // Compare different sized images. $difference = $comparer->difference('image1.png', 'image3.png', 'image.diff.png'); $I->assertTrue($difference > 0); codecept_debug($difference); $I->assertTrue(file_exists('image.diff.png')); // Check missing command. $comparer->setCommand('this_command_doesnt_exist'); try { $difference = $comparer->difference('image1.png', 'image2.png', 'image.diff.png'); $I->fail("Bad command didn't throw an Exception"); } catch (Exception $e) { // All good. } }
/** * @param string $fileName * * @return $this */ public function haveAFileLikeThis($fileName) { $expectedDir = codecept_data_dir('expected'); $actualDir = codecept_data_dir('actual'); Assert::assertContains(file_get_contents("{$expectedDir}/{$fileName}"), file_get_contents("{$actualDir}/{$fileName}")); return $this; }
/** * @group core */ public function testLoadAllTests() { $this->testLoader = new \Codeception\TestLoader(codecept_data_dir() . 'claypit/tests'); $this->testLoader->loadTests(); $this->assertContainsTestName('order/AnotherCept', $this->testLoader->getTests()); $this->assertContainsTestName('MageGuildCest::darkPower', $this->testLoader->getTests()); $this->assertContainsTestName('FailingTest::testMe', $this->testLoader->getTests()); }
protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('host'); $user = $input->getOption('user'); $pass = $input->getOption('pass'); $dbName = $input->getArgument('name'); try { $this->dump = $this->pdoFactory->makeDump($host, $user, $pass, $dbName); } catch (\PDOException $e) { throw new RuntimeException('Error while connecting to database [' . $dbName . ']: ' . $e->getMessage()); } if (false === $this->dump) { $output->writeln('<error>Something went wrong with the dump component instance.</error>'); return false; } \Codeception\Configuration::config(); if (!empty($input->getOption('dump-file'))) { $dumpFile = $input->getOption('dump-file'); } else { $dumpFile = codecept_data_dir($input->getArgument('snapshot') . '.sql'); } $output->writeln('<info>Dump file will be written to [' . $dumpFile . ']</info>'); if (!empty($input->getOption('dist-dump-file'))) { $distDumpFile = $input->getOption('dist-dump-file'); } else { $distDumpFile = codecept_data_dir($input->getArgument('snapshot') . '.dist.sql'); } $output->writeln('<info>Distribution version of dump file will be written to [' . $distDumpFile . ']</info>'); $skipTables = $input->getOption('skip-tables'); if (!empty($skipTables)) { $tables = explode(',', $skipTables); foreach ($tables as $table) { $this->dump->tables[$table] = \MySQLDump::NONE; } } $memory = fopen('php://memory', 'w'); $this->dump->write($memory); rewind($memory); $dumpContents = stream_get_contents($memory); if (!$this->filesystem->file_put_contents($dumpFile, $dumpContents)) { $output->writeln('<error>Could not write dump to [' . $dumpFile . ']</error>'); return false; } $output->writeln('<info>Dump file written to [' . $dumpFile . ']</info>'); $localUrl = $input->getOption('local-url'); $distUrl = $input->getOption('dist-url'); $localDomain = rtrim(preg_replace('~http(s)*:\\/\\/(www\\.)*~', '', $localUrl), '/'); $distDomain = rtrim(preg_replace('~http(s)*:\\/\\/(www\\.)*~', '', $distUrl), '/'); $distDumpContents = str_replace($localDomain, $distDomain, $dumpContents); if (!$this->filesystem->file_put_contents($distDumpFile, $distDumpContents)) { $output->writeln('<error>Could not write dist dump to [' . $distDumpFile . ']</error>'); return false; } $output->writeln('<info>Distribution version of dump file written to [' . $distDumpFile . ']</info>'); $output->writeln('<comment>Any occurrence of [' . $localDomain . '] in it was replaced with [' . $distDomain . ']</comment>'); parent::execute($input, $output); return true; }
public function checkOtherReasonRequest() { $I = $this; $advFlatId = file_get_contents(codecept_data_dir('advertFlatId.json')); $I->amOnPage(AdvertsList::$URL . '/' . $advFlatId . '/edit'); $I->waitForElement(AdvertsList::$editAdvObjInfoTab); $I->see(Lists::unpubReason1, AdvertsList::$advInfoTable); $I->see(Flat::descriptionOtherReason, AdvertsList::$advInfoTable); $I->see(Lists::status3, AdvertsList::$advInfoTable); }
/** * @param string $fileName * * @return $this */ public function haveAValidCheckstyleReport($fileName) { $fileName = codecept_data_dir($fileName); $doc = new \DOMDocument(); $doc->loadXML(file_get_contents($fileName)); $xpath = new DOMXPath($doc); $rootElement = $xpath->query('/checkstyle'); Assert::assertEquals(1, $rootElement->length, 'Root element of the Checkstyle XML is exists.'); return $this; }
public function testTags() { $this->loader = new \Codeception\Test\Loader\Gherkin(['gherkin' => ['contexts' => ['default' => ['GherkinTestContext'], 'tag' => ['important' => ['TagGherkinContext']]]]]); $this->loader->loadTests(codecept_data_dir('refund.feature')); $test = $this->loader->getTests()[0]; /** @var $test \Codeception\Test\Gherkin * */ $test->getMetadata()->setServices($this->getServices()); $test->test(); $this->assertEquals('aXc', self::$calls); }
protected function _before() { $config = ['driver' => 'pdo_sqlite', 'dbname' => 'sqlite:///:memory:']; $this->db = \Doctrine\DBAL\DriverManager::getConnection($config); $schema = file_get_contents(codecept_data_dir() . '/dump.sql'); $this->db->exec($schema); // $this->db->insert('table_comment',['username'=>'tester','post_id'=>1]); // $this->db->query('select * from table_comment')->fetchAll(); $this->record = new Record(); $this->record->connection($this->db); }
public function setUp() { $this->dispatcher = new Symfony\Component\EventDispatcher\EventDispatcher(); $di = new \Codeception\Lib\Di(); $this->moduleContainer = new \Codeception\Lib\ModuleContainer($di, []); \Codeception\Module\EmulateModuleHelper::$onlyActions = []; \Codeception\Module\EmulateModuleHelper::$excludeActions = []; $module = $this->moduleContainer->create('EmulateModuleHelper'); $module->_initialize(); $this->testcase = new \Codeception\TestCase\Cept(); $this->testcase->configDispatcher($this->dispatcher)->configName('mocked test')->configFile(codecept_data_dir() . 'SimpleCept.php')->configDi($di)->configModules($this->moduleContainer)->initConfig(); }
/** * @group core */ public function testLoadAllTests() { Codeception\Util\Autoload::addNamespace('Math', codecept_data_dir() . 'claypit/tests/_support/Math'); // to autoload dependencies $this->testLoader = new \Codeception\Test\Loader(['path' => codecept_data_dir() . 'claypit/tests']); $this->testLoader->loadTests(); $testNames = $this->getTestNames($this->testLoader->getTests()); $this->assertContainsTestName('AnotherCept', $testNames); $this->assertContainsTestName('MageGuildCest:darkPower', $testNames); $this->assertContainsTestName('FailingTest:testMe', $testNames); $this->assertContainsTestName('MathCest:testAddition', $testNames); $this->assertContainsTestName('MathTest:testAll', $testNames); }
static function uniqueCadastralNumber() { // if (self::$currentCadastralNumber) { // return self::$currentCadastralNumber; // } // $number = trim(file_get_contents(codecept_data_dir('cadastral_number.txt')),":"); // $number = trim($constFileName, ':'); $number = substr(str_shuffle("1234567890123456789"), 0, 19); // self::$currentCadastralNumber = $number; self::$currentCadastralNumber = preg_replace("/^(.{10})(.{2})(.{3})(.{4})\$/", "\$1:\$2:\$3:\$4", $number); file_put_contents(codecept_data_dir('cadastral_number.txt'), self::$currentCadastralNumber); return $number; }
public function checkAdvFlatProperties() { $I = $this; $advFlatId = file_get_contents(codecept_data_dir('advertFlatId.json')); $I->amOnPage(AdvertsList::$URL . '/' . $advFlatId . '/edit'); $I->waitForElement(AdvertsList::$editAdvObjInfoTab); $I->see(Flat::status0, AdvertsList::$editAdvStatus); $I->click(AdvertsList::$editAdvObjInfoTab); $I->see(Flat::category, AdvertsList::$editAdvObjTable); $I->see(Flat::categoryType0, AdvertsList::$editAdvObjTable); $I->see(Flat::region, AdvertsList::$editAdvObjTable); $I->see(Flat::city, AdvertsList::$editAdvObjTable); $I->see(Flat::houseNumber, AdvertsList::$editAdvObjTable); $I->see(Flat::$currentFlatNumber, AdvertsList::$editAdvObjTable); $I->click(AdvertsList::$editAdvTab); $I->waitForElement(AdvertsList::$editAdvDescription); $I->see(Flat::operationType1, AdvertsList::$editAdvOperationType); $desVal = $I->grabValueFrom(AdvertsList::$editAdvDescription); codecept_debug($desVal); if ($desVal !== Flat::descriptionFlatSell) { $I->see('error!!!'); } // $I->see(Flat::descriptionFlatSell, AdvertsList::$editAdvDescription); // $I->seeInFormFields('form[name=createAdvertForm]',['description' => Flat::descriptionFlatSell]); // $I->seeInField(AdvertsList::$editAdvDescription, Flat::descriptionFlatSell); $priceVal = $I->grabValueFrom(AdvertsList::$editAdvPrice); codecept_debug($priceVal); if ($priceVal !== Flat::priceFlatSell) { $I->see('error!!!'); } // $I->see(Flat::priceFlatSell, AdvertsList::$editAdvPrice); $I->see(Flat::market1, AdvertsList::$editAdvMarketType); $I->see(Flat::repair0, AdvertsList::$editAdvRepair); $ownNameVal = $I->grabValueFrom(AdvertsList::$editAdvOwnerName); codecept_debug($ownNameVal); if ($ownNameVal !== Flat::ownerName) { $I->see('error!!!'); } // $I->see(Flat::ownerName, AdvertsList::$editAdvOwnerName); $ownContactVal = $I->grabValueFrom(AdvertsList::$editAdvOwnerContacts); codecept_debug($ownContactVal); if ($ownContactVal !== Flat::ownerContacts) { $I->see('error!!!'); } // $I->see(Flat::ownerContacts, AdvertsList::$editAdvOwnerContacts); $I->see('Я владелец', AdvertsList::$editAdvOwnerLink); $I->see('Сохранить', AdvertsList::$editAdvSubmit); }
public function testWebsiteScraper_aPageWithoutItemsReturnsException() { $mockDownloader = \Mockery::mock(WebsiteDownloader::class); $mockDownloader->shouldReceive('download')->once()->andReturn(file_get_contents(codecept_data_dir() . 'plpPage.html')); $sampleProduct = new Product("Title", "Description", "0.01", "Big"); $mockPDPParser = \Mockery::mock(PDPParser::class); $mockPDPParser->shouldReceive('parseUrl')->times(7)->andReturn($sampleProduct); $pdpParser = new WebsiteScraper($mockPDPParser, $mockDownloader); $productResults = $pdpParser->getProductsForUrl('http://fakeUrl.com'); $products = $productResults->getProducts(); $this->assertEquals(7, count($products)); $this->assertEquals("Title", $products[0]->title); $this->assertEquals("Description", $products[0]->description); $this->assertEquals("0.01", $products[0]->price); $this->assertEquals("Big", $products[0]->size); }
public function testGroupEventsAreFired() { $events = []; $eventListener = function ($event, $eventName) use(&$events) { $events[] = $eventName; }; $this->dispatcher->addListener('test.before', $eventListener); $this->dispatcher->addListener('test.before.admin', $eventListener); $this->dispatcher->addListener('test.after', $eventListener); $this->dispatcher->addListener('test.after.admin', $eventListener); $this->suiteman->loadTests(codecept_data_dir() . 'SimpleAdminGroupCest.php'); $this->suiteman->run($this->runner, new \PHPUnit_Framework_TestResult(), ['silent' => true, 'colors' => false, 'steps' => true, 'debug' => false]); $this->assertContains('test.before', $events); $this->assertContains('test.before.admin', $events); $this->assertContains('test.after.admin', $events); }
public function addClient(FunctionalTester $I) { $client_data = json_decode('{ "name": "testname", "email": "*****@*****.**", "phone": "+7 (912) 12-34-99999", "status": "possible" }', true); $I->haveHttpHeader('Content-Type', 'application/json'); $I->sendPOST('/client', $client_data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(201); $I->canSeeResponseIsValidOnSchemaFile(codecept_data_dir() . 'schema/client.json'); $data = $I->grabDataFromResponseByJsonPath('$.data')[0]; unset($data['id']); $I->assertEquals($client_data, $data); }
/** * @test * it should dump the database to the data folder by default */ public function it_should_dump_the_database_to_the_data_folder_by_default() { $expectedDump = codecept_data_dir('issue4455.sql'); $expectedDistDump = codecept_data_dir('issue4455.dist.sql'); $application = new Application(); /** @var \tad\WPBrowser\Services\Db\MySQLDumpFactoryInterface $factory */ $factory = $this->prophesize('\\tad\\WPBrowser\\Services\\Db\\MySQLDumpFactoryInterface'); $dump = $this->prophesize('MySQLDump'); $dump->write(Argument::any())->shouldBeCalled(); $filesystem = $this->prophesize('tad\\WPBrowser\\Filesystem\\Filesystem'); $filesystem->file_put_contents($expectedDump, Argument::type('string'))->willReturn(true); $filesystem->file_put_contents($expectedDistDump, Argument::type('string'))->willReturn(true); $factory->makeDump(Argument::type('string'), Argument::type('string'), Argument::type('string'), Argument::type('string'))->willReturn($dump->reveal()); $application->add(new DbSnapshot(null, $factory->reveal(), $filesystem->reveal())); $command = $application->find('db:snapshot'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'name' => 'db', 'snapshot' => 'issue4455']); }
public function toGenerateDocumentation(CliGuy $I) { $sourceFile = codecept_data_dir() . 'TestedRoboTask.php'; $I->seeFileFound($sourceFile); include $sourceFile; $I->assertTrue(class_exists('TestedRoboTask')); $collection = $I->collectionBuilder(); $taskGenerator = $collection->taskGenDoc("TestedRoboTask.md"); $taskGenerator->filterClasses(function (\ReflectionClass $r) { return !($r->isAbstract() || $r->isTrait()) && $r->implementsInterface('Robo\\Contract\\TaskInterface'); })->prepend("# TestedRoboTask Tasks"); $taskGenerator->docClass('TestedRoboTask'); $taskGenerator->filterMethods(function (\ReflectionMethod $m) { if ($m->isConstructor() || $m->isDestructor() || $m->isStatic()) { return false; } $undocumentedMethods = ['', 'run', '__call', 'inflect', 'injectDependencies', 'getCommand', 'getPrinted', 'getConfig', 'setConfig', 'logger', 'setLogger', 'setProgressIndicator', 'progressIndicatorSteps', 'setBuilder', 'getBuilder', 'collectionBuilder']; return !in_array($m->name, $undocumentedMethods) && $m->isPublic(); // methods are not documented })->processClassSignature(function ($c) { return "## " . preg_replace('~Task$~', '', $c->getShortName()) . "\n"; })->processClassDocBlock(function (\ReflectionClass $c, $doc) { $doc = preg_replace('~@method .*?(.*?)\\)~', '* `$1)` ', $doc); $doc = str_replace('\\' . $c->name, '', $doc); return $doc; })->processMethodSignature(function (\ReflectionMethod $m, $text) { return str_replace('#### *public* ', '* `', $text) . '`'; })->processMethodDocBlock(function (\ReflectionMethod $m, $text) { return $text ? ' ' . trim(strtok($text, "\n"), "\n") : ''; }); $collection->run(); $I->seeFileFound('TestedRoboTask.md'); $contents = file_get_contents('TestedRoboTask.md'); $I->assertContains('A test task file. Used for testig documentation generation.', $contents); $I->assertContains('taskTestedRoboTask', $contents); $I->assertContains('Set the destination file', $contents); }
public function attachFile($field, $filename) { $el = $this->findField($field); // in order to be compatible on different OS $filePath = realpath(codecept_data_dir() . $filename); if (!is_readable($filePath)) { throw new \InvalidArgumentException("file not found or not readable: {$filePath}"); } // in order for remote upload to be enabled $el->setFileDetector(new LocalFileDetector()); // skip file detector for phantomjs if ($this->isPhantom()) { $el->setFileDetector(new UselessFileDetector()); } $el->sendKeys($filePath); }
<?php use Codeception\Util\Stub; use Facebook\WebDriver\Remote\RemoteWebDriver; use Facebook\WebDriver\WebDriverBy; use Facebook\WebDriver\WebDriverKeys; require_once codecept_data_dir() . 'app/data.php'; require_once __DIR__ . '/../unit/Codeception/Module/TestsForBrowsers.php'; class WebDriverTest extends TestsForBrowsers { /** * @var \Codeception\Module\WebDriver */ protected $module; /** * @var RemoteWebDriver */ protected $webDriver; const MODULE_CLASS = 'Codeception\\Module\\WebDriver'; const WEBDRIVER_CLASS = 'Facebook\\WebDriver\\Remote\\RemoteWebDriver'; public function _before() { $this->module = $this->getModule('WebDriver'); $this->webDriver =& $this->getModule('WebDriver')->webDriver; } public function _after() { data::clean(); } public function testClickEventOnCheckbox() {
<?php $I = new CliGuy($scenario); $I->wantTo('flatten dir with FlattenDir task'); $I->amInPath(codecept_data_dir() . 'sandbox'); $I->taskFlattenDir(['some/deeply/nested/*.re' => 'flattened', '*.txt' => 'flattened'])->run(); $I->seeDirFound('flattened'); $I->seeFileFound('structu.re', 'flattened'); $I->seeFileFound('a.txt', 'flattened'); $I->seeFileFound('b.txt', 'flattened');
<?php require_once codecept_data_dir() . 'TestedRoboFile.php'; class RunnerTest extends \Codeception\TestCase\Test { /** * @var \Robo\Runner */ private $runner; /** * @var \Symfony\Component\Console\Application */ private $app; const ROBOFILE = 'TestedRoboFile'; protected function _before() { $this->runner = new \Robo\Runner(); $this->app = $this->runner->createApplication(self::ROBOFILE); } public function testAllowEmptyValuesAsDefaultsToOptionalOptions() { $command = $this->createCommand('hello'); $yell = $command->getDefinition()->getOption('yell'); verify($yell->isValueOptional())->equals(false); verify($yell->getDefault())->equals(false); $to = $command->getDefinition()->getOption('to'); verify($to->isValueOptional())->equals(true); verify($to->getDefault())->equals(null); } public function testCommandDocumentation() {
public function testParseFileWithClass() { if (version_compare(PHP_VERSION, '5.5.0', '<')) { $this->markTestSkipped('only for php 5.5'); } $classes = Parser::getClassesFromFile(codecept_data_dir('php55Test')); $this->assertEquals(['php55Test'], $classes); }
public static function setUpBeforeClass() { self::$cwdBackup = getcwd(); self::$path = codecept_data_dir('folder-structures/wpbootstrap-test-root'); }
public function testFailDependenciesPrimitiveParam() { require_once codecept_data_dir() . 'FailDependenciesPrimitiveParam.php'; $this->injectionShouldFail('Parameter \'required\' must have default value'); $this->di->instantiate('FailDependenciesPrimitiveParam\\IncorrectDependenciesClass'); }
public function _before(CliGuy $I) { $I->amInPath(codecept_data_dir('sandbox')); }
function _before(FunctionalTester $I) { $I->haveFixtures(['userAccount' => ['class' => UserAccountFixture::className(), 'dataFile' => codecept_data_dir() . 'user_account.php']]); $I->amOnRoute('site/login'); }
<?php /** * @var \Codeception\Scenario $scenario */ $roboTaskName = 'lint:default-std-output'; $expectedDir = codecept_data_dir('expected'); $i = new AcceptanceTester($scenario); $i->wantTo("Run Robo task '<comment>{$roboTaskName}</comment>'."); $i->clearTheReportsDir()->runRoboTask($roboTaskName)->expectTheExitCodeToBe(2)->seeThisTextInTheStdOutput(file_get_contents("{$expectedDir}/native.default.txt"))->seeThisTextInTheStdError('One or more errors were reported (and any number of warnings)');
public function _before() { $this->tester->haveFixtures(['user' => ['class' => UserFixture::className(), 'dataFile' => codecept_data_dir() . 'user.php']]); }
/** * @group core */ public function testClassesFromFile() { $classes = Parser::getClassesFromFile(codecept_data_dir('DummyClass.php')); $this->assertContains('DummyClass', $classes); $classes = Parser::getClassesFromFile(codecept_data_dir('SimpleWithDependencyInjectionCest.php')); $this->assertContains('simpleDI\\LoadedTestWithDependencyInjectionCest', $classes); $this->assertContains('simpleDI\\AnotherCest', $classes); }