/** * @Given /^I should see a paginated table "(?P<element>[^"]*)" with the columns:$/ * * @param string $element * @param TableNode $table * * @throws \Exception */ public function iShouldSeeAPaginatedTableWithTheColumns($element, TableNode $table) { // Check that the (html) table exists $this->assertNumElements(1, $element); // Check that the (html) table has a pagination // Disabled for now, require JavaScript support to work //$this->assertNumElements(1, sprintf('%s_paginate', $element)); // Get the (html) table rows $elements = $this->getSession()->getPage()->findAll('css', sprintf('%s thead > tr > th', $element)); // Check the rows names foreach ($table->getRows() as $row) { $this->assertANodeElementContainsText($elements, $row[0]); } PHPUnit::assertEquals(count($table->getRows()), count($elements), 'Expected to find the same number of columns.'); }
/** * Put the specified questions on the specified pages of a given quiz. * * Give the question name in the first column, and that page number in the * second column. You may optionally give the desired maximum mark for each * question in a third column. * * @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 $DB; $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST); // The action depends on the field type. foreach ($data->getRows() as $questiondata) { if (count($questiondata) < 2 || count($questiondata) > 3) { 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 a the maxiumum mark. ' . count($questiondata) . ' values passed.', $this->getSession()); } list($questionname, $rawpage) = $questiondata; if (!isset($questiondata[2]) || $questiondata[2] === '') { $maxmark = null; } else { $maxmark = clean_param($questiondata[2], PARAM_FLOAT); if (!is_numeric($questiondata[2]) || $maxmark < 0) { throw new ExpectationException('When adding questions to a quiz, the max mark must be a positive number.', $this->getSession()); } } $page = clean_param($rawpage, PARAM_INT); if ($page <= 0 || (string) $page !== $rawpage) { throw new ExpectationException('When adding questions to a quiz, the page number must be a positive integer.', $this->getSession()); } $questionid = $DB->get_field('question', 'id', array('name' => $questionname), MUST_EXIST); quiz_add_quiz_question($questionid, $quiz, $page, $maxmark); } quiz_update_sumgrades($quiz); }
/** * Adds a question to the questionnaire with the provided data. * * @Given /^I add a "([^"]*)" question and I fill the form with:$/ * * @param string $questiontype The question type by text name to enter. * @param TableNode $fielddata */ public function i_add_a_question_and_i_fill_the_form_with($questiontype, TableNode $fielddata) { $validtypes = array('----- Page Break -----', 'Check Boxes', 'Date', 'Dropdown Box', 'Essay Box', 'Label', 'Numeric', 'Radio Buttons', 'Rate (scale 1..5)', 'Text Box', 'Yes/No'); if (!in_array($questiontype, $validtypes)) { throw new ExpectationException('Invalid question type specified.', $this->getSession()); } // We get option choices as CSV strings. If we have this, modify it for use in // multiline data. $rows = $fielddata->getRows(); $hashrows = $fielddata->getRowsHash(); $options = array(); if (isset($hashrows['Possible answers'])) { $options = explode(',', $hashrows['Possible answers']); $rownum = -1; // Find the row that contained multiline data and add line breaks. Rows are two item arrays where the // first is an identifier and the second is the value. foreach ($rows as $key => $row) { if ($row[0] == 'Possible answers') { $row[1] = str_replace(',', "\n", $row[1]); $rows[$key] = $row; break; } } $fielddata = new TableNode($rows); } $this->execute('behat_forms::i_set_the_field_to', array('id_type_id', $questiontype)); $this->execute('behat_forms::press_button', 'Add selected question type'); $this->execute('behat_forms::i_set_the_following_fields_to_these_values', $fielddata); $this->execute('behat_forms::press_button', 'Save changes'); }
/** * @Given /^taxonomy "([^""]*)" has following taxons:$/ */ public function taxonomyHasFollowingTaxons($taxonomyName, TableNode $taxonsTable) { $taxonomy = $this->findOneByName('taxonomy', $taxonomyName); $manager = $this->getEntityManager(); $taxons = array(); foreach ($taxonsTable->getRows() as $node) { $taxonList = explode('>', $node[0]); $parent = null; foreach ($taxonList as $taxonName) { $taxonName = trim($taxonName); if (!isset($taxons[$taxonName])) { /* @var $taxon TaxonInterface */ $taxon = $this->getRepository('taxon')->createNew(); $taxon->setName($taxonName); $taxons[$taxonName] = $taxon; } $taxon = $taxons[$taxonName]; if (null !== $parent) { $parent->addChild($taxon); } else { $taxonomy->addTaxon($taxon); } $parent = $taxon; } } $manager->persist($taxonomy); $manager->flush(); }
/** * @Given /^taxon "([^""]*)" has following children:$/ */ public function taxonHasFollowingChildren($taxonName, TableNode $childrenTable) { /* @var $taxon TaxonInterface */ $taxon = $this->findOneByName('taxon', $taxonName); $manager = $this->getEntityManager(); $children = []; foreach ($childrenTable->getRows() as $node) { $taxonList = explode('>', $node[0]); /* @var $parent TaxonInterface */ $parent = null; foreach ($taxonList as $item) { $item = trim($item); $childData = preg_split('[\\[|\\]]', $item, -1, PREG_SPLIT_NO_EMPTY); if (!isset($children[$childData[0]])) { /* @var $child TaxonInterface */ $child = $this->getFactory('taxon')->createNew(); $child->setName($childData[0]); $child->setCode($childData[1]); $children[$childData[0]] = $child; } $child = $children[$childData[0]]; if (null !== $parent) { $parent->addChild($child); } else { $taxon->addChild($child); } $parent = $child; } } $manager->persist($taxon); $manager->flush(); }
/** * @Given /^taxonomy "([^""]*)" has following taxons:$/ */ public function taxonomyHasFollowingTaxons($taxonomyName, TableNode $taxonsTable) { $taxonomy = $this->findOneByName('taxonomy', $taxonomyName); $manager = $this->getEntityManager(); $taxons = array(); foreach ($taxonsTable->getRows() as $node) { $taxonList = explode('>', $node[0]); $parent = null; foreach ($taxonList as $taxon) { $taxon = trim($taxon); $taxonData = preg_split("[\\[|\\]]", $taxon, -1, PREG_SPLIT_NO_EMPTY); if (!isset($taxons[$taxonData[0]])) { /* @var $taxon TaxonInterface */ $taxon = $this->getFactory('taxon')->createNew(); $taxon->setName($taxonData[0]); $taxon->setCode($taxonData[1]); $taxons[$taxonData[0]] = $taxon; } $taxon = $taxons[$taxonData[0]]; if (null !== $parent) { $parent->addChild($taxon); } else { $taxonomy->addTaxon($taxon); } $parent = $taxon; } } $manager->persist($taxonomy); $manager->flush(); }
/** * Fills the advanced permissions form with the provided data. Expects a table with capability name and permission (Inherit/Allow/Prevent/Prohibit) columns. * @Given /^I fill the capabilities form with the following permissions:$/ * @param TableNode $table * @return void */ public function i_fill_the_capabilities_form_with_the_following_permissions($table) { // Ensure we are using the advanced view. // Wrapped in a try/catch to capture the exception and continue execution, we don't know if advanced mode was already enabled. try { $advancedtoggle = $this->find_button(get_string('showadvanced', 'form')); if ($advancedtoggle) { $this->getSession()->getPage()->pressButton(get_string('showadvanced', 'form')); } } catch (Exception $e) { // We already are in advanced mode. } // Using getRows() as we are not sure if tests writers will add the header. foreach ($table->getRows() as $key => $row) { if (count($row) !== 2) { throw new ExpectationException('You should specify a table with capability/permission columns', $this->getSession()); } list($capability, $permission) = $row; // Skip the headers row if it was provided if (strtolower($capability) == 'capability' || strtolower($capability) == 'capabilities') { continue; } // Checking the permission value. $permissionconstant = 'CAP_' . strtoupper($permission); if (!defined($permissionconstant)) { throw new ExpectationException('The provided permission value "' . $permission . '" is not valid. Use Inherit, Allow, Prevent or Prohibited', $this->getSession()); } // Converting from permission to constant value. $permissionvalue = constant($permissionconstant); // Here we wait for the element to appear and exception if it does not exists. $radio = $this->find('xpath', '//input[@name="' . $capability . '" and @value="' . $permissionvalue . '"]'); $radio->click(); } }
/** * @Then there are keywords in :smth */ public function thereAreValues($file, \Behat\Gherkin\Node\TableNode $node) { $this->seeFileFound($file); foreach ($node->getRows() as $row) { $this->seeThisFileMatches('~' . implode('.*?', $row) . '~'); } }
/** * Manually allocates multiple reviewers in workshop. * * @When /^I allocate submissions in workshop "(?P<workshop_name_string>(?:[^"]|\\")*)" as:"$/ * @param string $workshopname * @param TableNode $table should have one column with title 'Reviewer' and another with title 'Participant' (or 'Reviewee') */ public function i_allocate_submissions_in_workshop_as($workshopname, TableNode $table) { $this->find_link($workshopname)->click(); $this->find_link(get_string('allocate', 'workshop'))->click(); $rows = $table->getRows(); $reviewer = $participant = null; for ($i = 0; $i < count($rows[0]); $i++) { if (strtolower($rows[0][$i]) === 'reviewer') { $reviewer = $i; } else { if (strtolower($rows[0][$i]) === 'reviewee' || strtolower($rows[0][$i]) === 'participant') { $participant = $i; } else { throw new ElementTextException('Unrecognised column "' . $rows[0][$i] . '"', $this->getSession()); } } } if ($reviewer === null) { throw new ElementTextException('Column "Reviewer" could not be located', $this->getSession()); } if ($participant === null) { throw new ElementTextException('Neither "Participant" nor "Reviewee" column could be located', $this->getSession()); } for ($i = 1; $i < count($rows); $i++) { $this->i_add_a_reviewer_for_workshop_participant($rows[$i][$reviewer], $rows[$i][$participant]); } }
/** * @When /I have parameters/ */ public function iHaveParams(TableNode $table) { foreach ($table->getRows() as $idx => $row) { if ($idx == 0) { continue; } Fixtures::add($row[0], $row[1]); } }
function it_should_throw_an_exception_if_no_existence(EntityResolver $resolver, TableNode $tableNode, $repository, $manager, ClassMetadata $metadata) { $resolver->resolve(Argument::cetera())->willReturn([$metadata]); $metadata->getName()->willReturn("EntityStub"); $tableNode->getRows()->willReturn(array(array('firstName', 'lastName', 'number', 'nullValue'), array('John', 'DOE', 0, ''))); $manager->getRepository(Argument::any())->willReturn($repository); $repository->findOneBy(['firstName' => 'John', 'lastName' => 'DOE', 'number' => 0, 'nullValue' => null])->willReturn(null); $this->shouldThrow(new \Exception("There is no object for the following criteria: {\"firstName\":\"John\",\"lastName\":\"DOE\",\"number\":0,\"nullValue\":null}"))->duringExistLikeFollowing(1, "Class", $tableNode); }
/** * @Then I should see following: */ public function iSeeTableEqual(TableNode $table) { foreach ($table->getRows() as $idx => $row) { if ($idx == 0) { continue; } $this->assertEquals($row[0], $row[1]); } }
/** * @param string $code * @param TableNode $expectedLines * * @Then /^exported xlsx file of "([^"]*)" should contains the following headers:$/ */ public function exportedXlsxFileOfShouldContainsTheFollowingHeaders($code, TableNode $expectedLines) { $path = $this->getMainContext()->getSubcontext('job')->getJobInstancePath($code); $reader = ReaderFactory::create(Type::XLSX); $reader->open($path); $sheet = current(iterator_to_array($reader->getSheetIterator())); $actualLines = iterator_to_array($sheet->getRowIterator()); $reader->close(); $this->compareXlsxFileHeadersOrder(array_values($expectedLines->getRows()), array_values($actualLines)); }
/** * @Given /^I have players:$/ */ public function iHavePlayers(TableNode $table) { $playerManager = $this->kernel->getContainer()->get('cytron_babitch.player.manager'); foreach ($table->getRows() as $row) { $player = new Player(); $player->setName($row[0]); $player->setEmail($row[1]); $playerManager->persist($player, true); } }
/** * 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); }
/** * @Then /^"([^"]*)" sharees returned (are|is empty)$/ * @param string $shareeType * @param string $isEmpty * @param \Behat\Gherkin\Node\TableNode|null $shareesList */ public function thenListOfSharees($shareeType, $isEmpty, $shareesList = null) { if ($isEmpty !== 'is empty') { $sharees = $shareesList->getRows(); $respondedArray = $this->getArrayOfShareesResponded($this->response, $shareeType); PHPUnit_Framework_Assert::assertEquals($sharees, $respondedArray); } else { $respondedArray = $this->getArrayOfShareesResponded($this->response, $shareeType); PHPUnit_Framework_Assert::assertEmpty($respondedArray); } }
/** * @Given I have manifests: */ public function iHaveManifests(TableNode $table) { $manifestsPath = __DIR__ . '/../fixtures/manifests/'; $em = $this->getEntityManager(); foreach ($table->getRows() as $row) { $content = file_get_contents($manifestsPath . $row[0]); $repository = $em->getRepository('AppBundle:Repository')->findOneByName(json_decode($content, true)['name']); $manifest = new Manifest($repository); $manifest->setContent($content); $em->persist($manifest); } $em->flush(); }
/** * @Given the page has the following product links */ public function thePageHasTheFollowingProductLinks(TableNode $table) { $productUrls = $this->getProductListScraper('products.html')->extractProductLinks(new \Sainsburys\Model\Url('http://sainsburys.com/products')); $productLinks = []; foreach ($productUrls as $productUrl) { $productLinks[] = $productUrl->getUrl(); } assertCount(3, $productLinks); foreach ($table->getRows() as $row) { $productLink = $row[0]; assertTrue(in_array($productLink, $productLinks)); } }
/** * POST to a specific route * * @When I send a POST request to route :route with values: */ public function iSendAPostRequestToRouteWithValues($route, TableNode $table) { $post = []; foreach ($table->getRows() as $hash) { $post[$hash[0]] = $hash[1]; } $url = $this->getService('router')->generate($route, $post); $this->client = $this->getService('session'); $crawler = $this->jsonRequest($url, $post); $response = $this->client->getResponse(); //#dump($post, $response);echo "\n",__METHOD__,':',__LINE__,"\n";#die; throw new PendingException(); }
/** * This function will convert Gherkin tables into structure array of data * * if Gherkin table look like * * | field | value1 | value2 | ... | valueN | * | field1 | single value 1 | | ... | | * | field2 | single value 2 | | ... | | * | field3 | multiple | value | ... | here | * * the returned array should look like: * $data = array( * "field1" => "single value 1", * "field2" => "single value 2", * "field3" => array( "multiple", "value", ... ,"here"), * ... * ); * * or if the Gherkin table values comes from a examples table: * | value | * | <field1> | * | <field2> | * | ... | * | <fieldN> | * * Examples: * | <field1> | <field2> | ... | <fieldN> | * | value1 | value2 | ... | valueN | * * the returned array should look like * $data = array( * "field1" => "value1", * "field2" => "value2", * ... * "fieldN" => "valueN", * ); * * @param \Behat\Gherkin\Node\TableNode $table The Gherkin table to extract the values * @param array $data If passed the values are concatenated/updated * * @return false|array * * @todo Define better the intended results in all (possible) variations */ static function convertTableToArrayOfData(TableNode $table, array $data = null) { if (empty($data)) { $data = array(); } // prepare given data $i = 0; $rows = $table->getRows(); $headers = array_shift($rows); // this is needed to take the first row ( readability only ) foreach ($rows as $row) { $count = count(array_filter($row)); // check if the field is supposed to be empty // or it simply has only 1 element if ($count == 1 && count($row) && !method_exists($table, "getCleanRows")) { $count = 2; } $key = $row[0]; switch ($count) { // case 1 is for the cases where there is an Examples table and it // gets the values from there, so the field name/id shold be on the // examples table (ex: "| <field_name> |") case 1: $value = $key; $aux = $table->getCleanRows(); $k = count($aux) === count(array_keys($table)) ? $i : $i + 1; $key = str_replace(array('<', '>'), array('', ''), $aux[$k][0]); break; // case 2 is the most simple case where "| field1 | as value 1 |" // case 2 is the most simple case where "| field1 | as value 1 |" case 2: if (count($headers) === 1) { $value = $row[0]; } else { $value = $row[1]; } break; // this is for the cases where there are several values for the same // field (ex: author) and the gherkin table should look like // this is for the cases where there are several values for the same // field (ex: author) and the gherkin table should look like default: $value = array_slice($row, 1); break; } $data[$key] = $value; $i++; } // if its empty return false otherwise return the array with data return empty($data) ? false : $data; }
/** * @Given /^I should see form with:$/ */ public function assertFormContain(TableNode $table) { foreach ($table->getRows() as $row) { list($field, $value) = $row; $node = $this->getSession()->getPage()->findField($field); if (empty($node)) { $node = $this->getSession()->getDriver()->find('//label[contains(normalize-space(string(.)), "' . $field . '")]'); if (!empty($node)) { $node = current($node); } } if (null === $node) { throw new \Behat\Mink\Exception\ElementNotFoundException($this->getSession(), 'form field', 'id|name|label|value', $field); } if ($node->getTagName() == 'input' && in_array($node->getAttribute('type'), array('checkbox', 'radio'))) { $actual = $node->isChecked() ? 'YES' : 'NO'; } elseif ($node->getTagName() == 'select') { $actual = $node->getValue(); if (!is_array($actual)) { $actual = array($actual); } $options = array(); $optionNodes = $this->getSession()->getDriver()->find($node->getXpath() . "/option"); foreach ($optionNodes as $optionNode) { $options[$optionNode->getValue()] = $optionNode->getText(); $options[$optionNode->getText()] = $optionNode->getText(); } foreach ($actual as $index => $optionValue) { if (isset($options[$optionValue])) { $actual[$index] = $options[$optionValue]; } } } elseif ($node->getTagName() == 'label') { foreach (explode(',', $value) as $option) { $option = $this->fixStepArgument(trim($option)); $this->assertSession()->checkboxChecked($option); } return true; } else { $actual = $node->getValue(); } if (is_array($actual)) { $actual = join(',', $actual); } $regex = '/^' . preg_quote($value, '$/') . '/ui'; if (!preg_match($regex, $actual)) { $message = sprintf('The field "%s" value is "%s", but "%s" expected.', $field, $actual, $value); throw new \Behat\Mink\Exception\ExpectationException($message, $this->getSession()); } } }
public function testTokens() { $table = new TableNode(); $table->addRow(array('username', 'password')); $table->addRow(array('<username>', '<password>')); $tableCompare = new TableNode(<<<TABLE | username | password | | everzet | qwerty | TABLE ); $exampleTable = $table->createExampleRowStepArgument(array('username' => 'everzet', 'password' => 'qwerty')); $this->assertNotSame($table, $exampleTable); $this->assertSame($tableCompare->getRows(), $exampleTable->getRows()); }
/** * @Given /^Update the following eclass_course_management values:$/ */ public function updatethefollowingeclasscoursemanagementvalues(TableNode $table) { global $DB; $data = $table->getRows(); $record = new stdClass(); $record->id = $data[1][0]; $record->courseid = $data[1][0]; $record->startdate = $data[1][1]; $record->enddate = $data[1][2]; $record->timemodified = $data[1][2]; $record->lastopened = $data[1][2]; $record->lastclosed = $data[1][2]; $DB->update_record('eclass_course_management', $record); }
/** * @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(); } }
/** * Transformations for TableNode arguments. * * Transformations applicable to TableNode arguments should also * be applied, adding them in a different method for Behat API restrictions. * * @Transform /^table:(.*)/ * @param TableNode $tablenode * @return TableNode The transformed table */ public function tablenode_transformations(TableNode $tablenode) { // Walk through all values including the optional headers. $rows = $tablenode->getRows(); foreach ($rows as $rowkey => $row) { foreach ($row as $colkey => $value) { // Transforms vars into nasty strings. if (preg_match('/\\$NASTYSTRING(\\d)/', $rows[$rowkey][$colkey])) { $rows[$rowkey][$colkey] = $this->replace_nasty_strings($rows[$rowkey][$colkey]); } } } // Return the transformed TableNode. $tablenode->setRows($rows); return $tablenode; }
/** * @Transform /^table:/ */ public function mockEmailInTable(TableNode $table) { if ($this->connection) { $rows = $table->getRows(); foreach ($rows as $index => $row) { foreach ($row as $key => $value) { if (preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i', $value)) { $row[$key] = $this->mockEmail($value); } $rows[$index] = $row; } } $table->setRows($rows); } return $table; }
public function testTableFromArrayCreation() { $table1 = new TableNode(); $table1->addRow(array('username', 'password')); $table1->addRow(array('everzet', 'qwerty')); $table1->addRow(array('antono', 'pa$sword')); $table2 = new TableNode(<<<TABLE | username | password | | everzet | qwerty | | antono | pa\$sword| TABLE ); $this->assertEquals($table2->getRows(), $table1->getRows()); $this->assertEquals(array(array('username' => 'everzet', 'password' => 'qwerty'), array('username' => 'antono', 'password' => 'pa$sword')), $table1->getHash()); $this->assertEquals(array('username' => 'password', 'everzet' => 'qwerty', 'antono' => 'pa$sword'), $table2->getRowsHash()); }
/** * @Given /^I fill form with:$/ */ public function fillForm(TableNode $table) { $page = $this->getSession()->getPage(); foreach ($table->getRows() as $row) { list($fieldSelector, $value) = $row; $field = $page->findField($fieldSelector); if (empty($field)) { $field = $this->getSession()->getDriver()->find('//label[contains(normalize-space(string(.)), "' . $fieldSelector . '")]'); if (!empty($field)) { $field = current($field); } } if (empty($field)) { throw new \Exception('Field not found ' . $fieldSelector . PHP_EOL); } $tag = strtolower($field->getTagName()); if ($tag == 'textarea') { $page->fillField($fieldSelector, $value); } elseif ($tag == 'select') { if ($field->hasAttribute('multiple')) { foreach (explode(',', $value) as $index => $option) { $page->selectFieldOption($fieldSelector, trim($option), true); } } else { $page->selectFieldOption($fieldSelector, $value); } } elseif ($tag == 'input') { $type = strtolower($field->getAttribute('type')); if ($type == 'checkbox' || $type == 'radio') { if (strtolower($value) == 'yes') { $page->checkField($fieldSelector); } else { $page->uncheckField($fieldSelector); } // } elseif ($type == 'radio') { // // TODO: handle radio } else { $page->fillField($fieldSelector, $value); } } elseif ($tag == 'label') { foreach (explode(',', $value) as $option) { $option = $this->fixStepArgument(trim($option)); $field->getParent()->checkField($option); } } } }
/** * Adds a question to the existing feedback with filling the form. * * The form for creating a question should be on one page. * * @When /^I add a "(?P<question_type_string>(?:[^"]|\\")*)" question to the feedback with:$/ * @param string $questiontype * @param TableNode $questiondata with data for filling the add question form */ public function i_add_question_to_the_feedback_with($questiontype, TableNode $questiondata) { $questiontype = $this->escape($questiontype); $additem = $this->escape(get_string('add_item', 'feedback')); $this->execute('behat_forms::i_select_from_the_singleselect', array($questiontype, $additem)); $rows = $questiondata->getRows(); $modifiedrows = array(); foreach ($rows as $row) { foreach ($row as $key => $value) { $row[$key] = preg_replace('|\\\\n|', "\n", $value); } $modifiedrows[] = $row; } $newdata = new TableNode($modifiedrows); $this->execute("behat_forms::i_set_the_following_fields_to_these_values", $newdata); $saveitem = $this->escape(get_string('save_item', 'feedback')); $this->execute("behat_forms::press_button", $saveitem); }
/** * Creates a new course with the provided table data matching course settings names with the desired values. * * @Given /^I create a course with:$/ * @param TableNode $table The course data * @return Given[] */ public function i_create_a_course_with(TableNode $table) { $steps = array(new Given('I go to the courses management page'), new Given('I should see the "' . get_string('categories') . '" management page'), new Given('I click on category "' . get_string('miscellaneous') . '" in the management interface'), new Given('I should see the "' . get_string('categoriesandcoures') . '" management page'), new Given('I click on "' . get_string('createnewcourse') . '" "link" in the "#course-listing" "css_element"')); // If the course format is one of the fields we change how we // fill the form as we need to wait for the form to be set. $rowshash = $table->getRowsHash(); $formatfieldrefs = array(get_string('format'), 'format', 'id_format'); foreach ($formatfieldrefs as $fieldref) { if (!empty($rowshash[$fieldref])) { $formatfield = $fieldref; } } // Setting the format separately. if (!empty($formatfield)) { // Removing the format field from the TableNode. $rows = $table->getRows(); $formatvalue = $rowshash[$formatfield]; foreach ($rows as $key => $row) { if ($row[0] == $formatfield) { unset($rows[$key]); } } $table->setRows($rows); // Adding a forced wait until editors are loaded as otherwise selenium sometimes tries clicks on the // format field when the editor is being rendered and the click misses the field coordinates. $steps[] = new Given('I expand all fieldsets'); $steps[] = new Given('I set the field "' . $formatfield . '" to "' . $formatvalue . '"'); $steps[] = new Given('I set the following fields to these values:', $table); } else { $steps[] = new Given('I set the following fields to these values:', $table); } $steps[] = new Given('I press "' . get_string('savechanges') . '"'); return $steps; }