/** * @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 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); } }
/** * @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; }
/** * @param $fieldName * @param $string * * @throws ExpectationException * * @return bool * * * @Then /^the field "([^"]*)" should have the following options:$/ */ public function theFieldShouldHaveTheFollowingOptions($fieldName, PyStringNode $string) { $field = $this->getCurrentPage()->findField($fieldName); $id = $field->getAttribute('id'); if ('select' === $field->getTagName()) { $options = $field->findAll('css', 'option'); } elseif ('input' === $field->getTagName() && 0 === strpos($id, 's2id_')) { $options = $field->getParent()->getParent()->findAll('css', 'option'); } else { throw $this->createExpectationException(sprintf('"%s" field is not a select field, can\'t have options.', $fieldName)); } $availableOptions = []; foreach ($options as $option) { $optionValue = trim($option->getText()); if ($optionValue) { $availableOptions[] = $optionValue; } } if (count(array_intersect($string->getLines(), $availableOptions)) === count($string->getLines())) { return true; } throw $this->createExpectationException(sprintf('"%s" field have these options (%s), but expected following options (%s).', $fieldName, implode(', ', $availableOptions), implode(', ', $string->getLines()))); }
/** * @Given /^the following response headers should be present:$/ */ public function assertExistingHeaders(PyStringNode $list) { $headers = $list->getLines(); foreach ($headers as $header) { assertTrue($this->getLastResponse()->hasHeader($header), 'Header "' . $header . '" should be present'); } }
/** * Accepts YAML fixture definitions similar to the ones used in SilverStripe unit testing. * * Example: Given there are the following member records: * member1: * Email: member1@test.com * member2: * Email: member2@test.com * * @Given /^there are the following ([^\s]*) records$/ */ public function stepThereAreTheFollowingRecords($dataObject, PyStringNode $string) { $yaml = array_merge(array($dataObject . ':'), $string->getLines()); $yaml = implode("\n ", $yaml); // Save fixtures into database // TODO Run prepareAsset() for each File and Folder record $yamlFixture = new \YamlFixture($yaml); $yamlFixture->writeInto($this->getFixtureFactory()); }
/** * Converts a PyStringObject to a normal stringObject with intents * * @param PyStringNode $pynode * * @return string */ public function convertPyStringToNormalString(PyStringNode $pynode) { $intent = " "; $intentedPyNodeText = ""; foreach ($pynode->getLines() as $pynodeLine) { $intentedPyNodeText .= $intent . $pynodeLine . "\n"; } return sprintf("{$intent}\"\"\"\n%s{$intent}\"\"\"", $intentedPyNodeText); }
/** * @Then /^the Adapter should report the scenario "([^"]*)" with following steps:$/ */ public function theAdapterShouldReportTheScenarioWithSteps($scenarioName, PyStringNode $expected_steps) { Phake::verify($this->_mockedClient, Phake::atLeast(1))->startScenario($scenarioName); // some steptext might be more than once in the result array $timesOccured = array_count_values($expected_steps->getLines()); foreach ($expected_steps->getLines() as $steptext) { $times_expected = $timesOccured[$steptext]; Phake::verify($this->_mockedClient, Phake::times($times_expected))->addStepToBuffer($steptext, null); } $this->_cntScenariosToBeStopped++; Phake::verify($this->_mockedClient, Phake::atLeast($this->_cntScenariosToBeStopped))->stopScenario(); }
/** * @Given /^a new "([^"]*)" document with:$/ */ public function aNewDocumentWith($collection, PyStringNode $string) { $database = $this->mongoDatabase; $obj = json_decode(trim(implode($string->getLines())), true); $this->mongoClient->{$database}->{$collection}->insert($obj); }
/** * @Then /^I should get:$/ */ public function getResult(PyStringNode $expected) { $tmp = substr($this->tmp, 0, -1); if (!function_exists('normalize')) { function normalize($str) { return str_replace('\\', '/', $str); } } // expected $lines = array_slice($expected->getLines(), 2); $expectedFiles = array_map(function ($line) { // remove everything before the filepath return normalize(trim(preg_replace('/\\d\\s*/', '', $line))); }, $lines); // actual $display = array_slice($this->display, 3); $actualFiles = array_map(function ($line) { // remove everything before the filepath return normalize(trim(preg_replace('/\\d\\s*/', '', $line))); }, $display); // compare if (0 === count($lines) && 0 !== count($display)) { throw new \Exception('Failed asserting that there are no suspects'); } foreach ($expectedFiles as $expected) { if (false !== ($key = array_search($expected, $actualFiles))) { unset($actualFiles[$key]); } else { throw new \Exception(sprintf('Failed asserting that file "%s" is a suspect', $expected)); } } if (0 !== count($actualFiles)) { throw new \Exception(sprintf('The file(s) "%s" are suspects too', implode('", "', $actualFiles))); } }
/** * @Given /^I specify the following transformations:$/ */ public function applyTransformations(PyStringNode $transformations) { foreach ($transformations->getLines() as $t) { $this->client->getEventDispatcher()->addListener('request.before_send', function ($event) use($t) { $event['request']->getQuery()->add('t', $t); }); } }
/** * @Given /^I test the exposed resources:$/ */ public function iTestTheExposedResources(PyStringNode $resources) { foreach ($resources->getLines() as $line) { $this->getClient()->get($this->locatePath($line)); } }
/** * treat payload as json data and try to decode it * * @var PyStringNode $node * * @return mixed */ private function getJsonFromPyStringNode(PyStringNode $node) { return \GuzzleHttp\json_decode(implode('', $node->getLines()), true); }