/** * @Given /^I have restaurant with following data:$/ */ public function iHaveRestaurantWithFollowingData(TableNode $table) { $restaurantData = $table->getRow(1); $street = new Street($restaurantData[1], $restaurantData[2]); $address = new Address($street, new City($restaurantData[3]), new Country($restaurantData[4])); $this->restaurant = new Restaurant(new RestaurantId(), $restaurantData[0], $address); }
/** * @Then the post list table looks like */ public function thePostListTableLooksLike(TableNode $expectedTable) { $WPTable = $this->getTable(); $actualTable = $WPTable->getTableNode(); $expectedTableHeader = $expectedTable->getRow(0); $actualTableHeader = $actualTable->getRow(0); //Check table headers if (count($actualTableHeader) != count($expectedTableHeader)) { $message = "Columns do no match:\n"; $message .= $actualTable->getTableAsString(); throw new \Exception($message); } else { foreach ($expectedTableHeader as $index => $column) { if ($column != $actualTableHeader[$index]) { $message = "Columns do no match:\n"; $message .= $actualTable->getTableAsString(); throw new \Exception($message); } } } //Check rows $expectedRows = $expectedTable->getRows(); foreach ($expectedRows as $rowIndex => $rowColumns) { $actualRow = $actualTable->getRow($rowIndex); foreach ($rowColumns as $column => $expectedCellValue) { if (trim($expectedCellValue) != $actualRow[$column]) { $message = sprintf("(Row %d) %s does not match expected %s:\n", $rowIndex, $actualRow[$column], $expectedCellValue); $message .= $actualTable->getTableAsString(); throw new \Exception($message); } } } }
/** * Create event. * * @Given /^I create a calendar event with form data:$/ * @param TableNode $data * @return array the list of actions to perform */ public function i_create_a_calendar_event_with_form_data($data) { // Get the event name. $eventname = $data->getRow(1); $eventname = $eventname[1]; return array(new Given('I follow "' . get_string('monththis', 'calendar') . '"'), new Given('I click on "' . get_string('newevent', 'calendar') . '" "button"'), new Given('I set the following fields to these values:', $data), new Given('I press "' . get_string('savechanges') . '"'), new Given('I should see "' . $eventname . '"')); }
/** * @Then I should get a :arg1 with a rank :arg2 with the following cards: */ public function iShouldGetAWithARankWithTheFollowingCards($arg1, $arg2, TableNode $table) { $expectedCards = $table->getRow(0); $result = $this->handFinder->findHand($this->cards); PHPUnit_Framework_Assert::assertContains($arg1, $result); PHPUnit_Framework_Assert::assertContains($arg2, $result); foreach ($expectedCards as $expectedCard) { PHPUnit_Framework_Assert::assertContains($expectedCard, $result['cards']); } }
/** * Put the specified questions on the specified pages of a given quiz. * * The first row should be column names: * | question | page | maxmark | * The first two of those are required. The others are optional. * * question needs to uniquely match a question name. * page is a page number. Must start at 1, and on each following * row should be the same as the previous, or one more. * maxmark What the question is marked out of. Defaults to question.defaultmark. * * Then there should be a number of rows of data, one for each question you want to add. * * For backwards-compatibility reasons, specifying the column names is optional * (but strongly encouraged). If not specified, the columns are asseumed to be * | question | page | maxmark |. * * @param string $quizname the name of the quiz to add questions to. * @param TableNode $data information about the questions to add. * * @Given /^quiz "([^"]*)" contains the following questions:$/ */ public function quiz_contains_the_following_questions($quizname, TableNode $data) { global $CFG, $DB; require_once __DIR__ . '/../../editlib.php'; $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST); // Deal with backwards-compatibility, optional first row. $firstrow = $data->getRow(0); if (!in_array('question', $firstrow) && !in_array('page', $firstrow)) { if (count($firstrow) == 2) { $headings = array('question', 'page'); } else { if (count($firstrow) == 3) { $headings = array('question', 'page', 'maxmark'); } else { throw new ExpectationException('When adding questions to a quiz, you should give 2 or three 3 things: ' . ' the question name, the page number, and optionally the maxiumum mark. ' . count($firstrow) . ' values passed.', $this->getSession()); } } $rows = $data->getRows(); array_unshift($rows, $headings); $data->setRows($rows); } // Add the questions. $lastpage = 0; foreach ($data->getHash() as $questiondata) { if (!array_key_exists('question', $questiondata)) { throw new ExpectationException('When adding questions to a quiz, ' . 'the question name column is required.', $this->getSession()); } if (!array_key_exists('page', $questiondata)) { throw new ExpectationException('When adding questions to a quiz, ' . 'the page number column is required.', $this->getSession()); } // Question id. $questionid = $DB->get_field('question', 'id', array('name' => $questiondata['question']), MUST_EXIST); // Page number. $page = clean_param($questiondata['page'], PARAM_INT); if ($page <= 0 || (string) $page !== $questiondata['page']) { throw new ExpectationException('The page number for question "' . $questiondata['question'] . '" must be a positive integer.', $this->getSession()); } if ($page < $lastpage || $page > $lastpage + 1) { throw new ExpectationException('When adding questions to a quiz, ' . 'the page number for each question must either be the same, ' . 'or one more, then the page number for the previous question.', $this->getSession()); } $lastpage = $page; // Max mark. if (!array_key_exists('maxmark', $questiondata) || $questiondata['maxmark'] === '') { $maxmark = null; } else { $maxmark = clean_param($questiondata['maxmark'], PARAM_FLOAT); if (!is_numeric($questiondata['maxmark']) || $maxmark < 0) { throw new ExpectationException('The max mark for question "' . $questiondata['question'] . '" must be a positive number.', $this->getSession()); } } // Add the question. quiz_add_quiz_question($questionid, $quiz, $page, $maxmark); } quiz_update_sumgrades($quiz); }
/** * @When /^I create restaurant with following data:$/ */ public function iCreateRestaurantWithFollowingData(TableNode $table) { $restaurantData = $table->getRow(1); try { $street = new Street($restaurantData[1], $restaurantData[2]); $address = new Address($street, new City($restaurantData[3]), new Country($restaurantData[4])); $restaurant = new Restaurant(new RestaurantId(), $restaurantData[0], $address); $this->restaurantRepository->add($restaurant); } catch (\Exception $e) { } }
/** * Create event. * * @Given /^I create a calendar event:$/ * @param TableNode $data */ public function i_create_a_calendar_event($data) { // Get the event name. $eventname = $data->getRow(1); $eventname = $eventname[1]; // Click to create new event. $this->execute("behat_general::i_click_on", array(get_string('newevent', 'calendar'), "button")); // Set form fields. $this->execute("behat_forms::i_set_the_following_fields_to_these_values", $data); // Save event. $this->execute("behat_forms::press_button", get_string('savechanges')); // Check if event is created. Being last step, don't need to wait or check for exceptions. $this->execute("behat_general::assert_page_contains_text", $eventname); }
/** * @Given /^I create a "([^"]*)" entity with the settings:$/ */ public function iCreateAEntityWithTheSettings($entity_type, TableNode $table) { $headers = $table->getRow(0); foreach ($table->getRows() as $key => $value) { if ($key == 0) { continue; } $this->setValueFromReference($value); /** @var nuntiusRoomEntity $entity */ $entity = entity_create($this->entityTypes[$entity_type], array_combine($headers, $value)); $entity->save(); $this->entities[$this->entityTypes[$entity_type]][] = $entity->identifier(); } }
/** * @Given /^following run for "([^"]+)":$/ */ public function followingRunFor($name, TableNode $table) { $app = $this->getApplication(); $project = $app['project_list']->get($name); $methods = array('created_at' => function (RunUnit $unit, $val) { $int = new \DateInterval($val); $now = new \DateTime(); $unit->setCreatedAt($now->sub($int)); }, 'started_at' => function (RunUnit $unit, $val) { $int = new \DateInterval($val); $now = new \DateTime(); $unit->setStartedAt($now->sub($int)); }, 'finished_at' => function (RunUnit $unit, $val) { $int = new \DateInterval($val); $now = new \DateTime(); if (!$unit->getStartedAt()) { $unit->setStartedAt($now->sub($int)); } $unit->setFinishedAt($now->sub($int)); }, 'feature' => function (RunUnit $unit, $val) { $unit->setFeature($val); }, 'return_code' => function (RunUnit $unit, $val) { $unit->setReturnCode($val); }); $headers = $table->getRow(0); foreach ($headers as $col) { if (!isset($methods[$col])) { throw new \RuntimeException(sprintf('No handler for column "%s".', $col)); } } $run = new Run(); $run->setProjectName($name); $units = $run->getUnits(); foreach ($table->getRows() as $i => $row) { if ($i == 0) { continue; } $unit = new RunUnit(); foreach ($headers as $i => $header) { $value = $row[$i]; if ($value === '@null') { continue; } $methods[$header]($unit, $row[$i]); } $units->add($unit); } $app['run_storage']->saveRun($run); }
/** * @Given /^There are records in table \'([^\']+)\'$/ * @param string $tableName * @param TableNode $table */ public function thereAreItemsInTable($tableName, TableNode $table) { /* @var $connection \Doctrine\DBAL\Connection */ $connection = $this->container->get('doctrine')->getConnection(); $fields = $table->getRow(0); $tableFields = '`' . implode('`, `', $fields) . '`'; $tablePlaceholders = ':' . implode(', :', $fields); $sth = $connection->prepare(str_replace(['__table', '__fields', '__placeholders'], [$tableName, $tableFields, $tablePlaceholders], ' INSERT INTO __table (__fields) VALUES (__placeholders) ')); foreach ($table as $row) { $sth->execute($row); } }
/** * @Then /^I should be on the page for "(?P<model>[^"]*)" with following details:$/ */ public function iShouldBeOnThePageForWithInIts($model, TableNode $table) { $model = ucfirst($model); $attribute = $table->getRow(0); $value = $table->getRow(1); $obj = $model::model()->findByAttributes(array($attribute[0] => $value[0])); if ($obj === null) { throw new CDbException(ucfirst($model) . ' with "' . $attribute . '" equals to "' . $value . '" not found'); } $expected = Yii::app()->urlManager->createUrl(strtolower($model) . '/view', array('id' => $obj->id)); $this->assertPageAddress($expected); }
/** * @Then /^I should get the following response:/ * * @param TableNode $node */ public function checkWithTableNode(TableNode $node) { $data = array_combine($node->getRow(0), $node->getRow(1)); Assertion::eq($data, $this->response); }
/** * @When I try to persist the following user: * * @param TableNode $table */ public function persistUser(TableNode $table) { $row = $table->getRow(1); $user = User::create($row[0], $row[1], $row[2], new PhpPasswordHasher()); $this->getEntityManager()->getRepository('Account:User')->save($user); $this->user = $user; }
/** * @Then I should see the following name suggestions: */ public function iShouldSeeTheFollowingNameSuggestions(TableNode $table) { Assertion::inArray($table->getRow(1)[0], $this->suggestions); Assertion::count($this->suggestions, 2); }
/** * @When I send a registration request with the following credentials: * * @param TableNode $table */ public function iSendARegistrationRequestWithTheFollowingCredentials(TableNode $table) { $row = $table->getRow(1); $this->username = $row[0]; $this->response = $this->performRequest('POST', '/api/users.json', ['username' => $row[0], 'password' => $row[1], 'email' => $row[2], 'locale' => $row[3]], true, [], [], 200, true, null, true); }
/** * {@inheritdoc} */ protected function printStepTableArgument(TableNode $table, $color = null) { $this->writeln('<table class="argument">'); $this->writeln('<thead>'); $headers = $table->getRow(0); $this->printColorizedTableRow($headers, 'row'); $this->writeln('</thead>'); $this->writeln('<tbody>'); foreach ($table->getHash() as $row) { $this->printColorizedTableRow($row, 'row'); } $this->writeln('</tbody>'); $this->writeln('</table>'); }
public function testGetRowWithLineNumbers() { $table = new TableNode(array(5 => array('username', 'password'), 10 => array('everzet', 'qwerty'), 13 => array('antono', 'pa$sword'))); $this->assertEquals(array('username', 'password'), $table->getRow(0)); $this->assertEquals(array('antono', 'pa$sword'), $table->getRow(2)); }
/** * {@inheritdoc} */ protected function printOutlineExampleResultExceptions(TableNode $examples, array $events) { $colCount = count($examples->getRow(0)); foreach ($events as $event) { $error = $this->relativizePathsInString($event->get('exception')->getMessage()); $this->writeln('<tr class="failed exception">'); $this->writeln('<td colspan="' . $colCount . '">'); $this->writeln('<pre class="backtrace">' . htmlspecialchars($error) . '</pre>'); $this->writeln('</td>'); $this->writeln('</tr>'); } }
/** * @Then /^the following <row> should appear in the table "([^"]*)":$/ */ public function theFollowingRowShouldAppearInTheTable($table_id, TableNode $table) { $page = $this->getSession()->getPage(); $table_element = $page->find('css', "table#{$table_id}"); if (!$table_element) { throw new \Exception("Table '{$table_id}' was not found."); } $expectedRow = $table->getRow(0); // Search for the row in the table foreach ($table_element->findAll('css', 'tr') as $i => $row) { // Compare the given row to all table rows. If no exception is thrown it // means the row was found. try { $this->compareTableRow($row->findAll('css', 'td'), $expectedRow); } catch (\Exception $e) { // Try the next row. continue; } // Found the row. return; } throw new \Exception('Row not found.'); }
/** * @When /^An external event (.*) is fired with payload$/ */ public function anExternalEventIsFiredWithPayload($event, TableNode $payload) { static::$app['events']->fire($event, $payload->getRow(0)); }
/** * @Then /^I should see (?P<tableName>[\w\d\-]+) table header:$/ */ public function assertTableHeader($tableName, TableNode $expectedHeader) { $table = $this->findTable($tableName); Assert::assertEquals($expectedHeader->getRow(0), $table->getColumns(), "Table header looks different: " . $table->dumpHeader()); }
/** Set up the users required for a scenario. * * @Given /^the following users exist:$/ */ public function setUpUsers(TableNode $table) { $this->pdo->exec(<<<SQL DELETE FROM {$this->table_prefix}user SQL ); $this->pdo->exec(<<<SQL ALTER TABLE {$this->table_prefix}user AUTO_INCREMENT = 1 SQL ); if (0 !== count(array_diff(['name', 'password', 'email', 'member of'], $table->getRow(0)))) { throw new InvalidArgumentException("Table missing one of the required columns (name, password, email, member of)"); } $users = []; foreach ($table->getHash() as $user) { $r_group = $this->pdo->query(<<<SQL SELECT groupid FROM {$this->table_prefix}group WHERE name = '{$user['member of']}' SQL ); if (1 !== $r_group->rowCount()) { throw new DomainException("User '{$user['name']}' is assigned to the non existing group '{$user['member of']}'"); } $user['groupid'] = $r_group->fetchColumn(); $user['isadmin'] = isset($user['flags']) && in_array('isadmin', array_map('trim', explode(',', $user['flags']))) ? 1 : 0; $user['inactive'] = isset($user['flags']) && in_array('inactive', array_map('trim', explode(',', $user['flags']))) ? 1 : 0; $users[] = $user; } foreach ($users as $user) { $this->pdo->exec(<<<SQL INSERT INTO {$this->table_prefix}user ( username, userjoin, useremail, userpassword, groupids, usernodelete, useractivate, userisadmin ) VALUES ( '{$user['name']}', UNIX_TIMESTAMP(), '{$user['email']}', MD5('{$user['password']}'), ';{$user['groupid']};', {$user['isadmin']}, {$user['inactive']}, {$user['isadmin']} ) SQL ); } }