/** * @Then the system should have the following info sms subscription low balance reminder logs: * * @param PyStringNode $body */ public function theSystemShouldHaveTheFollowingOperations(PyStringNode $body) { /** @var CollectLogsTestWorker $collectLogsTestWorker */ $collectLogsTestWorker = $this->kernel->getContainer()->get('muchacuba.info_sms.subscription.low_balance_reminder.collect_logs_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectLogsTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Muchacuba\\InfoSms\\Subscription\\LowBalanceReminder\\Log'); }
/** * @Given the system should have the following recharge card profiles debt operations */ public function theSystemShouldHaveTheFollowingDebtOperations(PyStringNode $body) { /** @var CollectOperationsTestWorker $collectOperationsTestWorker */ $collectOperationsTestWorker = $this->kernel->getContainer()->get('muchacuba.recharge_card.profile.debt.collect_operations_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectOperationsTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Muchacuba\\RechargeCard\\Profile\\Debt\\Operation'); }
/** * @When I send a :method request to URL :url with body: */ public function iSendARequestToUrlWithBody($method, $url, PyStringNode $body) { $bodyReplace = $body->getRaw(); $bodyReplace = $this->replaceParameters($bodyReplace); $body = new PyStringNode([$bodyReplace], $body->getLine()); $this->restContext->iSendARequestToWithBody($method, $this->replaceParameters($url), $body); }
/** * @Given the system should have the following uniquenesses: */ public function theSystemShouldHaveTheFollowingUniquenesses(PyStringNode $body) { /** @var CollectUniquenessTestWorker $collectUniquenessTestWorker */ $collectUniquenessTestWorker = $this->kernel->getContainer()->get('cubalider.unique.collect_uniqueness_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectUniquenessTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Cubalider\\Uniqueness'); }
function it_saves_behat_feature_file(PyStringNode $config, Filesystem $filesystem) { $config->getRaw()->willReturn('Feature: test'); $filesystem->dumpFile(Argument::containingString('/features/feature.feature'), 'Feature: test')->shouldBeCalled(); $this->createWorkingDirectory(); $this->iHaveTheFeature($config); }
/** * @Given there exists a snippet template ":name" with the following property configuration */ public function thereExistsASnippetTemplateWithTheFollowingPropertyConfiguration($name, PyStringNode $string) { $template = <<<EOT <?xml version="1.0" ?> <template xmlns="http://schemas.sulu.io/template/template" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.sulu.io/template/template http://schemas.sulu.io/template/template-1.0.xsd" > <key>%s</key> <properties> <property name="title" type="text_line" mandatory="true"> <meta> <title lang="de">Title</title> <title lang="en">Title</title> </meta> </property> %s </properties> </template> EOT; $template = sprintf($template, $name, $string->getRaw()); $this->createStructureTemplate('snippet', $name, $template); }
/** * @Then I should get the following data: * * @param PyStringNode $string * * @throws \Exception */ public function iShouldGetTheFollowingData(PyStringNode $string) { $matcher = (new SimpleFactory())->createMatcher(); if (!$matcher->match(json_decode(json_encode($this->result), true), json_decode((string) $string->getRaw(), true))) { throw new \Exception($matcher->getError()); } }
/** * @Given the system should have the following internet profiles: * * @param PyStringNode $body * */ public function theSystemShouldHaveTheFollowingInternetProfiles(PyStringNode $body) { /** @var CollectProfilesTestWorker $collectProfilesTestWorker */ $collectProfilesTestWorker = $this->kernel->getContainer()->get('muchacuba.internet.collect_profiles_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectProfilesTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Muchacuba\\Internet\\Profile'); }
/** * @param string $code * @param PyStringNode $csv * * @Then /^exported file of "([^"]*)" should contain:$/ * * @throws ExpectationException * @throws \Exception */ public function exportedFileOfShouldContain($code, PyStringNode $csv) { $config = $this->getFixturesContext()->getJobInstance($code)->getRawConfiguration(); $path = $this->getMainContext()->getSubcontext('job')->getJobInstancePath($code); if (!is_file($path)) { throw $this->getMainContext()->createExpectationException(sprintf('File "%s" doesn\'t exist', $path)); } $delimiter = isset($config['delimiter']) ? $config['delimiter'] : ';'; $enclosure = isset($config['enclosure']) ? $config['enclosure'] : '"'; $escape = isset($config['escape']) ? $config['escape'] : '\\'; $csvFile = new \SplFileObject($path); $csvFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE); $csvFile->setCsvControl($delimiter, $enclosure, $escape); $expectedLines = []; foreach ($csv->getLines() as $line) { if (!empty($line)) { $expectedLines[] = explode($delimiter, str_replace($enclosure, '', $line)); } } $actualLines = []; while ($data = $csvFile->fgetcsv()) { if (!empty($data)) { $actualLines[] = array_map(function ($item) use($enclosure) { return str_replace($enclosure, '', $item); }, $data); } } $expectedCount = count($expectedLines); $actualCount = count($actualLines); assertSame($expectedCount, $actualCount, sprintf('Expecting to see %d rows, found %d', $expectedCount, $actualCount)); if (md5(json_encode($actualLines[0])) !== md5(json_encode($expectedLines[0]))) { throw new \Exception(sprintf('Header in the file %s does not match expected one: %s', $path, implode(' | ', $actualLines[0]))); } unset($actualLines[0]); unset($expectedLines[0]); foreach ($expectedLines as $expectedLine) { $originalExpectedLine = $expectedLine; $found = false; foreach ($actualLines as $index => $actualLine) { // Order of columns is not ensured // Sorting the line values allows to have two identical lines // with values in different orders sort($expectedLine); sort($actualLine); // Same thing for the rows // Order of the rows is not reliable // So we generate a hash for the current line and ensured that // the generated file contains a line with the same hash if (md5(json_encode($actualLine)) === md5(json_encode($expectedLine))) { $found = true; // Unset line to prevent comparing it twice unset($actualLines[$index]); break; } } if (!$found) { throw new \Exception(sprintf('Could not find a line containing "%s" in %s', implode(' | ', $originalExpectedLine), $path)); } } }
/** * @Then /^(?:the )?response should be:$/ */ public function theResponseShouldBe(PyStringNode $content) { if ($this->getResponseHeader('Content-Type') === 'application/json') { $this->assertJsonStringEqualsJsonString($this->adaptContent($content->getRaw()), $this->getResponse()->getContent(), sprintf('The content of the response is not the expected')); } else { Assertions::assertEquals($content->getRaw(), $this->getResponse()->getContent(), sprintf('The content of the response is not the expected')); } }
/** * @Then /^it should contain:$/ */ public function itShouldContain(PyStringNode $string) { $sql = file_get_contents($this->workingDirectory . '/behat_table.sql'); if (empty($sql) || !preg_match(sprintf('/%s/', preg_quote($string->getRaw())), $sql)) { $this->printDebug($sql); throw new Exception('Content not found'); } }
/** * Sends a HTTP request with a body * * @Given I send a :method request to :url with body: */ public function iSendARequestToWithBody($method, $url, PyStringNode $body) { $client = $this->getSession()->getDriver()->getClient(); // intercept redirection $client->followRedirects(false); $client->request($method, $this->locatePath($url), array(), array(), array(), $body->getRaw()); $client->followRedirects(true); }
/** * @Then I should see: */ public function iShouldSee(PyStringNode $content) { $displayArray = explode("\n", $this->tester->getDisplay()); array_walk($displayArray, function (&$line) { $line = rtrim($line); }); expect($displayArray)->shouldBeLike($content->getStrings()); }
/** * @Then /^(?:the )?response should equal to json:$/ */ public function theResponseShouldEqualToJson(PyStringNode $jsonString) { $expected = json_decode($jsonString->getRaw(), true); $actual = $this->lastResponse; if (null === $expected) { throw new \RuntimeException("Can not convert etalon to json:\n" . $jsonString->getRaw()); } assertEquals($expected, $actual, "Failed asserting that equals to \n" . print_r($actual, true)); }
/** * @When the system has the following user accounts: * * @param PyStringNode $body */ public function theSystemHasTheFollowingUserAccounts(PyStringNode $body) { /** @var CreateAccountTestWorker $createAccountTestWorker */ $createAccountTestWorker = $this->kernel->getContainer()->get('muchacuba.user.create_account_test_worker'); $items = json_decode($body->getRaw(), true); foreach ($items as $item) { $createAccountTestWorker->create($item['id'], $item['username'], $item['password'], $item['roles']); } }
/** * @Then the system should have the following info sms message stats: * * @param PyStringNode $body */ public function theSystemShouldHaveTheFollowingStats(PyStringNode $body) { $expected = (array) json_decode($body->getRaw(), true); /** @var CollectStatsTestWorker $collectStatsTestWorker */ $collectStatsTestWorker = $this->kernel->getContainer()->get('muchacuba.info_sms.message.collect_stats_test_worker'); $actual = iterator_to_array($collectStatsTestWorker->collect()); (new SimpleFactory())->createMatcher()->match($actual, $expected) ?: (new \PHPUnit_Framework_Constraint_IsEqual($expected))->evaluate($actual); $this->rootContext->ignoreState('Muchacuba\\InfoSms\\Message\\Stat'); }
/** * @Then the JSON should match pattern: * * @param PyStringNode $string * @throws \Exception */ public function theJsonShouldMatchPattern(PyStringNode $string) { $expected = $string->getRaw(); $current = (string) $this->getParameterBag()->get('response')->getBody(); $matcher = (new SimpleFactory())->createMatcher(); if (!$matcher->match($current, $expected)) { throw new \Exception($matcher->getError()); } }
/** @Then /^I should get:$/ */ public function iShouldGet(PyStringNode $string) { // if ((string) $string !== $this->output) { // throw new Exception( // "Actual output is:\n" . $this->output // ); // } assertEquals($string->getRaw(), $this->output); }
/** * @When /^I write a (?:spec|class) "([^"]*)" with following code$/ */ public function iWriteASpecWithFollowingCode($file, PyStringNode $codeContent) { $dirname = dirname($file); if (!file_exists($dirname)) { mkdir($dirname, 0777, true); } file_put_contents($file, $codeContent->getRaw()); require_once $file; }
/** * @Given /^"([^"]*)" file have following content:$/ */ public function xmlFileHaveFollowingContent($fileName, PyStringNode $fileContent) { $targetFolder = sprintf("%s/Project/app/teryt", $this->fixturesPath); if (!file_exists($targetFolder)) { mkdir($targetFolder); } $filePath = sprintf("%s/%s", $targetFolder, $fileName); file_put_contents($filePath, $fileContent->getRaw()); expect(file_exists($filePath))->toBe(true); }
public function testGetRaw() { $str = new PyStringNode(array('line1', 'line2', 'line3'), 0); $expected = <<<STR line1 line2 line3 STR; $this->assertEquals($expected, $str->getRaw()); }
/** * @Given there are sections for :publicationId publication in API: * * @param string $publicationId * @param PyStringNode $sectionsFromApi */ public function thereAreSectionsForPublicationInAPI($publicationId, PyStringNode $sectionsFromApi) { $sectionsFromApiWithPublication = str_replace('PUBLICATION_ID', $publicationId, $sectionsFromApi->getRaw()); $sectionsApiResponse = json_decode($sectionsFromApiWithPublication, true); $this->sectionsFromApi[$publicationId] = $sectionsApiResponse['sections']; $path = sprintf(self::SECTION_PATH_PATTERN, $publicationId); $this->apiHttpClient->shouldReceive('get')->with(Mockery::on(function (ApiHttpPathAndQuery $apiHttpPathAndQuery) use($path) { return $apiHttpPathAndQuery == ApiHttpPathAndQuery::createForPath($path); }))->andReturn($sectionsFromApiWithPublication); }
/** * @Then this file body contains: */ public function thisFileBodyContains(PyStringNode $string) { $pattern = getcwd() . '/' . $this->dir; $content = ''; foreach ((new Finder())->files()->in($pattern)->name('*' . $this->fileName) as $file) { $content = $file->getContents(); } if (strpos($content, $string->getRaw()) === false) { throw new \Exception('File contains wrong data'); } }
/** * @Then /^the console output should have lines ending in:$/ */ public function theConsoleOutputShouldHaveLinesEndingIn(PyStringNode $string) { $stdOutLines = explode(PHP_EOL, $this->lastBehatStdOut); $expectedLines = $string->getLines(); \PHPUnit_Framework_Assert::assertCount(count($expectedLines), $stdOutLines); foreach ($stdOutLines as $idx => $stdOutLine) { $suffix = isset($expectedLines[$idx]) ? $expectedLines[$idx] : '(NONE)'; $constraint = \PHPUnit_Framework_Assert::stringEndsWith($suffix); $constraint->evaluate($stdOutLine); } }
/** * @Then /^I should see:$/ */ public function iShouldSee(PyStringNode $string) { $page = $this->session->getPage(); $html = $page->getText(); $lines = $string->getLines(); foreach ($lines as $line) { if (strpos($html, $line) === false) { throw new Exception($line . ' not found on page'); } } }
/** * @Given /^Unpack files to the same directory:$/ */ public function unpackFilesToTheSameDirectory(PyStringNode $string) { $expectedFiles = $string->getLines(); $this->pagesDir = $this->package->unpack($expectedFiles); assertFileExists($this->pagesDir); chdir($this->pagesDir); $foundFiles = array_flip(glob('*.html')); assertCount(count($expectedFiles), $foundFiles); foreach ($expectedFiles as $file) { assertArrayHasKey($file, $foundFiles); } }
public function iSendARequestWithBody($method, $url, PyStringNode $string) { $name = md5($string); $this->loader->setTemplate($name, (string) $string); $token = $this->getParameterBag()->get('token'); $this->addHeader('Authorization', 'Bearer ' . $token); $body = $this->twig->render($name, $this->getParameterBag()->getAll()); $string = new PyStringNode(explode("\n", $body), $string->getLine()); $url = $this->parameterize($url); parent::iSendARequestWithBody($method, $url, $string); $this->getParameterBag()->set('response', $this->response); }
/** * @param PyStringNode $behatData * @param array $config * * @return array */ protected function getExpectedLines(PyStringNode $behatData, $config) { $delimiter = isset($config['delimiter']) ? $config['delimiter'] : ';'; $enclosure = isset($config['enclosure']) ? $config['enclosure'] : ''; $expectedLines = []; foreach ($behatData->getLines() as $line) { if (!empty($line)) { $expectedLines[] = explode($delimiter, str_replace($enclosure, '', $line)); } } return $expectedLines; }
/** * @Then the sitemap should have urls: */ public function theSitemapShouldHaveUrls(PyStringNode $string) { $xml = $this->getSession()->getPage()->getContent(); $crawler = new Crawler($xml); $assertUrls = explode("\n", $string->getRaw()); $foundUrls = []; foreach ($crawler->filter('url > loc') as $node) { $foundUrls[] = parse_url($node->nodeValue, PHP_URL_PATH); } if (count($diff = array_diff($assertUrls, $foundUrls)) > 0) { throw new \InvalidArgumentException(sprintf('Sitemap returned a difference: %s', json_encode(array_values($diff)))); } }
/** * @Given there is a file with: */ public function thereIsAFileWith(PyStringNode $string) { $file = uniqid() . ".php"; $container = $this->app->getContainer(); $generator = $container->get("Generator\\IndexGenerator"); $processor = $generator->getProcessor(); $processor->clearResultNodes(); $parser = $generator->getClassUtils()->getParser(); $parser->addProcessor($processor); $this->content = $string->getRaw(); $scope = $parser->parseContent($file, $this->content, null, false); $generator->processFileScope($this->project->getIndex(), $scope); }