/** * 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'); }
/** * Creates entries provided in the form: * | cn | attribute1 | attribute2 | attributeN | * | primary | value1 | value2 | valueN | * | ... | ... | ... | ... | * * @Given /^Ldap entries:$/ */ public function ldapEntries(TableNode $entries) { foreach ($entries->getHash() as $entry) { $ldapEntry = new Entry('cn' . '=' . $entry['cn'] . ',' . $this->rootDn, $entry); $this->client->getEntryManager()->add($ldapEntry); } }
/** * @Given Posts exist: */ public function postsExist(TableNode $table) { $postsData = $table->getHash(); foreach ($postsData as $postData) { $this->processPost($postData); } }
/** * @When /^las siguientes taquillas:$/ */ public function lasSiguientesTaquillas(TableNode $table) { foreach ($table->getHash() as $item) { /** @var Locker $locker */ $locker = $this->getRepository('locker')->createNew(); $locker->setCode($item['código']); $locker->setStatus($this->status[$item['estado']]); if ($item['alquilada_a']) { $username = $item['alquilada_a']; $user = $this->getRepository('user')->findOneBy(['username' => $username]); if (!$user) { throw new \Exception('User not found: ' . $username); } $start = new \DateTime($item['desde'] . ' days'); $end = new \DateTime($item['hasta'] . ' days midnight'); $renewable = isset($item['renovable']) ? $item['renovable'] : 'sí'; /** @var Rental $rental */ $rental = $this->getRepository('rental')->createNew(); $rental->setStartAt($start); $rental->setEndAt($end); $rental->setUser($user); $rental->setLocker($locker); $rental->setIsRenewable($renewable === 'sí'); $locker->setOwner($user); $locker->setStatus(Locker::RENTED); $this->getEntityManager()->persist($rental); } $this->getEntityManager()->persist($locker); } $this->getEntityManager()->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(); } }
/** * 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); }
/** * Add these posts to this wordpress installation * Example: Given there are posts * | post_title | post_content | post_status | post_author | post_date | * | Just my article | The content of my article | publish | 1 | 2016-10-11 08:30:00 | * * * @Given /^there are posts$/ */ public function thereArePosts(TableNode $table) { foreach ($table->getHash() as $postData) { $postData = $this->parseArgs($postData); $this->insert($postData); } }
/** * Checks that the given select field doesn't have the listed options. * * @Then I should not have the following options for :select: */ public function assertNoSelectOptions($select, TableNode $options) { // Retrieve the specified field. if (!($field = $this->getSession()->getPage()->findField($select))) { throw new ExpectationException("Field '{$select}' not found.", $this->getSession()); } // Check that the specified field is a <select> field. $this->assertElementType($field, 'select'); // Retrieve the options table from the test scenario and flatten it. $expected_options = $options->getColumnsHash(); array_walk($expected_options, function (&$value) { $value = reset($value); }); // Retrieve the actual options that are shown in the page. $actual_options = $field->findAll('css', 'option'); // Convert into a flat list of option text strings. array_walk($actual_options, function (&$value) { $value = $value->getText(); }); // Check that none of the expected options are present. foreach ($expected_options as $expected_option) { if (in_array($expected_option, $actual_options)) { throw new ExpectationException("Option '{$expected_option}' is unexpectedly found in select list '{$select}'.", $this->getSession()); } } }
/** * @Given /^groups memberships:$/ */ public function groupsMemberships(TableNode $table) { $memberships = $table->getHash(); foreach ($memberships as $membership) { // Find group node. $group_node = $membership['group']; foreach ($this->nodes as $node) { if ($node->type == 'group' && $node->title == $group_node) { $group_node = $node; } } // Subscribe nodes and users to group. if (isset($membership['members'])) { $members = explode(",", $membership['members']); foreach ($this->users as $user) { if (in_array($user->name, $members)) { og_group('node', $group_node->nid, array('entity' => $user, 'entity_type' => 'user', "membership type" => OG_MEMBERSHIP_TYPE_DEFAULT)); // Patch till i figure out why rules are not firing. if ($user->name == 'editor') { og_role_grant('node', $group_node->nid, $user->uid, 4); } } } } if (isset($membership['nodes'])) { $content = explode(",", $membership['nodes']); foreach ($this->nodes as $node) { if ($node->type != 'group' && in_array($node->title, $content)) { og_group('node', $group_node->nid, array('entity' => $node, 'entity_type' => 'node', 'state' => OG_STATE_ACTIVE)); } } } } }
/** * Creates multiple group memberships. * * Provide group membership data in the following format: * * | user | group | role on group | membership status | * | Foo | The Group | administrator member | Active | * * @Given group memberships: */ public function addGroupMemberships(TableNode $groupMembershipsTable) { foreach ($groupMembershipsTable->getHash() as $groupMembershipHash) { if (isset($groupMembershipHash['group']) && isset($groupMembershipHash['user'])) { $group = $this->getGroupByName($groupMembershipHash['group']); $user = user_load_by_name($groupMembershipHash['user']); // Add user to group with the proper group permissions and status if ($group && $user) { // Add the user to the group og_group("node", $group->nid->value(), array("entity type" => "user", "entity" => $user, "membership type" => OG_MEMBERSHIP_TYPE_DEFAULT, "state" => $this->getMembershipStatusByName($groupMembershipHash['membership status']))); // Grant user roles $group_role = $this->getGroupRoleByName($groupMembershipHash['role on group']); og_role_grant("node", $group->nid->value(), $user->uid, $group_role); } else { if (!$group) { throw new \Exception(sprintf("No group was found with name %s.", $groupMembershipHash['group'])); } if (!$user) { throw new \Exception(sprintf("No user was found with name %s.", $groupMembershipHash['user'])); } } } else { throw new \Exception(sprintf("The group and user information is required.")); } } }
/** * @Given the following html response contents: * * @param TableNode $table */ public function theFollowingHtmlResponses(TableNode $table) { foreach ($table->getHash() as $item) { $this->responseHTMLs[] = file_get_contents(__DIR__ . '/../../Resources/Fixtures/' . $item['content']); } $this->buildMockHttpClientProvider(); }
/** * Sets the specified site settings. * A table with | Setting label | value | is expected. * * @Given /^the following site settings are set:$/ * @param TableNode $table * @throws SystemException */ public function site_settings_set(TableNode $table) { $settings = array(); foreach ($table->getHash() as $sitesetting) { $settings[$sitesetting['field']] = $sitesetting['value']; } // Validate the settings $allowsettings = array('sitename', 'lang', 'country', 'theme', 'dropdownmenu', 'homepageinfo', 'userscanchooseviewthemes', 'remoteavatars', 'userscanhiderealnames', 'searchusernames', 'searchuserspublic', 'anonymouscomments', 'loggedinprofileviewaccess', 'staffreports', 'staffstats', 'userscandisabledevicedetection', 'masqueradingreasonrequired', 'masqueradingnotified', 'showprogressbar', 'exporttoqueue', 'defaultmultipleblogs', 'searchplugin', 'creategroups', 'createpublicgroups', 'allowgroupcategories', 'institutionexpirynotification', 'institutionautosuspend', 'requireregistrationconfirm', 'allowpublicviews', 'allowpublicprofiles', 'allowanonymouspages', 'generatesitemap', 'showselfsearchsideblock', 'showtagssideblock', 'tagssideblockmaxtags', 'viewmicroheaders', 'showonlineuserssideblock', 'onlineuserssideblockmaxusers', 'licensemetadata', 'licenseallowcustom', 'allowmobileuploads', 'wysiwyg', 'sitefilesaccess', 'watchlistnotification_delay', 'skins'); // if public views are disabled, sitemap generation must also be disabled. if (empty($settings['allowpublicviews'])) { $settings['generatesitemap'] = false; } else { // Ensure allowpublicprofiles is set as well $settings['allowpublicprofiles'] = 1; } // Update site settings $oldsearchplugin = get_config('searchplugin'); $oldlanguage = get_config('lang'); $oldtheme = get_config('theme'); foreach ($allowsettings as $setting) { if (isset($settings[$setting]) && !set_config($setting, $settings[$setting])) { throw new SystemException("Can not set the option \"{$setting}\" to \"{$settings[$setting]}\""); } } if (isset($settings['lang']) && $oldlanguage != $settings['lang']) { safe_require('artefact', 'file'); ArtefactTypeFolder::change_public_folder_name($oldlanguage, $settings['lang']); } }
/** * @Given the following users exist: */ public function theFollowingUsersExist(TableNode $table) { /** @var \Ma27\ApiKeyAuthenticationBundle\Model\Password\PasswordHasherInterface $hasher */ $hasher = $this->getContainer()->get('ma27_api_key_authentication.password.strategy'); $em = $this->getEntityManager(); $userRole = $em->getRepository('Account:Role')->findOneBy(['role' => 'ROLE_USER']); $adminRole = $em->getRepository('Account:Role')->findOneBy(['role' => 'ROLE_ADMIN']); foreach ($table->getHash() as $row) { $user = User::create($row['username'], $hasher->generateHash($row['password']), $row['email']); if (isset($row['user_id'])) { // there are cases where the user id should be known $r = new \ReflectionProperty(User::class, 'id'); $r->setAccessible(true); $r->setValue($user, $row['user_id']); } if (isset($row['activation_date'])) { $user->getPendingActivation()->setActivationDate(new \DateTime($row['activation_date'])); } if (!(isset($row['is_non_activated']) && $row['is_non_activated'] === 'true')) { $user->setState(User::STATE_APPROVED); // roles only allowed for approved users $user->addRole($userRole); if (isset($row['is_admin']) && $row['is_admin'] === 'true') { $user->addRole($adminRole); } } else { if (isset($row['activation_key'])) { $user->setActivationKey($row['activation_key']); } } $em->persist($user); } $em->flush(); }
/** * Create a new WordPress website from scratch * * @Given /^\w+ have a vanilla wordpress installation$/ */ public function installWordPress(TableNode $table = null) { global $wp_rewrite; $name = "admin"; $email = "*****@*****.**"; $password = "******"; $username = "******"; if ($table) { $hash = $table->getHash(); $row = $hash[0]; $name = $row["name"]; $username = $row["username"]; $email = $row["email"]; $password = $row["password"]; } $mysqli = new \Mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $value = $mysqli->multi_query(implode("\n", array("DROP DATABASE IF EXISTS " . DB_NAME . ";", "CREATE DATABASE " . DB_NAME . ";"))); \PHPUnit_Framework_Assert::assertTrue($value); require_once ABSPATH . 'wp-admin/includes/upgrade.php'; wp_install($name, $username, $email, true, '', $password); //This is a bit of a hack, we don't care about the notification e-mails here so clear the inbox //we run the risk of deleting stuff we want! $this->inboxFactory->getInbox($email)->clearInbox(); $wp_rewrite->init(); $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%day%/%postname%/'); }
/** * @Given /^I should see display with following fields$/ */ public function iShouldSeeDisplayWithFollowingFields(TableNode $table) { $display = $this->getPage('News display')->getElement('Display'); foreach ($table->getHash() as $row) { expect($display->hasFieldWithName($row['Field name']))->toBe(true); } }
/** * @Given the following :entityName entities exist: */ public function theFollowingEntitiesExist($entityName, TableNode $table) { /** @var EntityManager $doctrine */ $doctrine = $this->get('doctrine')->getManager(); $meta = $doctrine->getClassMetadata($entityName); $rows = []; $hash = $table->getHash(); foreach ($hash as $row) { $id = $row['id']; unset($row['id']); foreach ($row as $property => &$value) { $propertyName = Inflector::camelize($property); $fieldType = $meta->getTypeOfField($propertyName); switch ($fieldType) { case 'array': case 'json_array': $value = json_decode($value, true); break; case 'datetime': $value = new \DateTime($value); break; } } $rows[$id] = $row; } $this->persistEntities($entityName, $rows); }
/** * @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 /^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); }
/** * @Given /^the external "([^"]*)" user:$/ */ public function createExternalUser($service, TableNode $table) { $external_user = new ExternalUser(); $external_user->setService(strtolower($service)); $em = $this->getEntityManager(); foreach ($table->getRowsHash() as $field => $value) { switch ($field) { case 'name': $external_user->setName($value); break; case 'id': $external_user->setRemoteId($value); break; case 'email': $external_user->setEmail($value); break; case 'username': $external_user->setUsername($value); break; case 'picture': $external_user->setProfilePictureUrl($value); break; case 'user': $user = $em->getRepository('ActsCamdramSecurityBundle:User')->findOneByEmail($value); $external_user->setUser($user); break; } } $em->persist($external_user); $em->flush(); }
/** * @Given /^I should see the row in the table "(?P<element>[^"]*)":$/ * * @param string $element * @param TableNode $table * * @throws \Exception */ public function iShouldSeeTheRow($element, TableNode $table) { // Check that the (html) table exists $this->assertNumElements(1, $element); // Get the (html) table rows $headerNodeElements = $this->getSession()->getPage()->findAll('css', sprintf('%s thead > tr > th', $element)); $rowNodeElements = $this->getSession()->getPage()->findAll('css', sprintf('%s > tbody > tr', $element)); foreach ($table->getColumnsHash() as $rowIndex => $row) { // At this point, we want to check that $rowNodeElements contains a rows matching $row $rowMatches = false; foreach ($rowNodeElements as $rowNodeElement) { /* @var NodeElement $rowNodeElement */ try { // Get the row cells $cellNodeElements = $rowNodeElement->findAll('css', 'td'); // Check that for each cells of $row, we got a matching value foreach ($row as $columnText => $cellValue) { $this->assertNodeElementContainsText($cellNodeElements[$this->findTableIndex($headerNodeElements, $columnText)], $cellValue); } // At this point the row match otherwise an exception would have been thrown $rowMatches = true; continue; } catch (\Exception $exception) { // Exception thrown because the row was not matching // Do nothing and pass to the next row } } PHPUnit::assertTrue($rowMatches, sprintf('Expected to find at least one row matching row #%d', $rowIndex)); } }
/** * @Given /^There are published representative news$/ */ public function thereArePublishedLeaderNews(TableNode $table) { /* @var $em EntityManager */ $em = $this->getEm(); /* @var $activityService \Civix\CoreBundle\Service\ActivityUpdate */ $activityService = $this->getMainContext()->getContainer()->get('civix_core.activity_update'); $hash = $table->getHash(); $diffSec = 0; foreach ($hash as $row) { $diffSec++; $news = new RepresentativeNews(); $news->setUser($em->getRepository(Representative::class)->findOneByUsername($row['username'])); $news->setSubject($row['subject']); $news->setPublishedAt(new \DateTime()); $em->persist($news); $em->flush($news); $activity = $activityService->publishLeaderNewsToActivity($news); $activity->getSentAt()->sub(new \DateInterval('PT' . (count($hash) - $diffSec) . 'S')); $activity->setSentAt(clone $activity->getSentAt()); if (!empty($row['expired_interval_direction'])) { $expired = new \DateTime(); $expired->{$row}['expired_interval_direction'](new \DateInterval($row['expired_interval_value'])); $activity->setExpireAt($expired); $em->flush($activity); } } $result = $em->getRepository(LeaderNewsActivity::class)->findAll(); Assert::assertTrue(count($result) >= count($hash)); }
/** * 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]); } }
/** * @Given /^there are following tax categories:$/ * @Given /^the following tax categories exist:$/ */ public function thereAreTaxCategories(TableNode $table) { foreach ($table->getHash() as $data) { $this->thereIsTaxCategory($data['name'], false); } $this->getEntityManager()->flush(); }
/** * @param string $code * @param TableNode $table * * @Given /^the following job "([^"]*)" configuration:$/ */ public function theFollowingJobConfiguration($code, TableNode $table) { $jobInstance = $this->getFixturesContext()->getJobInstance($code); $configuration = $jobInstance->getRawParameters(); foreach ($table->getRowsHash() as $property => $value) { $value = $this->replacePlaceholders($value); if (in_array($value, ['yes', 'no'])) { $value = 'yes' === $value; } if ('filters' === $property) { $value = json_decode($value, true); } $configuration[$property] = $value; } /** @var JobRegistry $jobRegistry */ $jobRegistry = $this->getMainContext()->getContainer()->get('akeneo_batch.job.job_registry'); $job = $jobRegistry->get($jobInstance->getJobName()); /** @var JobParametersFactory $jobParamsFactory */ $jobParamsFactory = $this->getMainContext()->getContainer()->get('akeneo_batch.job_parameters_factory'); $jobParams = $jobParamsFactory->create($job, $configuration); /** @var JobParametersValidator $jobParamsValidator */ $jobParamsValidator = $this->getMainContext()->getContainer()->get('akeneo_batch.job.job_parameters_validator'); $violations = $jobParamsValidator->validate($job, $jobParams, ['Default']); if ($violations->count() > 0) { $messages = []; /** @var ConstraintViolationInterface $violation */ foreach ($violations as $violation) { $messages[] = $violation->getMessage(); } throw new \InvalidArgumentException(sprintf('The parameters "%s" are not valid for the job "%s" due to violations "%s"', print_r($jobParams->all(), true), $job->getName(), implode(', ', $messages))); } $jobInstance->setRawParameters($jobParams->all()); $saver = $this->getMainContext()->getContainer()->get('akeneo_batch.saver.job_instance'); $saver->save($jobInstance); }
/** * 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 . '"')); }
/** * @Given /^the following promotions exist:$/ * @Given /^there are following promotions configured:$/ */ public function theFollowingPromotionsExist(TableNode $table) { $manager = $this->getEntityManager(); $factory = $this->getFactory('promotion'); foreach ($table->getHash() as $data) { $promotion = $factory->createNew(); $promotion->setName($data['name']); $promotion->setDescription($data['description']); $promotion->setCode($data['code']); if (array_key_exists('usage limit', $data) && '' !== $data['usage limit']) { $promotion->setUsageLimit((int) $data['usage limit']); } if (array_key_exists('used', $data) && '' !== $data['used']) { $promotion->setUsed((int) $data['used']); } if (array_key_exists('starts', $data)) { $promotion->setStartsAt(new \DateTime($data['starts'])); } if (array_key_exists('ends', $data)) { $promotion->setEndsAt(new \DateTime($data['ends'])); } $manager->persist($promotion); } $manager->flush(); }
/** * @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) . '~'); } }
/** * @Then /^I should get the following products after apply the following updater to it:$/ * * @param TableNode $updates * * @throws \Exception */ public function iShouldGetTheFollowingProductsAfterApplyTheFollowingUpdaterToIt(TableNode $updates) { $application = $this->getApplicationsForUpdaterProduct(); $updateCommand = $application->find('pim:product:update'); $updateCommand->setContainer($this->getMainContext()->getContainer()); $updateCommandTester = new CommandTester($updateCommand); $getCommand = $application->find('pim:product:get'); $getCommand->setContainer($this->getMainContext()->getContainer()); $getCommandTester = new CommandTester($getCommand); foreach ($updates->getHash() as $update) { $username = isset($update['username']) ? $update['username'] : null; $updateCommandTester->execute(['command' => $updateCommand->getName(), 'identifier' => $update['product'], 'json_updates' => $update['actions'], 'username' => $username]); $expected = json_decode($update['result'], true); if (isset($expected['product'])) { $getCommandTester->execute(['command' => $getCommand->getName(), 'identifier' => $expected['product']]); unset($expected['product']); } else { $getCommandTester->execute(['command' => $getCommand->getName(), 'identifier' => $update['product']]); } $actual = json_decode($getCommandTester->getDisplay(), true); if (null === $actual) { throw new \Exception(sprintf('An error occured during the execution of the update command : %s', $getCommandTester->getDisplay())); } if (null === $expected) { throw new \Exception(sprintf('Looks like the expected result is not valid json : %s', $update['result'])); } $diff = $this->arrayIntersect($actual, $expected); assertEquals($expected, $diff); } }
/** * @Given /^Users exist:$/ */ public function usersExist(TableNode $table) { $usersData = $table->getHash(); add_filter('send_password_change_email', '__return_false'); add_filter('send_email_change_email', '__return_false'); foreach ($usersData as $userData) { if (empty($userData['login'])) { throw new \InvalidArgumentException('You must provide a user login!'); } $user = get_user_by('login', $userData['login']); $data = $this->getUserDataFromTable($userData); if ($user) { $data['ID'] = $user->ID; } $result = $user ? wp_update_user($data) : wp_insert_user($data); if (is_wp_error($result)) { throw new \UnexpectedValueException('User could not be created: ' . $result->get_error_message()); } foreach ($this->getUserMetaDataFromTable($userData) as $key => $value) { update_user_meta($user->ID, $key, $value); } } remove_filter('send_password_change_email', '__return_false'); remove_filter('send_email_change_email', '__return_false'); }
/** * 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; }