我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.webdriver.support.ui.Select()。
def set_select_by_text(self, select, text): ''' Set the selected value of a select element by the visible text. Parameters ---------- select: str or selenium.webdriver.remote.webelement.WebElement Any valid CSS selector or a selenium element text: str The visible text in the select element option. (Not the value) ''' if isinstance(select, str): elem = self.get_element(select) else: elem = select sel = Select(elem) sel.select_by_visible_text(text)
def set_select_by_value(self, select, value): ''' Set the selected value of a select element by the value. Parameters ---------- select: str or selenium.webdriver.remote.webelement.WebElement Any valid CSS selector or a selenium element value: str The value on the select element option. (Not the visible text) ''' if isinstance(select, str): elem = self.get_element(select) else: elem = select sel = Select(elem) sel.select_by_value(value)
def test_extra_dropdown_persists(self): self.element.extra_dropdown.click() self.element.wait_for_display() self.assertEqual( self.element.dropdown_select.get_attribute('value'), '1', ) select = Select(self.element.dropdown_select) select.select_by_value('2') self.element.next.click() self.element.back.click() self.assertEqual( self.element.dropdown_select.get_attribute('value'), '2', )
def test_create_new_project(self): """ Test creating a project """ project_name = "masterproject" url = reverse('newproject') self.get(url) self.enter_text('#new-project-name', project_name) select = Select(self.find('#projectversion')) select.select_by_value(str(self.release.pk)) self.click("#create-project-button") # We should get redirected to the new project's page with the # notification at the top element = self.wait_until_visible('#project-created-notification') self.assertTrue(project_name in element.text, "New project name not in new project notification") self.assertTrue(Project.objects.filter(name=project_name).count(), "New project not found in database")
def select_option(select_el, by, val): """Select an option from a select dropdown Arguments: select_el -- the Selenium WebDriver Element select dropdown by -- the type of the value used (index | text | value) val -- the value of the option to select """ select = Select(select_el) if by == 'index': return select.select_by_index(val) elif by == 'text': select.select_by_visible_text(val) elif by == 'value': select.select_by_value(val) else: raise Exception('Invalid SELECT BY type') return True
def fill_form(self, fields=(), submit=True): """ Fill in a form and press enter on last :param fields: list of tupules: (input_id, value), (input_id, value) :return: """ elem = None for input_id, value in fields: if '//' in input_id: find = input_id else: find = "//input[@id='{id}']".format(id=input_id) elem = self.find_element(find) if elem.tag_name == 'select': select = Select(elem) select.select_by_visible_text(value) else: elem.send_keys(value) if elem and submit: elem.send_keys(Keys.ENTER)
def test_1_modal_from_url(self, base_url, selenium): self.baseurl = base_url self.get(selenium, base_url + '/scheduled/2') modal, title, body = self.get_modal_parts(selenium) self.assert_modal_displayed(modal, title, body) assert title.text == 'Edit Scheduled Transaction 2' assert body.find_element_by_id( 'sched_frm_id').get_attribute('value') == '2' assert body.find_element_by_id( 'sched_frm_description').get_attribute('value') == 'ST2' assert body.find_element_by_id( 'sched_frm_type_monthly').is_selected() assert body.find_element_by_id( 'sched_frm_type_date').is_selected() is False assert body.find_element_by_id( 'sched_frm_type_per_period').is_selected() is False assert body.find_element_by_id( 'sched_frm_day_of_month').get_attribute('value') == '4' assert body.find_element_by_id( 'sched_frm_amount').get_attribute('value') == '222.22' acct_sel = Select(body.find_element_by_id('sched_frm_account')) assert acct_sel.first_selected_option.get_attribute('value') == '1' budget_sel = Select(body.find_element_by_id('sched_frm_budget')) assert budget_sel.first_selected_option.get_attribute('value') == '2' assert selenium.find_element_by_id('sched_frm_active').is_selected()
def test_acct_filter_opts(self, selenium): self.get(selenium, self.baseurl + '/transactions') acct_filter = Select(selenium.find_element_by_id('account_filter')) # find the options opts = [] for o in acct_filter.options: opts.append([o.get_attribute('value'), o.text]) assert opts == [ ['None', ''], ['1', 'BankOne'], ['2', 'BankTwoStale'], ['3', 'CreditOne'], ['4', 'CreditTwo'], ['6', 'DisabledBank'], ['5', 'InvestmentOne'] ]
def test_budg_filter_opts(self, selenium): self.get(selenium, self.baseurl + '/transactions') budg_filter = Select(selenium.find_element_by_id('budget_filter')) # find the options opts = [] for o in budg_filter.options: opts.append([o.get_attribute('value'), o.text]) assert opts == [ ['None', ''], ['7', 'Income (income)'], ['1', 'Periodic1'], ['2', 'Periodic2'], ['3', 'Periodic3 Inactive'], ['4', 'Standing1'], ['5', 'Standing2'], ['6', 'Standing3 Inactive'] ]
def test_filter_opts(self, selenium): self.get(selenium, self.baseurl + '/ofx') acct_filter = Select(selenium.find_element_by_id('account_filter')) # find the options opts = [] for o in acct_filter.options: opts.append([o.get_attribute('value'), o.text]) assert opts == [ ['None', ''], ['1', 'BankOne'], ['2', 'BankTwoStale'], ['3', 'CreditOne'], ['4', 'CreditTwo'], ['6', 'DisabledBank'], ['5', 'InvestmentOne'] ]
def __init__(self): 'stst\resources\linux\chromedriver' # cur_dir = os.path.dirname(__file__) # 'stst/features' # path = os.path.join(cur_dir, 'resources') # print(cur_dir) driver = webdriver.Chrome() driver.get("http://asiya.cs.upc.edu/demo/asiya_online.php#") time.sleep(3) driver._switch_to.frame(driver.find_element_by_id("demo-content")) elem = Select(driver.find_element_by_id("input")) elem.select_by_value("raw") elem = driver.find_element_by_id("no_tok") elem.click() elem = Select(driver.find_element_by_id("srclang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("trglang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("srccase")) elem.select_by_value("ci") elem = Select(driver.find_element_by_id("trgcase")) elem.select_by_value("ci") self.driver = driver
def reload(self): driver = self.driver driver.get("http://asiya.cs.upc.edu/demo/asiya_online.php#") time.sleep(3) driver._switch_to.frame(driver.find_element_by_id("demo-content")) elem = Select(driver.find_element_by_id("input")) elem.select_by_value("raw") elem = driver.find_element_by_id("no_tok") elem.click() elem = Select(driver.find_element_by_id("srclang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("trglang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("srccase")) elem.select_by_value("ci") elem = Select(driver.find_element_by_id("trgcase")) elem.select_by_value("ci") self.driver = driver
def unselect_from_list_by_index(self, locator, *indexes): """Unselects `*indexes` from list identified by `locator` Select list keywords work on both lists and combo boxes. Key attributes for select lists are `id` and `name`. See `introduction` for details about locating elements. """ if not indexes: raise ValueError("No index given.") items_str = "index(es) '%s'" % ", ".join(indexes) self._info("Unselecting %s from list '%s'." % (items_str, locator)) select = self._get_select_list(locator) if not select.is_multiple: raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.") for index in indexes: select.deselect_by_index(int(index))
def unselect_from_list_by_value(self, locator, *values): """Unselects `*values` from list identified by `locator` Select list keywords work on both lists and combo boxes. Key attributes for select lists are `id` and `name`. See `introduction` for details about locating elements. """ if not values: raise ValueError("No value given.") items_str = "value(s) '%s'" % ", ".join(values) self._info("Unselecting %s from list '%s'." % (items_str, locator)) select = self._get_select_list(locator) if not select.is_multiple: raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.") for value in values: select.deselect_by_value(value)
def unselect_from_list_by_label(self, locator, *labels): """Unselects `*labels` from list identified by `locator` Select list keywords work on both lists and combo boxes. Key attributes for select lists are `id` and `name`. See `introduction` for details about locating elements. """ if not labels: raise ValueError("No value given.") items_str = "label(s) '%s'" % ", ".join(labels) self._info("Unselecting %s from list '%s'." % (items_str, locator)) select = self._get_select_list(locator) if not select.is_multiple: raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.") for label in labels: select.deselect_by_visible_text(label) # Private
def test_add_new_dataset(driver, project): driver.get("/") driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(project.id)) driver.find_element_by_id('react-tabs-2').click() driver.find_element_by_partial_link_text('Upload new dataset').click() dataset_name = driver.find_element_by_css_selector('[name=datasetName]') dataset_name.send_keys(test_dataset_name) header_file = driver.find_element_by_css_selector('[name=headerFile]') header_file.send_keys(pjoin(os.path.dirname(os.path.dirname(__file__)), 'data', 'asas_training_subset_classes.dat')) tar_file = driver.find_element_by_css_selector('[name=tarFile]') tar_file.send_keys(pjoin(os.path.dirname(os.path.dirname(__file__)), 'data', 'asas_training_subset.tar.gz')) driver.find_element_by_class_name('btn-primary').click() status_td = driver.wait_for_xpath( "//div[contains(text(),'Successfully uploaded new dataset')]")
def test_edit_project(driver, project): driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(project.id)) project_name = driver.find_element_by_css_selector('[name=projectName]') project_name.clear() test_proj_name = str(uuid.uuid4()) project_name.send_keys(test_proj_name) project_desc = driver.find_element_by_css_selector('[name=projectDescription]') project_desc.clear() project_desc.send_keys("New Test Description") driver.find_element_by_class_name('btn-primary').click() status_td = driver.wait_for_xpath( "//div[contains(text(),'Successfully updated project')]") assert driver.find_element_by_css_selector('[name=projectName]').\ get_attribute("value") == test_proj_name assert driver.find_element_by_css_selector('[name=projectDescription]').\ get_attribute("value") == "New Test Description"
def test_add_new_featureset(driver, project, dataset): driver.get('/') driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(project.id)) driver.find_element_by_id('react-tabs-4').click() driver.find_element_by_partial_link_text('Compute New Features').click() featureset_name = driver.find_element_by_css_selector('[name=featuresetName]') featureset_name.send_keys(test_featureset_name) driver.find_element_by_class_name('btn-primary').click() driver.wait_for_xpath("//div[contains(text(),'Feature computation begun')]") driver.wait_for_xpath("//td[contains(text(),'Completed')]", 30)
def test_check_uncheck_tags(driver, project, dataset): driver.get('/') driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(project.id)) driver.find_element_by_id('react-tabs-4').click() driver.find_element_by_partial_link_text('Compute New Features').click() driver.find_element_by_partial_link_text('Filter By Tag').click() driver.find_element_by_xpath("//li[contains(text(),'General')]").click() driver.find_element_by_css_selector('[name=amplitude]') driver.find_element_by_css_selector('[label=Astronomy]').click() time.sleep(0.1) driver.find_element_by_css_selector('[label=General]').click() time.sleep(0.1) with pytest.raises(NoSuchElementException): driver.find_element_by_css_selector('[name=amplitude]').click() driver.find_element_by_css_selector('[label=General]').click() driver.wait_for_xpath('//*[@name="amplitude"]')
def _add_prediction(proj_id, driver): driver.refresh() proj_select = Select(driver.wait_for_xpath('//select[@name="project"]')) proj_select.select_by_value(str(proj_id)) driver.find_element_by_id('react-tabs-8').click() driver.find_element_by_partial_link_text('Predict Targets').click() driver.find_element_by_class_name('btn-primary').click() driver.wait_for_xpath("//div[contains(text(),'Model predictions begun')]") try: driver.wait_for_xpath("//td[contains(text(),'Completed')]", 30) except: driver.save_screenshot("/tmp/pred_fail.png") raise
def _build_model(proj_id, model_type, driver): driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(proj_id)) driver.find_element_by_id('react-tabs-6').click() driver.find_element_by_partial_link_text('Create New Model').click() model_select = Select(driver.find_element_by_css_selector('[name=modelType]')) model_select.select_by_visible_text(model_type) model_name = driver.find_element_by_css_selector('[name=modelName]') test_model_name = str(uuid.uuid4()) model_name.send_keys(test_model_name) driver.find_element_by_class_name('btn-primary').click() try: driver.wait_for_xpath("//div[contains(text(), 'Model training begun')]") driver.wait_for_xpath("//td[contains(text(), 'Completed')]", 10) except: driver.save_screenshot("/tmp/models_fail.png") raise
def test_hyper_param_populate(driver, project, featureset, model): driver.get('/') driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(project.id)) driver.find_element_by_id('react-tabs-6').click() driver.find_element_by_partial_link_text('Create New Model').click() driver.find_element_by_partial_link_text('Choose Model Parameters').click() model_select = Select(driver.find_element_by_css_selector('[name=modelType]')) model_select.select_by_visible_text("RandomForestClassifier (fast)") driver.wait_for_xpath("//label[contains(text(),'n_estimators')]") driver.wait_for_xpath("//label[contains(text(),'max_features')]") model_select.select_by_visible_text("RidgeClassifierCV") driver.wait_for_xpath("//label[contains(text(),'alphas')]") driver.wait_for_xpath("//label[contains(text(),'scoring')]") model_select.select_by_visible_text("BayesianRidgeRegressor") driver.wait_for_xpath("//label[contains(text(),'n_iter')]") driver.wait_for_xpath("//label[contains(text(),'alpha_1')]")
def test_cannot_build_model_unlabeled_data(driver, project, featureset): driver.get('/') driver.refresh() proj_select = Select(driver.find_element_by_css_selector('[name=project]')) proj_select.select_by_value(str(project.id)) driver.find_element_by_id('react-tabs-6').click() driver.find_element_by_partial_link_text('Create New Model').click() model_name = driver.find_element_by_css_selector('[name=modelName]') model_name.send_keys(str(uuid.uuid4())) driver.find_element_by_class_name('btn-primary').click() driver.wait_for_xpath( "//div[contains(.,'Cannot build model for unlabeled feature set.')]")
def select_state_option(self, value, dowait=True): ''' Select state value from dropdown. Wait until district dropdown has loaded before returning. ''' #path = '//select[@id="variation-tablepress-32"]' path = '//select[@id="variation-tablepress-31"]' district_select_elem = self.driver.find_element_by_xpath(path) def district_select_updated(driver): try: district_select_elem.text except StaleElementReferenceException: return True except: pass return False state_select = self.get_state_select() state_select.select_by_value(value) return self.get_state_select()
def select_by_visible_text(self, locator, option_text, replacement=None, retry_by_browser_refresh=False): """Select an option by visible option text :param locator: locator of select element :param replacement: if locator contains dynamic part, i.e. '$value', it will be replaced by replacement variable :param option_text: option text by which to select the option :param retry_by_browser_refresh: if set to True, when webdriver is not able to find any element, it will refresh the browser and try to find the element again :return: None """ if replacement: locator = locator.replace('$value', replacement) try: select = Select(self.fetch_element(locator)) select.select_by_visible_text(option_text) self.context.logger.info("Selected element '" + locator + "' by visible text '" + option_text + "'") except Exception as e: self.context.logger.error("Unable to select option '" + option_text + "'. Error: %s" % e, exc_info=True) Assert.assert_fail("Unable to select option '" + option_text + "'")
def test_number_kanbancolumns_for_case_not_default(self): driver = self.selenium issue = Issue(title="title", kanbancol=KanbanColumn.objects.get(project=self.project, name="Todo"), due_date=str(datetime.date.today()), priority=3, storypoints=2, description="blubber", project=self.project ) issue.save() issue.assignee.add(self.user) driver.get("{}{}".format(self.live_server_url, reverse('issue:create', kwargs={'project': self.project2.name_short}))) driver.find_element_by_id("id_title").send_keys("title") # assert that 2nd project has one kanban col more self.assertEqual(len(Select(driver.find_element_by_id("id_kanbancol")).options), 5) # assert that dependsOn now has one entry driver.get('{}{}'.format(self.live_server_url, reverse('issue:backlog', kwargs={'project': self.project.name_short} ))) driver.find_element_by_link_text("New issue").click() driver.find_element_by_xpath("(//input[@type='search'])[2]").send_keys('\n') time.sleep(1) self.assertEqual(len(driver.find_elements_by_css_selector('#select2-id_dependsOn-results li')), 1) for i in driver.find_elements_by_css_selector('#select2-id_dependsOn-results li'): self.assertIn("title", i.text)
def test_edit_same_settings_as_set(self): driver = self.selenium issue = Issue(title="title", kanbancol=KanbanColumn.objects.get(project=self.project, name="Todo"), due_date=str(datetime.date.today()), priority=3, storypoints=2, description="blubber", project=self.project ) issue.save() issue.assignee.add(self.user) driver.get("{}{}".format(self.live_server_url, reverse('issue:edit', kwargs={'project': self.project.name_short, 'sqn_i': issue.number}))) self.assertEqual(len(Select(driver.find_element_by_id("id_kanbancol")).options), 4) # issue must not depend on itself driver.find_element_by_xpath("(//input[@type='search'])[2]").send_keys('\n') time.sleep(1) self.assertEqual(len(driver.find_elements_by_css_selector('#select2-id_dependsOn-results li')), 1) for i in driver.find_elements_by_css_selector('#select2-id_dependsOn-results li'): self.assertEqual(i.text, "No results found")
def wait_for_dip_in_transfer_backlog(self, dip_uuid): """Wait for the DIP with UUID ``dip_uuid`` to appear in the Backlog tab. """ max_seconds = 120 seconds = 0 while True: self.navigate(self.get_transfer_backlog_url(), reload=True) self.driver.find_element_by_css_selector( 'input[title="search query"]').send_keys(dip_uuid) Select(self.driver.find_element_by_css_selector( 'select[title="field name"]')).select_by_visible_text( 'SIP UUID') Select(self.driver.find_element_by_css_selector( 'select[title="query type"]')).select_by_visible_text( 'Phrase') self.driver.find_element_by_id('search_submit').click() summary_el = self.driver.find_element_by_id('backlog-entries_info') if 'Showing 0 to 0 of 0 entries' == summary_el.text.strip(): seconds += 1 if seconds > max_seconds: break time.sleep(1) else: time.sleep(1) # Sleep a little longer, for good measure break
def change_encrypted_space_key(self, space_uuid, new_key_repr=None): """Edit the existing space with UUID ``space_uuid`` and set its GPG key to the existing one matching ``new_key_repr``, if provided, or else to any other key. """ self.navigate(self.get_space_edit_url(space_uuid)) select = Select(self.driver.find_element_by_id('id_protocol-key')) if new_key_repr: select.select_by_visible_text(new_key_repr) else: currently_selected = select.first_selected_option.text for option in select.options: if option.text != currently_selected: select.select_by_visible_text(option.text) break self.driver.find_element_by_css_selector('input[type=submit]').click() self.wait_for_presence('div.alert-success')
def get_value(self, selector): ''' Gets value of an element by CSS selector. Parameters ---------- selector: str A CSS selector to search for. This can be any valid CSS selector. Returns ------- str The value of a selenium element object. ''' elem = self.get_element(selector) if self.driver == 'Gecko': # Let's do this the stupid way because Mozilla thinks geckodriver is # so incredibly amazing. tag_name = elem.tag_name if tag_name == 'select': select = Select(elem) return select.all_selected_options[0].get_attribute('value') else: return elem.get_attribute('value') else: return elem.get_attribute('value')
def _set_select_elem(self, elem, value): self._scroll_into_view(elem) s = Select(elem) value = value if isinstance(value, string_types) else str(value) s.select_by_value(value)
def _set_select_elem_by_text(self, elem, text): self._scroll_into_view(elem) s = Select(elem) s.select_by_visible_text(text)
def configure_audible_library(driver, lang): logging.info("Opening Audible library") lib_url = "https://www.audible.com/lib" if lang != "us": lib_url = lib_url.replace('.com', "." + lang) driver.get(lib_url) time.sleep(2) logging.info("Selecting books from 'All Time'") select = Select(driver.find_element_by_id("adbl_time_filter")) select.select_by_value("all") time.sleep(5) # Make sure we are getting the ENHANCED format # u'ENHANCED' u'MP332' u'ACELP16' u'ACELP85' s = Select(driver.find_element_by_id("adbl_select_preferred_format")) if len(s.all_selected_options) == 1: if 'ENHANCED' == s.all_selected_options[0].get_attribute("value").strip(): logging.info("Selected format was ENHANCED, continuing") else: logging.info("Format was '%s', selecting 'ENHANCED'" % (s.all_selected_options[0].get_attribute("value"),)) for opt in s.options: if "ENHANCED" == opt.get_attribute("value"): opt.click() time.sleep(5) else: logging.critical("Got more than one adbl_select_preferred_format.all_selected_options") sys.exit(1) # Comment out this in hope of not hitting download limit as fast if not ('adbl-sort-down' in driver.find_element_by_id("SortByLength").get_attribute("class")): logging.info("Sorting downloads by shortest to longest") driver.find_element_by_id("SortByLength").click() time.sleep(10) else: logging.info("Downloads were already sorted by shortest to longest, continuing")
def _select_dropdown(self, value, element): select = Support.Select(element) select.select_by_visible_text(value)
def _select_dropdown_by_value(self, value, element): select = Support.Select(element) select.select_by_value(value)
def _get_dropdown_options(self, element): select = Support.Select(element) return select.options
def element(self): return Support.Select(self.src_elem)
def enter(self, message = None): self.log("Select active element") element = self.driver.switch_to.active_element element.send_keys(Keys.ENTER)
def enterAndSelectFromDropdown(self, by, value, text, message = None, nth = 1, \ dropdownBy = None, dropdownValue = None): element = self.assertElementPresent(by, value, message = message) if not element: self.onFail(by, value, message, "Not found") element = self.sendKeys(by, value, text) if dropdownBy: self.assertElementPresent(dropdownBy, dropdownValue, message) description = "{0}-th from {1} dropdown".format(nth, self.describeElement(by, value)) self.log("Find " + description) for i in range(1, nth+1): element = self.sendKeys(by, value, Keys.ARROW_DOWN) element = self.sendKeys(by, value, Keys.ENTER, message = "Select " + description) return element
def selectOptionByText(self, by, value, text): self.log("selection '{0}' option from {1}".format(text, self.describeElement(by, value))) return Select(self.assertElementPresent(by, value)).select_by_visible_text(text)
def duo_login(self, qr_code): """Log into duo.""" self.selenium.switch_to_frame( self.find_element(*self.LOCATORS.duo_iframe)) dropdown_element = self.wait.until(EC.element_to_be_clickable( self.LOCATORS.dropdown)) select = Select(dropdown_element) select.select_by_value(self.LOCATORS.value) passcode_button = self.wait.until(EC.element_to_be_clickable( self.LOCATORS.passcode_button)) passcode_button.click() self.find_element(*self.LOCATORS.QR_input).send_keys(qr_code) self.find_element(*self.LOCATORS.login_button).click() self.selenium.switch_to_default_content() return Home(self.selenium, self.base_url).wait_for_page_to_load()
def get_action_selected(self): """Return action selected on recipe page.""" select = Select(self.find_element(*self.LOCATORS.action)) value = select.first_selected_option.get_attribute('value') return value
def action_configuration(self, conf, recipe_action): """Configure action for recipe.""" action_dropdown = self.wait.until(EC.element_to_be_clickable( self.LOCATORS.action)) select = Select(action_dropdown) select.select_by_value(recipe_action) action_message = conf.get('recipe', 'recipe_message') if recipe_action == 'console-log': self.find_element(*self.LOCATORS.action_message).clear() self.find_element(*self.LOCATORS.action_message).send_keys(action_message) # noqa if recipe_action == 'show-heartbeat': recipe_survey_id = conf.get('recipe', 'recipe_survey_id') recipe_thanks_message = conf.get('recipe', 'recipe_thanks_message') recipe_post_url = conf.get('recipe', 'recipe_post_url') recipe_learn_more = conf.get('recipe', 'recipe_learn_more') recipe_learn_more_url = conf.get('recipe', 'recipe_learn_more_url') self.find_element(*self.LOCATORS.survey_id).clear() self.find_element(*self.LOCATORS.survey_id).send_keys(recipe_survey_id) # noqa self.find_element(*self.LOCATORS.action_message).clear() self.find_element(*self.LOCATORS.action_message).send_keys(action_message) # noqa self.find_element(*self.LOCATORS.thanks_message).clear() self.find_element(*self.LOCATORS.thanks_message).send_keys(recipe_thanks_message) # noqa self.find_element(*self.LOCATORS.post_answer_url).clear() self.find_element(*self.LOCATORS.post_answer_url).send_keys(recipe_post_url) # noqa self.find_element(*self.LOCATORS.learn_more).clear() self.find_element(*self.LOCATORS.learn_more).send_keys(recipe_learn_more) # noqa self.find_element(*self.LOCATORS.learn_more_url).clear() self.find_element(*self.LOCATORS.learn_more_url).send_keys(recipe_learn_more_url) # noqa if recipe_action == 'preference-experiment': pass
def insert_one_match(self, match): # match is a dict: {} """ driver = self.driver driver.find_element_by_css_selector("a.pull-right.btn.btn-default.btn-small.newMatchButton").click() select = Select(driver.find_element_by_name('countFactions')) option = select.first_selected_option select.select_by_index(0) driver.find_element_by_name('newGameMatch').send_keys("Foosball") #driver.find_element_by_id('additionalOptionButton').click() #driver.find_element_by_css_selector('a.btn.btn-xs.btn-default').click() driver.execute_script("matchForm.toggleAdditionalOptions();") driver.find_element_by_name('newPlaceMatch').send_keys("Xiaomi Wuchaicheng 11F") driver.find_element_by_css_selector('button.btn.btn-default.btn-sm.next.pull-right').click() xpath = '//label[text()=' + '" ???"' + ']' driver.find_element_by_xpath(xpath).click() xpath = '//label[text()=' + '" ???"' + ']' driver.find_element_by_xpath(xpath).click() driver.find_element_by_css_selector('button.btn.btn-default.btn-sm.next.pull-right').click() xpath = '//div[@data-step-id="1"]/div/div/p/label[text()=' + '" Xinyan Xing"' + ']' driver.find_element_by_xpath(xpath).click() xpath = '//div[@data-step-id="1"]/div/div/p/label[text()=' + '" Zhaoruihua"' + ']' driver.find_element_by_xpath(xpath).click() driver.find_element_by_css_selector('button.btn.btn-default.btn-sm.next.pull-right').click() score1 = 5 score2 = 3 driver.find_element_by_css_selector('input.form-control.input-xs').send_keys(score1) driver.find_element_by_xpath('//div[@data-faction-step-class="matchStep3"]/div[3]/input').send_keys(score2) driver.find_element_by_name('matchNotes').send_keys("Auto inputed by Yin Kangkai's bot") driver.find_element_by_css_selector('a.btn.btn-primary.additionalButton').click() print "done"
def fast_multiselect(self, element_id, labels): select = Select(self.drv.find_element_by_id(element_id)) for label in labels: select.select_by_visible_text(label)
def test_945(self): self.case_no = self.get_case_number() self.log.info(' CASE %s log: ' % str(self.case_no)) self.driver.maximize_window() for item in ["Packages", "Recipes", "Tasks"]: self.driver.get(self.base_url) self.driver.find_element_by_link_text("core-image-minimal").click() self.driver.find_element_by_link_text(items).click() # this may be page specific. If future page content changes, try to replace it with new xpath xpath_showrows = "/html/body/div[4]/div/div/div[2]/div[2]/div[2]/div/div/div[2]/select" xpath_table = "html/body/div[4]/div/div/div[2]/div[2]/table/tbody"#"id=('otable')/tbody" self.driver.find_element_by_xpath(xpath_showrows).click() rows_displayed = int(self.driver.find_element_by_xpath(xpath_showrows + "/option[2]").text) # not sure if this is a Selenium Select bug: If page is not refreshed here, "select(by visible text)" operation will go back to 100-row page # Sure we can use driver.get(url) to refresh page, but since page will vary, we use click link text here self.driver.find_element_by_link_text(items).click() Select(self.driver.find_element_by_css_selector("select.pagesize")).select_by_visible_text(str(rows_displayed)) self.failUnless(self.is_element_present(By.XPATH, xpath_table + "/tr[" + str(rows_displayed) +"]")) self.failIf(self.is_element_present(By.XPATH, xpath_table + "/tr[" + str(rows_displayed+1) +"]")) # click 1st package, then go back to check if it's still those rows shown. self.driver.find_element_by_xpath(xpath_otable + "/tr[1]/td[1]/a").click() time.sleep(3) self.driver.find_element_by_link_text(item).click() self.assertTrue(self.is_element_present(By.XPATH, xpath_otable + "/tr[" + str(option_tobeselected) +"]"),\ msg=("Row %d should exist" %option_tobeselected)) self.assertFalse(self.is_element_present(By.XPATH, xpath_otable + "/tr[" + str(option_tobeselected+1) +"]"),\ msg=("Row %d should not exist" %(option_tobeselected+1))) ############## # CASE 946 # ##############
def test_new_duplicates_project_name(self): """ Should not be able to create a new project whose name is the same as an existing project """ project_name = "dupproject" Project.objects.create_project(name=project_name, release=self.release) url = reverse('newproject') self.get(url) self.enter_text('#new-project-name', project_name) select = Select(self.find('#projectversion')) select.select_by_value(str(self.release.pk)) element = self.wait_until_visible('#hint-error-project-name') self.assertTrue(("Project names must be unique" in element.text), "Did not find unique project name error message") # Try and click it anyway, if it submits we'll have a new project in # the db and assert then try: self.click("#create-project-button") except InvalidElementStateException: pass self.assertTrue( (Project.objects.filter(name=project_name).count() == 1), "New project not found in database")
def launch_application(self, application): # find the launch application button to activate app_launch_button = self._get_element( *self._app_launch_button_locator) # find the application selector at the top of the page app_selector = self._get_element(*self._application_selector_locator) # Access the app selector dropdown = Select(app_selector) # Choose the correct option in the selector dropdown.select_by_value(application) # Perform the launch app_launch_button.click()
def fill(self, by, arg, value, root=None): root = root or self.driver element = root.find_element(by, arg) if element.tag_name == 'select': Select(element).select_by_visible_text(value) elif element.get_attribute('type') == 'checkbox': if element.is_selected() and value is False: element.click() elif not element.is_selected() and value is True: element.click() else: element.clear() element.send_keys(value)