class FunctionalSearchTest(LiveServerTestCase): def use_xvfb(self): from pyvirtualdisplay import Display self.display = Display("xvfb", visible=1, size=(1280, 1024)) self.display.start() self.driver = WebDriver() def setUp(self): try: self.driver = WebDriver() ui_is_not_available = False except WebDriverException: ui_is_not_available = True if settings.TEST_HEADLESS or ui_is_not_available: self.use_xvfb() self.driver.implicitly_wait(10) super(FunctionalSearchTest, self).setUp() def tearDown(self): self.driver.quit() if hasattr(self, "display"): self.display.stop() super(FunctionalSearchTest, self).tearDown() def test_simple_homepage_address_search_redirect(self): self.driver.get(self.live_server_url) input = self.driver.find_element_by_id("vc-search-input") input.send_keys("foobar\r") summary = self.driver.find_element_by_id("result-description") self.assertEqual(summary.text, 'No results for "foobar"')
def login(browser: webdriver.WebDriver): """ The login(driver) function is used to login into JIRA :param browser: instance of a selenium.webdriver() object :return: No return value """ from elticket import helper_config config = helper_config.get_config() have_dns = config.getboolean(config.sections()[0], 'have_dns') homepage_url_no_dns = config.get(config.sections()[0], 'homepage_url_no_dns') homepage_url = config.get(config.sections()[0], 'homepage_url') login_user = config.get(config.sections()[2], 'user_value') login_pw = config.get(config.sections()[2], 'pw_value') if have_dns: browser.get(homepage_url) else: browser.get(homepage_url_no_dns) fld_user = browser.find_element_by_id(elements_jira.fld_login_user_id) fld_user.click() retry_element_is_focused(browser, fld_user) fld_user.send_keys(login_user) fld_pw = browser.find_element_by_id(elements_jira.fld_login_pw_id) fld_pw.click() retry_element_is_focused(browser, fld_pw) fld_pw.send_keys(login_pw) btn_login = browser.find_element_by_id(elements_jira.btn_login_id) btn_login.click()
def log_in(driver: WebDriver): print("Logging in...") global PASSWORD, USERNAME username = USERNAME password = PASSWORD sign_in_div: WebElement = driver.find_element_by_class_name("nav-user-sign-in") # type: ignore sign_in_buttons: list[WebElement] = sign_in_div.find_elements_by_class_name("nav-header-button") for button in sign_in_buttons: if button.text == "Log In": driver.execute_script("arguments[0].click();", button) email_input = driver.find_element_by_id("rec-acct-sign-in-email-address") password_input = driver.find_element_by_id("rec-acct-sign-in-password") email_input.send_keys(username) # type: ignore password_input.send_keys(password) # type: ignore # Press Log In Button log_in_btn = driver.find_element_by_class_name("rec-acct-sign-in-btn") driver.execute_script("arguments[0].click();", log_in_btn) print("Logged in.") # Wait till login page is gone. WebDriverWait(driver, 10).until(EC.invisibility_of_element((By.ID, "signInModalHeading")))
class Base: @classmethod def __init__(self, p_live_server_url): self.live_server_url = p_live_server_url self.driver = WebDriver() @classmethod def pause(self, p_seconds): try: WebDriverWait(self.driver, p_seconds).until(EC.title_is('pause')) except: pass @classmethod def grid_cell_doubleclick(self, p_element): ActionChains(self.driver).double_click(p_element).perform() @classmethod def grid_cell_input(self, p_element, p_text): self.grid_cell_doubleclick(p_element) for k in range(0, len(p_element.text)): p_element.send_keys(Keys.BACKSPACE) p_element.send_keys(p_text) @classmethod def action_login(self, p_username, p_password, p_expectsuccess=True): self.driver.get('{0}{1}'.format(self.live_server_url, '/login/')) WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body'))) username_input = self.driver.find_element_by_id('txt_user') username_input.send_keys(p_username) password_input = self.driver.find_element_by_id('txt_pwd') password_input.send_keys(p_password) self.driver.find_element_by_xpath("//button[. = 'Sign in']").click() if p_expectsuccess: try: WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'header'))) except: WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, 'div_alert_text'))) else: try: WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, 'div_alert_text'))) except: WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'header'))) @classmethod def action_create_user(self, p_username, p_password, p_superuser): self.driver.get('{0}{1}'.format(self.live_server_url, '/users/')) WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body'))) assert 'OmniDB' in self.driver.title self.driver.find_element_by_xpath("//button[. = 'New User']").click() username_cell = self.driver.find_element_by_xpath("//tbody/tr[last()]/td[1]") self.grid_cell_input(username_cell, p_username) password_cell = self.driver.find_element_by_xpath("//tbody/tr[last()]/td[2]") self.grid_cell_input(password_cell, p_password) if p_superuser: superuser_cell = self.driver.find_element_by_xpath("//tbody/tr[last()]/td[3]") self.grid_cell_doubleclick(superuser_cell) self.driver.find_element_by_tag_name('body').click() self.driver.find_element_by_xpath("//button[. = 'Save Data']").click()
def syn_test_script(): try: success = True driver = WebDriver() driver.implicitly_wait(30) log_output("Starting @ http://www.kay.com/en/kaystore") driver.get("http://www.kay.com/en/kaystore") log_output("Navigating to Engagement Rings") ActionChains(driver).move_to_element(driver.find_element_by_xpath("//div[3]/div[2]/div/div/div[3]/nav/div/ul/li[4]/a[2]")).perform() driver.find_element_by_xpath("//div[3]/div[2]/div/div/div[3]/nav/div/ul/li[4]/ul/li[2]/div/div/div[2]/ul/li[2]/ul/li/ul/li[1]/a").click() time.sleep(2) if not ("Engagement" in driver.find_element_by_tag_name("html").text): success = False print("Did not find word engagement on page in reasonable time") log_output("Changing price range to 3rd facet") if not driver.find_element_by_id("facet_checkbox7").is_selected(): driver.find_element_by_id("facet_checkbox7").click() time.sleep(3) log_output("Viewing more rings") driver.find_element_by_id("view-more").click() log_output("Select a nice ring") driver.find_element_by_xpath("//div[3]/div[2]/div/div/div[4]/div[7]/div[2]/div[2]/div[7]/div[37]/div/a/img").click() #log_output("starting timer") #time.sleep(5) log_output("Add Ring to bag") # There is a bit of funkiness with this Product page and the overlay when you add an item to Cart # Sometimes the addToCartBtn is not immediately available and can time out or error out # The 5 second sleep timer above is disabled, but if we see issues this may need re-anabled # or use WebDriverWait ActionChains(driver).move_to_element(driver.find_element_by_xpath("//a[@id='addToCartBtn']")).perform() driver.find_element_by_xpath("//a[@id='addToCartBtn']") driver.find_element_by_xpath("//a[@id='addToCartBtn']").click() log_output("Adding coverage") driver.find_element_by_link_text("ADD TO BAG").click() log_output("Checking out with a beautiful ring!") driver.find_element_by_link_text("CHECKOUT").click() if not ("Shopping Bag (1 Item)" in driver.find_element_by_tag_name("html").text): success = False print("verifyTextPresent failed") finally: driver.quit() if not success: raise Exception("Test failed.")
def loginToWebsite(self, driver: WebDriver) -> None: """ 1) Login using credentials in `config.cfg` 2) sleep for 3 seconds """ inputElement = driver.find_element_by_id("Username") inputElement.send_keys(self.EMAIL) inputElement = driver.find_element_by_id("Password") inputElement.send_keys(self.PASSWORD) inputElement.send_keys(Keys.ENTER) sleep(3)
class TestFirefox(LiveServerTestCase): """To test a user story using Firefox""" def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.selenium.maximize_window() temp_user_creation() db_init() def tearDown(self): self.selenium.close() def test_login(self): """Test when the user wants to log in""" self.selenium.get('%s%s' % (self.live_server_url, '/authentication/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys('*****@*****.**') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('test2020') submit = self.selenium.find_element_by_id("submit-button") submit.send_keys(Keys.RETURN) def test_search_product_details(self): """To test when the user wants to search a prod and its details""" self.selenium.get('%s%s' % (self.live_server_url, '/')) query_input = self.selenium.find_element_by_id("query") query_input.send_keys('nutella') search = self.selenium.find_element_by_id("search-btn") search.send_keys(Keys.RETURN) product = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='details-link']"))) product.click() def test_save_product(self): """To test when the user wants to save a product""" self.test_login() query_input = self.selenium.find_element_by_id("query") query_input.send_keys('nutella') search = self.selenium.find_element_by_id("search-btn") search.send_keys(Keys.RETURN) product = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.ID, "product-title"))) product.click() substitute = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='save-btn']"))) substitute.click() def test_logout(self): self.test_login() logout = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='logout']"))) logout.click()
class MySeleniumTests(LiveServerTestCase): def setUp(self): self.selenium = WebDriver(executable_path='C:/geckodriver.exe') self.selenium.implicitly_wait(10) self.user = User.objects.create_user('wafistos4', '*****@*****.**', 'djamel2013') self.profile = Profile.objects.get_or_create(user=self.user, image='picture/wafi.png') def tearDown(self): self.selenium.quit() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/register/login/')) self.selenium.find_element_by_id("id_username").send_keys('wafistos4') self.selenium.find_element_by_id("id_password").send_keys('djamel2013') self.selenium.find_element_by_id('submitBtn').click() self.assertEquals(self.selenium.title, 'Home') def test_search(self): self.selenium.get('%s%s' % (self.live_server_url, '/store')) query = self.selenium.find_element_by_name("q") query.send_keys('Pepsi') self.selenium.find_element_by_id('submitId').click() # todo ajouter le test du formulaire
class HomeTestCase(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(3) def test_home(self): self.browser.get('{0}{1}'.format(self.live_server_url,reverse('index'))) body = self.browser.find_element_by_tag_name('body') self.assertIn('username', body.text) user = ModelTestFactory.getUser(password='******') username_input = self.browser.find_element_by_name("username") username_input.send_keys(user.username) password_input = self.browser.find_element_by_name("password") password_input.send_keys('test') self.browser.find_element_by_id('loginBtn').click()
def fill_in_element(driver: webdriver.WebDriver, by: By, locator, content, confirm=False): config = helper_config.get_config() wait_until_confirm_selection = config.getfloat( config.sections()[1], 'wait_until_confirm_selection') # from selenium.webdriver.support.wait import WebDriverWait try: if retry_element_is_visible(driver, by, locator): WebDriverWait(driver, 10).until(ec.element_to_be_clickable((by, locator))) element = driver.find_element_by_id(locator) if retry_element_can_be_filled(driver, By.ID, locator, content): if confirm: time.sleep(wait_until_confirm_selection) element.send_keys(Keys.RETURN) logging.info("Entered information in %s" % str(locator)) except NoSuchElementException: logging.error("Cannot find the element %s" % str(locator)) except StaleElementReferenceException: logging.error("Element %s is not available" % str(locator))
def work(pid): print('Starting %s' % str(pid)) wd = WebDriver() wd.set_window_size(1280, 1000) wd.implicitly_wait(15) try: wd.get("http://trumpdonald.org/") while True: wd.find_element_by_id("can").click() finally: raise Exception("Test exited. pid=%s" % str(pid)) wd.quit() return None
class SeleniumTest(TestCase): """Testing google.com""" def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(5) self.browser.get('http://google.com') def tearDown(self): self.browser.close() def search(self, search_string): q = self.browser.find_element_by_name('q') q.send_keys(search_string) q.submit() results = self.browser.find_element_by_id('search') return results.find_elements_by_tag_name('a') def test_python(self): for link in self.search('python'): if 'https://www.python.org/' in (link.get_attribute('href') or ''): break else: self.fail('python.com is not on google results page') def test_python_in_title(self): self.search('python django') assert 'python' in self.browser.title
def increase_quantity_to_two(driver: WebDriver): print("Attempting to increase quantity to two!") # Open quantity selection quantity_open_button = "guest-counter" WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.ID, quantity_open_button))) open_quantity_button = driver.find_element_by_id(quantity_open_button) driver.execute_script("arguments[0].click();", open_quantity_button) # Find the div that holds the increase quantity button div_holder_of_increase_button = "rec-guest-counter-row" WebDriverWait(driver, 5).until( EC.presence_of_element_located( (By.CLASS_NAME, div_holder_of_increase_button))) open_div_holder_of_increase_button: WebElement = driver.find_element_by_class_name( div_holder_of_increase_button) # Get the button we want from within this element plus_and_minus_button_class_name = "sarsa-button-subtle" buttons = open_div_holder_of_increase_button.find_elements_by_class_name( plus_and_minus_button_class_name) select_plus_button = buttons[1] driver.execute_script("arguments[0].click();", select_plus_button) # # Hit close and continue (probably not needed) # close_button_selector = "sarsa-button-link" # button = open_div_holder_of_increase_button.find_element_by_class_name(close_button_selector) # driver.execute_script("arguments[0].click();", button) print("Successful at increasing quantity to two!")
def switch_to_iframe(driver: webdriver.WebDriver, iframe_id) -> None: retry_element_is_visible(driver, By.ID, iframe_id) try: driver.switch_to.frame(driver.find_element_by_id(iframe_id)) except NoSuchElementException: logging.error("Cannot find the specified iFrame") finally: return None
def test_overwrite(self): driver2 = WebDriver() self.selenium.get('%s%s' % (self.live_server_url, '/apka/1/')) self.selenium.implicitly_wait(100) edit_button1 = self.selenium.find_element_by_id('editButton1') save_button1 = self.selenium.find_element_by_id('submitButton1') edit_button1.click() driver2.get('%s%s' % (self.live_server_url, '/apka/1/')) driver2.implicitly_wait(100) edit_button2 = driver2.find_element_by_id('editButton1') save_button2 = driver2.find_element_by_id('submitButton1') edit_button2.click() driver2.implicitly_wait(100) inputok = driver2.find_element_by_name('ok') inputok.clear() inputok.send_keys('0') inputupr = driver2.find_element_by_name('upr') inputupr.clear() inputupr.send_keys('1') save_button2.click() alert = driver2.switch_to.alert self.assertEqual(alert.text, "Zapisano dane") alert.accept() obwod = Obwod.objects.get(id=1) self.assertEqual(obwod.otrzymanych_kart, 0) self.assertEqual(obwod.uprawnionych, 1) driver2.quit() self.selenium.implicitly_wait(100) inputok = self.selenium.find_element_by_name('ok') inputok.clear() inputok.send_keys('42') inputupr = self.selenium.find_element_by_name('upr') inputupr.clear() inputupr.send_keys('1337') save_button1.click() alert = self.selenium.switch_to.alert self.assertEqual(alert.text, u"Dane zmieniły się od ostatniego zapisu. Zapisujesz 1337, a ktoś inny zapisał 1") alert.accept() obwod = Obwod.objects.get(id=1) self.assertEqual(obwod.otrzymanych_kart, 0) self.assertEqual(obwod.uprawnionych, 1)
def test_start_page_with_files(browser: WebDriver, home_page): browser.get(home_page) assert browser.title == 'Feed files control - FFC' header_text = browser.find_element_by_tag_name('h1').text assert header_text == 'Feed files control - FFC' button = browser.find_element_by_id('id_new_manufacturers') button.click() form = browser.find_element_by_tag_name('form') assert form name_brand_field = browser.find_element_by_id('id_brand_name') file_field = browser.find_element_by_id("id_file_feed") name_brand_field.send_keys('Bosh') # TODO: change to pytest tmpfile file_field.send_keys(os.path.join(os.path.dirname(__file__), "example.txt")) form.submit() sleep(3) check_for_row_in_table_manufactured(browser, 'Bosh') check_for_row_in_table_manufactured(browser, 'example.txt')
def syn_test_script(): try: success = True driver = WebDriver() driver.implicitly_wait(30) # Disabled page sizing and instead used action chains to move mouse around #driver.set_window_size(1920, 1080) # Use Action chains to navigate page when there is an issue with the selection menus # If the menu item does not appear to select, it means there was a page movement that happened # out of sync with the action. driver.get("http://www.jared.com/en/jaredstore") log_output("Searching for Engagement") driver.find_element_by_id("SimpleSearchForm_SearchTerm").click() driver.find_element_by_id("SimpleSearchForm_SearchTerm").clear() driver.find_element_by_id("SimpleSearchForm_SearchTerm").send_keys("Engagement") driver.find_element_by_id("searchButton").click() log_output("Verify text on page") if not ("Engagement" in driver.find_element_by_tag_name("html").text): success = False print("verifyTextPresent failed") finally: driver.quit() if not success: raise Exception("Test failed.")
class LoginTest(unittest.TestCase): def setUp(self): self.driver = WebDriver() def tearDown(self): self.driver.quit() def test_can_login(self): self.driver.get(LOGIN_PAGE_URL) login_form = self.driver.find_element_by_id("login") assert_that(login_form.is_displayed(), equal_to(True))
def stop_watcher_and_get_data(driver: WebDriver, wait: WebDriverWait, watcher_window: Union[str, int], page: Page) -> bool: """ Watcher.htmlのStop Watchingボタンをクリック。 拡張機能が監視を終え、収集したデータを記録。 """ logger.debug("Watcher: stop") try: # watcher.htmlに移動してstopをクリック # クリックすると、Watcher.htmlのdivタグ(id="contents")の中に、収集したデータを記録する driver.switch_to.window(watcher_window) wait.until( expected_conditions.visibility_of_element_located((By.ID, "stop"))) elm = driver.find_element_by_id("stop") elm.click() # contentsの最後の要素がDOMに現れるまで待つ wait.until( expected_conditions.presence_of_element_located( (By.ID, "EndOfData"))) # watcher.htmlのHTMLをpageインスタンスのプロパティに保存 page.watcher_html = driver.page_source # type: ignore # clearContentsをクリック elm: Any = driver.find_element_by_id("clearContents") elm.click() # 最後の要素が消えるまで待つ wait.until( expected_conditions.invisibility_of_element_located( (By.ID, "EndOfData"))) except Exception as err: logger.exception(f'{err}') return False else: logger.debug("Watcher: Get data from Watcher") return True
def navigate_to_date(driver: WebDriver, desired_date: str, date_picker_element, id=True): print(f"Navigating to intended date. {desired_date}") if id: select_date: WebElement = driver.find_element_by_id(date_picker_element) # type: ignore else: select_date: WebElement = driver.find_element_by_class_name(date_picker_element) # type: ignore select_date.click() select_date.send_keys(Keys.CONTROL, "a") select_date.send_keys(desired_date) print(f"Navigated to date: {desired_date}")
def open_new_ticket(browser: webdriver.WebDriver): """ The open_new_ticket(browser) function opens a new ticket without any further specifications :param browser: instance of a selenium.webdriver() object :return: No return value """ try: WebDriverWait(browser, 20).until( EC.presence_of_element_located( (By.ID, elements_jira.btn_newissue_id))) WebDriverWait(browser, 20).until( EC.visibility_of_element_located( (By.ID, elements_jira.section_dashboard_id))) time.sleep(0.5) finally: bt_create = browser.find_element_by_id(elements_jira.btn_newissue_id) bt_create.click() logging.info("Creating new issue ticket ...")
def _fill_new_user_form(self, webdriver: WebDriver): """ Fill the new user form """ self.assertEqual( '{}/admin/hub_app/hubuser/add/'.format(self.live_server_url), webdriver.current_url) webdriver.find_element_by_id('id_username').send_keys(self.test_user) webdriver.find_element_by_id('id_password1').send_keys( self.test_password) webdriver.find_element_by_id('id_password2').send_keys( self.test_password) webdriver.find_element_by_css_selector( 'input[type="submit"][name="_continue"]').click()
def decline_offer(offer_reference): driver = WebDriver() # Login selenium_login(webdriver=driver) # Decline offer driver.get('https://www.odesk.com/applications/%s' % offer_reference) driver.find_element_by_id("declineButton").click() driver.find_element_by_css_selector("option[value=\"146\"]").click() driver.find_element_by_id("otherReason").clear() driver.find_element_by_id("otherReason").send_keys("Test") driver.find_element_by_xpath("(//a[contains(text(),'Decline')])[2]").click() driver.close()
def prepare_browser(driver: WebDriver): driver.find_element(By.XPATH, '//a[.="Sign in"]').click() driver.implicitly_wait(3) driver.find_element_by_id('user_email').send_keys( '*****@*****.**') driver.find_element_by_id('user_password').send_keys('fdRQNtZi4m6mYd!') driver.find_element_by_id('user_password').send_keys(Keys.ENTER) time.sleep(5) driver.find_element(By.XPATH, '//span[.="Start Again"]').click() try: driver.find_element(By.XPATH, '//button[.="Yes"]').click() except NoSuchElementException: pass time.sleep(3)
def start_watcher_and_move_blank(driver: WebDriver, wait: WebDriverWait, watcher_window: Union[int, str], blank_window: str) -> bool: """ watcher.htmlのStart Watchingボタンをクリック。拡張機能が監視を始める """ logger.debug("Watcher: starting...") try: driver.switch_to.window(watcher_window) wait.until( expected_conditions.visibility_of_element_located( (By.ID, "start"))) elm: Any = driver.find_element_by_id("start") elm.click() driver.switch_to.window(blank_window) wait.until(lambda d: "Watcher" != driver.title) # type: ignore except Exception as err: logger.exception(f'{err}') return False else: return True
def add_odesk_teams(user): """ Creates oDesk teams that will be used for our jobs. """ driver = WebDriver() driver.implicitly_wait(time_to_wait=10) selenium_login(webdriver=driver) account = user.get_profile() # Gain access to settings driver.find_element_by_css_selector("a.oNavIcon.oNavIconSettings").click() driver.find_element_by_id("answer").clear() driver.find_element_by_id("answer").send_keys(settings.ODESK_TEST_ACC_ANSWER) driver.find_element_by_id("submitButton").click() sg_name = SAMPLE_GATHERING_TEAM % TEAM_PREFIX v_name = VOTING_TEAM % TEAM_PREFIX btmg_name = BTM_GATHERING_TEAM % TEAM_PREFIX btmv_name = BTM_VOTING_TEAM % TEAM_PREFIX sg_res = add_odesk_team(webdriver=driver, name=sg_name) v_res = add_odesk_team(webdriver=driver, name=v_name) btmg_res = add_odesk_team(webdriver=driver, name=btmg_name) btmv_res = add_odesk_team(webdriver=driver, name=btmv_name) if not all([sg_res, v_res, btmg_res, btmv_res]): log.warning('[oDesk] Failed to create oDesk teams.') return False client = make_client_from_account(account) teams = client.hr.get_teams() for team in teams: if team['name'] == sg_name: account.odesk_teams[JOB_SAMPLE_GATHERING_KEY] = team['reference'] elif team['name'] == v_name: account.odesk_teams[JOB_VOTING_KEY] = team['reference'] elif team['name'] == btmg_name: account.odesk_teams[JOB_BTM_GATHERING_KEY] = team['reference'] elif team['name'] == btmv_name: account.odesk_teams[JOB_BTM_VOTING_KEY] = team['reference'] account.save() return True
def syn_test_script(): try: success = True driver = WebDriver() driver.implicitly_wait(60) log_output("Starting @ http://www.kay.com/en/kaystore") driver.get("http://www.kay.com/en/kaystore") driver.find_element_by_id("site-search__input").click() driver.find_element_by_id("site-search__input").clear() driver.find_element_by_id("site-search__input").send_keys("engagement") driver.find_element_by_id("searchButton").click() if not ("Engagement" in driver.find_element_by_tag_name("html").text): success = False print("verifyTextPresent failed") finally: driver.quit() if not success: raise Exception("Test failed.")
class FamilyBrowseVariantFilterTests(unittest.TestCase): """ Test the same recessive search with the more granular variant filters """ def setUp(self): self.selenium = WebDriver() self.live_server_url = LIVE_SERVER_URL # login boilerplate blah self.selenium.get(self.live_server_url + '/login') username_input = self.selenium.find_element_by_name("username_or_email") username_input.send_keys(ADMIN_USERNAME) password_input = self.selenium.find_element_by_name("password") password_input.send_keys(ADMIN_PASSWORD) self.selenium.find_element_by_xpath('//button[@type="submit"]').click() # visit the family browse page self.selenium.get(self.live_server_url + '/project/1kg/family/1/mendelian-variant-search') # set inheritance self.selenium.find_element_by_xpath('//li[@class="inheritance-pill-li"][@data-search_mode="all_variants"]/a').click() def test_genes_filter(self): self.selenium.find_element_by_xpath('//a[@href="#collapse-region"]').click() time.sleep(.4) genes_input = self.selenium.find_element_by_id("region-genes") genes_input.send_keys('cdcp2\nmpv17') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("9 variants" in stats_content) def test_region_filter(self): choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') self.selenium.find_element_by_xpath('//a[@href="#collapse-region"]').click() time.sleep(.4) choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') genes_input = self.selenium.find_element_by_id("region-coords") genes_input.send_keys('chr6:31000000-33000000') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("8 variants" in stats_content) def test_region_filter_full_chr(self): choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') self.selenium.find_element_by_xpath('//a[@href="#collapse-region"]').click() time.sleep(.4) choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') genes_input = self.selenium.find_element_by_id("region-coords") genes_input.send_keys('chr6') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("92 variants" in stats_content) def tearDown(self): self.selenium.quit() # class CohortGeneSearchTests(unittest.TestCase): # """ # Test all the different views you can go to on the cohort browse page # """ # def setUp(self): # # #self.selenium = webdriver.Chrome() # self.selenium = WebDriver() # self.live_server_url = 'http://*****:*****@type="submit"]').click() # # # visit the cohort browse page # self.selenium.get(self.live_server_url + '/project/g1k/cohort/random_cohort/cohort-gene-search') # # def test_recessive_basic(self): # self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="recessive"]').click() # choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') # choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') # # self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() # wait_for_xpath(self.selenium, '//div[@id="summary-container"]') # # results_content = self.selenium.find_element_by_id('resultsContainer').text # self.assertTrue("Returned 60 genes" in results_content) # # def test_homozygous_recessive_basic(self): # # self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="homozygous_recessive"]').click() # choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') # choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') # # self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() # wait_for_xpath(self.selenium, '//div[@id="summary-container"]') # # results_content = self.selenium.find_element_by_id('resultsContainer').text # self.assertTrue("Returned 53 genes" in results_content) # # def test_x_linked_recessive_basic(self): # # self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="x_linked_recessive"]').click() # choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') # choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') # # self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() # wait_for_xpath(self.selenium, '//div[@id="summary-container"]') # # results_content = self.selenium.find_element_by_id('resultsContainer').text # self.assertTrue("Returned 2 genes" in results_content) # # def test_compound_het_basic(self): # # self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="compound_het"]').click() # choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') # choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') # # self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() # wait_for_xpath(self.selenium, '//div[@id="summary-container"]') # # results_content = self.selenium.find_element_by_id('resultsContainer').text # self.assertTrue("Returned 6 genes" in results_content) # # def test_dominant_basic(self): # # self.selenium.find_element_by_xpath('//input[@name="cohort_inheritance"][@value="dominant"]').click() # choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'high_impact') # choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') # # self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() # wait_for_xpath(self.selenium, '//div[@id="summary-container"]') # # results_content = self.selenium.find_element_by_id('resultsContainer').text # self.assertTrue("Returned 6 genes" in results_content) def tearDown(self): self.selenium.quit()
success = True wd = WebDriver() wd.implicitly_wait(60) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("https://rippletrade.com/") wd.find_element_by_link_text("Sign Up").click() wd.find_element_by_id("register_username").click() wd.find_element_by_id("register_username").clear() wd.find_element_by_id("register_username").send_keys("yuiyoxoq") wd.find_element_by_id("register_password").click() wd.find_element_by_id("register_password").clear() wd.find_element_by_id("register_password").send_keys("b1zd3vf0r3v3r") wd.find_element_by_id("register_password2").click() wd.find_element_by_id("register_password2").clear() wd.find_element_by_id("register_password2").send_keys("b1zd3vf0r3v3r") wd.find_element_by_id("register_email").click() wd.find_element_by_id("register_email").clear() wd.find_element_by_id("register_email").send_keys("*****@*****.**") if not wd.find_element_by_id("terms").is_selected(): wd.find_element_by_id("terms").click() wd.find_element_by_xpath("//div[@id='t-register']//button[.='Sign UpMigrate Account']").click() wd.find_element_by_xpath("//div[@id='t-register']/section/div[4]/div[2]/div[5]/button").click()
class UITestCase(LiveServerTestCase): def use_xvfb(self): from pyvirtualdisplay import Display self.display = Display('xvfb', visible=1, size=(1280, 1024)) self.display.start() self.driver = WebDriver() def setUp(self): try: self.driver = WebDriver() ui_is_not_available = False except WebDriverException: ui_is_not_available = True if ui_is_not_available: self.use_xvfb() self.driver.implicitly_wait(10) super(UITestCase, self).setUp() def tearDown(self): self.driver.quit() if hasattr(self, 'display'): self.display.stop() # The super.tearDown sometimes hangs when truncating tables # because of lingering pending transactions with locks on those tables. # Kill them to avoid deadlock! try: dbname = settings.DATABASES['default']['NAME'] sql = "select pg_terminate_backend(procpid)" + \ " from pg_stat_activity where datname='%s'" % dbname + \ " and current_query='<IDLE> in transaction';" connection.cursor().execute(sql) except InterfaceError: # Sometimes we get "connection already closed" pass super(UITestCase, self).tearDown() def click(self, selector): self.find(selector).click() def click_when_visible(self, selector): element = self.find(selector) self.wait_until_visible(element) element.click() def find(self, selector): return self.driver.find_element_by_css_selector(selector) def find_name(self, name): return self.driver.find_element_by_name(name) def find_id(self, id): return self.driver.find_element_by_id(id) def process_login_form(self, username, password): username_elmt = self.find_name('username') password_elmt = self.find_name('password') username_elmt.send_keys(username) password_elmt.send_keys(password) self.click('form * button') def browse_to_url(self, url): self.driver.get(self.live_server_url + url) def find_anchor_by_url(self, url): return self.find("[href='%s']" % url) def wait_until_enabled(self, element, timeout=10): def isPresentAndEnabled(driver): return element.get_attribute("disabled") is None WebDriverWait(self.driver, timeout).until(isPresentAndEnabled) def wait_until_visible(self, element, timeout=10): def isVisible(driver): return element.is_displayed() WebDriverWait(self.driver, timeout).until(isVisible)
class MySeleniumTests(StaticLiveServerTestCase): def setUp(self): super(MySeleniumTests, self).setUp() options = Options() options.headless = True # option for server without display self.selenium = WebDriver(options=options) self.user = User.objects.create_user(username='******', password='******', email='*****@*****.**', is_active=True) self.category = Category.objects.create(name='boissons') self.category.save() self.product = Product.objects.create(id=1, name='coca', nutriscore='c', url='www.coca.com', image_url='www.linktojpg', category=self.category) self.product_alt = Product.objects.create(id=2, name='eau', nutriscore='a', url='www.eau.com', image_url='www.linktojpg', category=self.category) self.user.save(), self.product.save(), self.product_alt.save() def tearDown(self): self.selenium.quit() super(MySeleniumTests, self).tearDown() def test_login(self, username="******", password="******"): self.selenium.get('%s%s' % (self.live_server_url, "/accounts/login/")) self.selenium.find_element_by_id('logo').is_displayed() self.selenium.find_element_by_name("username").send_keys(username) self.selenium.find_element_by_name("password").send_keys(password) self.selenium.find_element_by_id("button_login").click() self.selenium.implicitly_wait(1) self.selenium.find_element_by_id("colette").is_displayed() self.selenium.implicitly_wait(1) # seconds self.selenium.find_element_by_id( "logout").is_displayed() # check if logout img is displayed def test_search(self): self.selenium.get('%s%s' % (self.live_server_url, "/")) self.selenium.find_element_by_id('logo').is_displayed() my_search = self.selenium.find_element_by_name("query") my_search.send_keys("eau") my_search.send_keys(Keys.RETURN) self.selenium.implicitly_wait(1) # seconds self.selenium.find_element_by_id('product_pick').is_displayed() def test_redirection_login_to_saved_product(self): self.selenium.get('%s%s' % (self.live_server_url, "/")) self.selenium.find_element_by_id('logo').is_displayed() my_search = self.selenium.find_element_by_name("query") my_search.send_keys("coca") my_search.send_keys(Keys.RETURN) self.selenium.implicitly_wait(1) # seconds self.selenium.find_element_by_name("button_id_2").click() def test_search_with_empty_query(self): self.selenium.get('%s%s' % (self.live_server_url, "/")) self.selenium.find_element_by_id('logo').is_displayed() my_search = self.selenium.find_element_by_name("query") my_search.send_keys("") my_search.send_keys(Keys.RETURN) self.selenium.implicitly_wait(1) # seconds element_to_check = self.selenium.find_element_by_id( "message_to_display") message = element_to_check.text assert "Votre saisie est vide !" in message def test_search_with_nonsense_query(self): self.selenium.get('%s%s' % (self.live_server_url, "/")) self.selenium.find_element_by_id('logo').is_displayed() my_search = self.selenium.find_element_by_name("query") my_search.send_keys("blablabla") my_search.send_keys(Keys.RETURN) self.selenium.implicitly_wait(1) # seconds element_to_check = self.selenium.find_element_by_id( "message_to_display") message = element_to_check.text assert "Votre produit n'existe pas dans notre base de donnée !" in message
class ExampleCommunityLiveTests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(ExampleCommunityLiveTests, cls).setUpClass() @classmethod def tearDownClass(cls): # cls.selenium.quit() super(ExampleCommunityLiveTests, cls).tearDownClass() def tearDown(self): self.selenium.get(self.full_url(reverse('logout'))) self.selenium.quit() def setUp(self): self.community = Community.objects.create( name="Kibbutz Broken Dream", ) self.users_details = dict() for i in range(NUM_OF_USERS): name = silly.name(slugify=True) email = silly.email() self.users_details[name] = OCUser.objects.create_superuser(email, name, DEFAULT_PASS) self.committee = Committee.objects.create(name="Culture", slug="culture", community=self.community) self.selenium = WebDriver() def full_url(self, s): if s.startswith(self.live_server_url): return s else: return self.live_server_url + s def get_current_path(self): return urlparse.urlsplit(self.selenium.current_url).path def assert_current_path(self, path): self.assertEqual(self.full_url(path), self.full_url(self.get_current_path())) def selenium_get_and_assert(self, url): """ Tries to go url (as is) and then asserts that current_path == url """ self.selenium.get(url) self.assert_current_path(url) def login(self, goto_login, name, pswd=DEFAULT_PASS): if goto_login is True: self.selenium.get(self.full_url(reverse('login'))) self.assert_current_path(reverse('login')) username_input = self.selenium.find_element_by_id("id_username") username_input.send_keys(self.users_details[name].email) password_input = self.selenium.find_element_by_id("id_password") password_input.send_keys(pswd) self.selenium.find_element_by_xpath('//input[@type="submit"]').click() def test_redirect_and_login(self): url = self.full_url(self.community.get_absolute_url()) # from IPython import embed # embed() self.selenium.get(url) name = random.choice(self.users_details.keys()) self.login(False, name) # False since the community we created is private - it should automatically redircet to login def test_create_meeting(self): name = random.choice(self.users_details.keys()) self.login(True, name) """ TODO - after login goto the community page, locate the relevant html element for the committee - and 'click()' it (The below code didn't work because click didn't work for me - idk y url = self.full_url(self.community.get_absolute_url()) self.selenium_get_and_assert(url) self.selenium.find_element_by_class_name( "panel-heading").click() # goto "Next meeting" (TODO: check if this works if we have single \ multiple meetings in the system) self.assert_current_path( self.committee.get_absolute_url()) # note: we're seeing a new meeting in progress - hence its' url is the committees' """ url = self.full_url(self.committee.get_absolute_url()) self.selenium_get_and_assert(url) # TODO: assert that we're seeing all the communities we're a member of new_subject_input = self.selenium.find_element_by_id("quick-issue-title") new_subject_input.send_keys("dummy-subject1") self.selenium.find_element_by_xpath( '//button[@type="submit"]').click() # should behave exactly like: self.selenium.find_element_by_id("quick-issue-add").click() # Create a new committee & assert what's needed
class UITestCase(StaticLiveServerTestCase): def use_xvfb(self): from pyvirtualdisplay import Display self.display = Display('xvfb', visible=1, size=(DISPLAY_WIDTH, DISPLAY_HEIGHT)) self.display.start() self.driver = WebDriver() def setUp(self): try: self.driver = WebDriver() ui_is_not_available = False except WebDriverException: ui_is_not_available = True if ui_is_not_available: self.use_xvfb() self.driver.set_window_size(DISPLAY_WIDTH, DISPLAY_HEIGHT) self.driver.implicitly_wait(10) clear_caches() setup_for_ui_test() super(UITestCase, self).setUp() def tearDown(self): self.driver.quit() if hasattr(self, 'display'): self.display.stop() ContentType.objects.clear_cache() super(UITestCase, self).tearDown() def click(self, selector): self.find(selector).click() def click_when_visible(self, selector): element = self.find(selector) self.wait_until_visible(element) element.click() def find(self, selector): return self.driver.find_element_by_css_selector(selector) def find_name(self, name): return self.driver.find_element_by_name(name) def find_id(self, id): return self.driver.find_element_by_id(id) def is_visible(self, selector): element = self.find(selector) return element is not None and element.is_displayed() def process_login_form(self, username, password): username_elmt = self.wait_until_present('[name="username"]') password_elmt = self.find_name('password') username_elmt.send_keys(username) password_elmt.send_keys(password) self.click('form * button') def browse_to_url(self, url): self.driver.get(self.live_server_url + url) def browse_to_instance_url(self, url, instance=None): instance = instance if instance is not None else self.instance self.driver.get('%s/%s/%s' % (self.live_server_url, instance.url_name, url)) def find_anchor_by_url(self, url): return self.find("[href='%s']" % url) def wait_until_present(self, selector, timeout=10): """ Wait until an element with CSS 'selector' exists on the page. Useful for detecting that an operation loads the page you're expecting. """ element = [None] # use list so it can be set by inner scope def is_present(driver): element[0] = self.find(selector) return element[0] is not None and element[0].is_displayed() WebDriverWait(self.driver, timeout).until(is_present) return element[0] def wait_until_text_present(self, text, timeout=10): """ Wait until 'text' exists on the page. Useful for detecting that an operation loads the page you're expecting. """ WebDriverWait(self.driver, timeout).until( lambda driver: text in driver.page_source) def wait_until_enabled(self, element_or_selector, timeout=10): """ Wait until 'element_or_selector' is enabled. """ element = self._get_element(element_or_selector) WebDriverWait(self.driver, timeout).until( lambda driver: element.get_attribute("disabled") is None) return element def wait_until_visible(self, element_or_selector, timeout=10): """ Wait until 'element_or_selector' (known to already exist on the page) is displayed. """ element = self._get_element(element_or_selector) WebDriverWait(self.driver, timeout).until( lambda driver: element.is_displayed()) return element def wait_until_invisible(self, element_or_selector, timeout=10): """ Wait until 'element_or_selector' (known to already exist on the page) is not displayed. """ element = self._get_element(element_or_selector) def is_invisible(driver): try: return not element.is_displayed() except StaleElementReferenceException: return True WebDriverWait(self.driver, timeout).until(is_invisible) return element def wait_for_input_value(self, element_or_selector, value, timeout=10): """ Wait until 'element_or_selector' input has the specified value """ element = self._get_element(element_or_selector) WebDriverWait(self.driver, timeout).until( # It seems wrong, but selenium fetches the value of an input # element using get_attribute('value') lambda driver: element.get_attribute('value') == value) return element def _get_element(self, element_or_selector): if isinstance(element_or_selector, basestring): return self.find(element_or_selector) else: return element_or_selector
class WStoreSeleniumTestCase(TestCase, LiveServerTestCase): fixtures = ['selenium_basic.json'] @classmethod def setUpClass(cls): super(WStoreSeleniumTestCase, cls).setUpClass() def setUp(self): # Open the page self.driver = WebDriver() self.driver.implicitly_wait(5) self.driver.set_window_size(1024, 768) self.driver.get(self.live_server_url) TestCase.setUp(self) def _check_container(self, container, offering_names): # Check offerings container container = self.driver.find_element_by_class_name(container) offering_elems = container.find_elements_by_class_name('menu-offering') self.assertEquals(len(offering_elems), len(offering_names)) for off_elem in offering_elems: title = off_elem.find_element_by_css_selector('h2') self.assertTrue(title.text in offering_names) def login(self, username='******'): # Set username username_elem = self.driver.find_element_by_name('username') username_elem.send_keys(username) # Set password password_elem = self.driver.find_element_by_name('password') password_elem.send_keys('admin') # Click login self.driver.find_element_by_css_selector('#login-form button').click() def oauth2_login(self, username='******'): from wstore.selenium_tests.tests import TESTING_PORT self.driver.get(self.live_server_url + '/oauth2/auth?response_type=code&client_id=test_app&redirect_uri=http://localhost:' + unicode(TESTING_PORT)) self.login(username) self.driver.find_element_by_class_name('btn-blue').click() time.sleep(1) # Get authorization code while self._server.call_received() < 1: pass code = self._server.get_path().split('=')[1] # Get access token opener = urllib2.build_opener() url = self.live_server_url + '/oauth2/token' data = 'client_id=test_app' data += '&client_secret=secret' data += '&grant_type=authorization_code' data += '&code=' + code data += '&redirect_uri=' + 'http://localhost:' + unicode(TESTING_PORT) headers = { 'content-type': 'application/form-url-encoded', } request = MethodRequest('POST', url, data, headers) response = opener.open(request) token = json.loads(response.read())['access_token'] return token def logout(self): self.driver.find_element_by_class_name('arrow-down-settings').click() options = self.driver.find_elements_by_css_selector('#settings-menu > li') options[-1].click() def tearDown(self): self.driver.quit() TestCase.tearDown(self) def back(self): self.driver.find_element_by_id('back').click() def view_all(self): self.driver.find_element_by_css_selector('#all').click() def search_keyword(self, keyword, id_='#text-search', btn='#search'): # Set search field search_elem = self.driver.find_element_by_css_selector(id_) search_elem.send_keys(keyword) # Click search button self.driver.find_element_by_css_selector(btn).click() def open_offering_details(self, offering_name): elements = self.driver.find_elements_by_class_name('menu-offering') for element in elements: if element.find_element_by_css_selector('h2').text == offering_name: element.click() break def _get_navs(self): submenu = self.driver.find_element_by_class_name('store-sub-menu') # Get first element return submenu.find_elements_by_css_selector('li') def click_first_cat(self): self.driver.find_element_by_id('menu-first-text').click() def click_second_cat(self): self.driver.find_element_by_id('menu-second-text').click() def click_third_cat(self): self.driver.find_element_by_id('menu-third-text').click() def click_first_nav(self): self._get_navs()[0].click() def click_second_nav(self): self._get_navs()[1].click() def _open_provider_option(self, option): self.driver.find_element_by_css_selector('#provider-options a.btn').click() self.driver.find_element_by_id(option).click() def create_offering_menu(self): self._open_provider_option('create-app') def fill_basic_offering_info(self, offering_info): # Name and version self.driver.find_element_by_css_selector('[name="app-name"]').send_keys(offering_info['name']) self.driver.find_element_by_css_selector('[name="app-version"]').send_keys(offering_info['version']) # Select the notification URL option if not offering_info['notification']: self.driver.find_element_by_css_selector('input[type="radio"][value="none"]').click() elif offering_info['notification'] == 'default': self.driver.find_element_by_css_selector('input[type="radio"][value="default"]').click() else: self.driver.find_element_by_css_selector('input[type="radio"][value="new"]').click() self.driver.find_element_by_id('notify').send_keys(offering_info['notification']) # Add the logo logo_path = os.path.join(settings.BASEDIR, 'wstore/ui/fiware/defaulttheme/static/assets/img/noimage.png') self.driver.find_element_by_id('img-logo').send_keys(logo_path) # Mark as open if needed if offering_info['open']: self.driver.find_element_by_id('open-offering').click() def _fill_usdl_form(self, usdl_info): # Fill description field self.driver.find_element_by_id('description').send_keys(usdl_info['description']) # Fill pricing info if needed if 'price' in usdl_info: self.driver.find_element_by_css_selector('#pricing-select option[value="single_payment"]').click() self.driver.find_element_by_id('price-input').send_keys(usdl_info['price']) if 'legal' in usdl_info: self.driver.find_element_by_id('legal-title').send_keys(usdl_info['legal']['title']) self.driver.find_element_by_id('legal-text').send_keys(usdl_info['legal']['text']) def _fill_usdl_upload(self, usdl_info): pass def _fill_usdl_url(self, usdl_info): pass def fill_usdl_info(self, usdl_info): # Select the correct method methods = { 'form': self._fill_usdl_form, 'upload': self._fill_usdl_upload, 'url': self._fill_usdl_url } methods[usdl_info['type']](usdl_info) def register_resource(self, resource_info): pass def click_tag(self, tag): tag_elems = self.driver.find_elements_by_class_name('tag') for te in tag_elems: if te.text == tag: te.click() break def fill_tax_address(self, tax): self.driver.find_element_by_id('street').send_keys(tax['street']) self.driver.find_element_by_id('postal').send_keys(tax['postal']) self.driver.find_element_by_id('city').send_keys(tax['city']) self.driver.find_element_by_id('country').send_keys(tax['country'])
class UITestCase(LiveServerTestCase): def use_xvfb(self): from pyvirtualdisplay import Display self.display = Display('xvfb', visible=1, size=(1280, 1024)) self.display.start() self.driver = WebDriver() def setUp(self): try: self.driver = WebDriver() ui_is_not_available = False except WebDriverException: ui_is_not_available = True if ui_is_not_available: self.use_xvfb() self.driver.implicitly_wait(10) super(UITestCase, self).setUp() def tearDown(self): self.driver.quit() if hasattr(self, 'display'): self.display.stop() super(UITestCase, self).tearDown() def click(self, selector): self.find(selector).click() def find(self, selector): return self.driver.find_element_by_css_selector(selector) def find_name(self, name): return self.driver.find_element_by_name(name) def find_id(self, id): return self.driver.find_element_by_id(id) def process_login_form(self, username, password): username_elmt = self.find_name('username') password_elmt = self.find_name('password') username_elmt.send_keys(username) password_elmt.send_keys(password) self.click('form * button') def browse_to_url(self, url): self.driver.get(self.live_server_url + url) def find_anchor_by_url(self, url): return self.find("[href='%s']" % url) def wait_until_enabled(self, element, timeout=10): def isPresentAndEnabled(driver): return element.get_attribute("disabled") is None WebDriverWait(self.driver, timeout).until(isPresentAndEnabled) def wait_until_visible(self, element, timeout=10): def isPresentAndEnabled(driver): return element.is_displayed() WebDriverWait(self.driver, timeout).until(isPresentAndEnabled)
try: driver.set_window_size(1900, 1000) driver.get("https://shop.briggsandstratton.com/us/en") driver.find_element_by_link_text("Shop Repair Parts Now »").click() # This try statement is used to detect the Foresee overlay that pops up at this point in FF # Without this, Chrome will not continue to next step as it will error out while waiting try: wait = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.LINK_TEXT, "No, thanks"))) driver.find_element_by_link_text("No, thanks").click() except Exception, e: print("Foresee not seen here") WebDriverWait(driver, 10).until_not(EC.presence_of_element_located((By.ID, "fsrOverlay"))) driver.find_element_by_id("aarisearch_brands_jl").click() wait = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//ul[@class='ari-caused-spacer-expand']/li[3]"))) driver.find_element_by_xpath("//ul[@class='ari-caused-spacer-expand']/li[3]").click() driver.find_element_by_id("arisearch_txtSearch").click() driver.find_element_by_id("arisearch_txtSearch").clear() driver.find_element_by_id("arisearch_txtSearch").send_keys("209617GS") driver.find_element_by_id("arisearch_btnLookup").click() # The following div classes get in the way of our user click as seen in errors # and we must change the css with javascript to allow the button click without a sleep statement # <div class="blockUI blockOverlay" ... wait; position: absolute;"></div> try: hideElement = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "blockUI"))) except Exception, e:
class UIRespondentTests(StaticLiveServerTestCase): """ Tests for the UI presented to the survey respondents. These include page rendering, response submission, and the CSRF protection of the page""" def setUp(self): """ Set up for the UI/respondent test case """ super(UIRespondentTests, self).setUp() self.web_driver = WebDriver() # Create a new survey, add some questions, and publish user = User.objects.create(username='******') survey = user.surveys.create(name='foobar') questions = ['what?', 'where?', 'why?', 'when?', 'anything else?'] for question in questions: survey.questions.create(question_text=question) survey.publish() self.survey = survey # Load up the response page url = '%s%s%s/' % (self.live_server_url, '/respond/', survey.id) self.web_driver.get(url) # No way of checking directly for 404 in selenium; just make sure the # survey name is in the source self.assertIn('foobar', self.web_driver.page_source) def tearDown(self): """ Clean up for the UI/respondent test case """ self.web_driver.quit() super(UIRespondentTests, self).tearDown() User.objects.all().delete() def test_response_page_rendering(self): """ The response page for a a survey contains the correct questions, in order """ try: form = self.web_driver.find_element_by_name('survey-respond-%s' % self.survey.id) except NoSuchElementException: self.fail('The form did not render with the expected element name') # For every question in the DB, make sure the page contains an element # for each, with the name as the question's ordinance and the id as # the question's pk. for question_ix, question in enumerate(self.survey.questions.all()): try: e1 = self.web_driver.find_element_by_name(str(question_ix)) except NoSuchElementException: self.fail('Question index %s was not rendered in response page' % question_ix) try: e2 = self.web_driver.find_element_by_id(str(question.pk)) except NoSuchElementException: self.fail('Question pk %s was not rendered in response page' % question.pk) if e1 != e2: self.fail('Expected HTML element for question pk %s and id %s ' 'to match' % (question.pk, question_ix)) def test_response_submission(self): """ A submission of a valid form creates the expected `Response` and `Answer` entries in the database """ questions = self.survey.questions.all() for question_ix, question in enumerate(questions): ans_input = self.web_driver.find_element_by_name(str(question_ix)) ans_input.send_keys('Answer to "%s"' % question.question_text) submit_button = self.web_driver.find_element_by_name('submit-response') submit_button.click() answers = self.survey.responses.get().answers.all() self.assertEqual(len(answers), len(questions)) for question, answer in zip(questions, answers): self.assertEqual(answer.answer_text, 'Answer to "%s"' % question.question_text) def test_csrf_protection(self): """ The form has a CSRF token and POST requests made outside of the form are rejected """ # Make sure the CSRF token exists try: self.web_driver.find_element_by_name('csrfmiddlewaretoken') except NoSuchElementException: self.fail('No CSRF token in response form') # Check that a 403 is returned when trying to submit a response not via # the form response = requests.post('%s%s%s/' % (self.live_server_url, '/respond/', self.survey.id)) self.assertEqual(response.status_code, 403)
class FamilyBrowseTests(unittest.TestCase): """ Test all the different views you can go to on the family test page """ def setUp(self): self.selenium = WebDriver() self.live_server_url = LIVE_SERVER_URL # login boilerplate blah self.selenium.get(self.live_server_url + '/login') username_input = self.selenium.find_element_by_name("username_or_email") username_input.send_keys(ADMIN_USERNAME) password_input = self.selenium.find_element_by_name("password") password_input.send_keys(ADMIN_PASSWORD) self.selenium.find_element_by_xpath('//button[@type="submit"]').click() # visit the family browse page self.selenium.get(self.live_server_url + '/project/1kg/family/1/mendelian-variant-search') def test_recessive_basic(self): self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="recessive"]').click() choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("7 variants" in stats_content) def test_homozygous_recessive_basic(self): self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="homozygous_recessive"]').click() choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("1 variants" in stats_content) def test_x_linked_recessive_basic(self): self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="x_linked_recessive"]').click() choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("No variants" in stats_content) def test_compound_het_basic(self): self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="compound_het"]').click() choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("6 variants" in stats_content) def test_dominant_basic(self): self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="dominant"]').click() choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("21 variants" in stats_content) def test_de_novo_basic(self): self.selenium.find_element_by_xpath('//input[@name="standard_inheritance"][@value="de_novo"]').click() choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("6 variants" in stats_content) def test_custom_inheritance(self): self.selenium.find_element_by_xpath('//li[@class="inheritance-pill-li"][@data-search_mode="custom_inheritance"]/a').click() time.sleep(.5) choose_select(self.selenium, '//select[@class="col-md-2 select-genotype form-control"][@data-indiv_id="NA19675"]', 'alt_alt') choose_select(self.selenium, '//select[@id="variant-presets-select"]', 'moderate_impact') choose_select(self.selenium, '//select[@id="quality-defaults-select"]', 'high_quality') self.selenium.find_element_by_xpath('//a[@id="run-search"]').click() wait_for_xpath(self.selenium, '//div[@id="summary-container"]') stats_content = self.selenium.find_element_by_id('variant-stats-container').text self.assertTrue("21 variants" in stats_content) def tearDown(self): self.selenium.quit()
def send_offer(cipher, job_reference, client, buyer_reference, worker_reference): driver = WebDriver() driver.implicitly_wait(time_to_wait=10) # Login selenium_login(webdriver=driver) # Worker's page driver.get('https:/www.odesk.com/users/%s' % cipher) driver.find_element_by_link_text("Contact").click() # Make an offer link driver.find_element_by_id("jsMakeOfferLink").click() el = driver.find_element_by_css_selector("#jsTeamSelector > select") el.find_element_by_css_selector("option[value=\"%s\"]" % buyer_reference).\ click() driver.find_element_by_id("jsMakeOfferProceed").click() # Sign in to make an offer driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(settings.ODESK_TEST_ACC_PASS) try: driver.find_element_by_id("answer").clear() driver.find_element_by_id("answer").send_keys(settings.ODESK_TEST_ACC_ANSWER) except selenium.exceptions.NoSuchElementException: pass driver.find_element_by_id("submitButton").click() # Make an offer form driver.find_element_by_id("useExistingJob-yes").click() el = driver.find_element_by_id("jobPosting") el.find_element_by_css_selector("option[value=\"%s\"]" % job_reference).\ click() driver.find_element_by_id("employerRate").clear() driver.find_element_by_id("employerRate").send_keys("0.01") driver.find_element_by_id("setLimit-yes").click() driver.find_element_by_id("limit").clear() driver.find_element_by_id("limit").send_keys("0") driver.find_element_by_id("submitButton").click() # Agreement driver.find_element_by_id("agreement").click() driver.find_element_by_id("submitButton").click() driver.close()
class ProfessorTest(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(1) create_user_and_login(self.browser, self.live_server_url,'john','johnpassword','*****@*****.**') self.name_professor = 'teste' def tearDown(self): [professor.delete() for professor in Professor.find()] self.browser.quit() def create_professor(self,professor_name): open_page(self.browser, '/interface/professor', self.live_server_url) button_create_professor = self.browser.find_element_by_name('criar') button_create_professor.click() self.assertIn('Interface - Professor Create', self.browser.title) form_name = self.browser.find_element_by_id('id_name') form_name.send_keys(professor_name) form_memberId = self.browser.find_element_by_id('id_memberId') form_memberId.send_keys('00000') form_office = self.browser.find_element_by_id('id_office') form_office.send_keys('0') form_email = self.browser.find_element_by_id('id_email') form_email.send_keys('0') form_phoneNumber = self.browser.find_element_by_id('id_phoneNumber') form_phoneNumber.send_keys('0') form_cellphoneNumber = self.browser.find_element_by_id('id_cellphoneNumber') form_cellphoneNumber.send_keys('0') form_idDepartment = self.browser.find_element_by_id('id_idDepartment') form_idDepartment.send_keys('') button_submit = self.browser.find_element_by_name('Cadastrar') button_submit.click() def test_login_to_interface_page(self): self.assertIn('Index', self.browser.title) link_interface = self.browser.find_element_by_link_text('Interface') link_interface.click() self.assertIn('Interface', self.browser.title) def test_login_to_professor_page(self): open_page(self.browser, '/interface/', self.live_server_url) professor_interface = self.browser.find_element_by_link_text('Professor') professor_interface.click() self.assertIn('Interface - Professor', self.browser.title) def test_create_professor(self): self.create_professor(self.name_professor) open_page(self.browser, '/interface/professor', self.live_server_url) professor_name_link = self.browser.find_element_by_link_text(self.name_professor) self.assertIsNotNone(professor_name_link) def test_edit_professor(self): professor = Professor(self.name_professor) professor.store() open_page(self.browser, '/interface/professor', self.live_server_url) professor_name_link = self.browser.find_element_by_link_text(self.name_professor) professor_name_link.click() self.assertIn('Interface - Professor Detail', self.browser.title) button_edit = self.browser.find_element_by_name('editar') button_edit.click() self.assertIn('Interface - Professor Edit', self.browser.title) form_name = self.browser.find_element_by_id('id_name') form_name.send_keys('Edit') form_memberId = self.browser.find_element_by_id('id_memberId') form_memberId.send_keys('') form_office = self.browser.find_element_by_id('id_office') form_office.send_keys('') form_email = self.browser.find_element_by_id('id_email') form_email.send_keys('') form_phoneNumber = self.browser.find_element_by_id('id_phoneNumber') form_phoneNumber.send_keys('0') form_cellphoneNumber = self.browser.find_element_by_id('id_cellphoneNumber') form_cellphoneNumber.send_keys('0') form_idDepartment = self.browser.find_element_by_id('id_idDepartment') form_idDepartment.send_keys('') button_apply = self.browser.find_element_by_name('Aplicar') button_apply.click() open_page(self.browser, '/interface/professor', self.live_server_url) professor_name_link_after_edit = self.browser.find_element_by_link_text(self.name_professor + 'Edit') professor_name_link_after_edit.click() list_professor_info = self.browser.find_elements_by_tag_name('p') self.assertEqual(list_professor_info[1].text, 'Member ID: 0') self.assertEqual(list_professor_info[2].text, 'Office: None') self.assertEqual(list_professor_info[3].text, 'Email: None') self.assertEqual(list_professor_info[4].text, 'Phone Number: 0') self.assertEqual(list_professor_info[5].text, 'CellPhone Number: 0') self.assertEqual(list_professor_info[6].text, 'Id Department: None') def test_delete_professor(self): professor = Professor(self.name_professor) professor.store() open_page(self.browser, '/interface/professor', self.live_server_url) professor_name_link = self.browser.find_element_by_link_text(self.name_professor) professor_name_link.click() self.assertIn('Interface - Professor Detail', self.browser.title) button_delete = self.browser.find_element_by_name('deletar') button_delete.click() alert = self.browser.switch_to.alert alert.accept() self.assertIn('Interface - Professor', self.browser.title) professor_name_after_delete = self.browser.find_elements_by_tag_name('a') names = [link.text for link in professor_name_after_delete] self.assertNotIn(self.name_professor, names)
from selenium.webdriver.firefox.webdriver import WebDriver wd = WebDriver() wd.implicitly_wait(60) wd.get("https://encrypted.google.com/") wd.find_element_by_id("gbqfq").click() wd.find_element_by_id("gbqfq").clear() wd.find_element_by_id("gbqfq").send_keys("santiago suarez ordoñez") wd.find_element_by_xpath("//ol[@id='rso']//em[.='Santiago Suarez Ordoñez']").click() wd.close()
# -*- coding: utf-8 -*- from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.common.action_chains import ActionChains import time success = True wd = WebDriver() wd.implicitly_wait(60) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("http://localhost/php4dvd/") wd.find_element_by_id("username").click() wd.find_element_by_id("username").clear() wd.find_element_by_id("username").send_keys("admin") wd.find_element_by_name("password").click() wd.find_element_by_name("password").clear() wd.find_element_by_name("password").send_keys("admin") wd.find_element_by_name("submit").click() finally: wd.quit() if not success: raise Exception("Test failed.")
def syn_test_script(): try: success = True driver = WebDriver() driver.implicitly_wait(30) # Disabled page sizing and instead used action chains to move mouse around #driver.set_window_size(1920, 1080) # Use Action chains to navigate page when there is an issue with the selection menus # If the menu item does not appear to select, it means there was a page movement that happened # out of sync with the action. #------Insert Script between these lines-----# driver.get( "http://www.jared.com/en/jaredstore/searchterm/731434000/true/731434000" ) # Search HTML for text to verify page log_output("Step - Verify Search worked") if not ("items" in driver.find_element_by_tag_name("html").text): success = False print("verifyTextPresent failed") log_output("Step - Select item via partial link text") driver.find_element_by_partial_link_text( "Mother's Bracelet Round Birthstones Design in Silver").click() log_output("Start customizing Jewelery") log_output(" Select Number of stones (1)") if not driver.find_element_by_xpath( "//select[@id='configSelect']//option[2]").is_selected(): driver.find_element_by_xpath( "//select[@id='configSelect']//option[2]").click() driver.find_element_by_id("btnStartCustomizing").click() log_output(" Select metal type") if not driver.find_element_by_xpath( "//select[@id='metalTypeSelect']//option[2]").is_selected(): driver.find_element_by_xpath( "//select[@id='metalTypeSelect']//option[2]").click() driver.find_element_by_id("next-step").click() log_output(" Select stone type") if not driver.find_element_by_xpath( "//select[@id='stoneTypeSelect']//option[2]").is_selected(): driver.find_element_by_xpath( "//select[@id='stoneTypeSelect']//option[2]").click() driver.find_element_by_xpath( "//div[@id='tab-stoneType']//a[.='Next']").click() log_output(" Select birthstone") driver.find_element_by_css_selector("span.month_text").click() driver.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[2]").click() driver.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click() driver.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click() driver.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click() if not driver.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input" ).is_selected(): driver.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/input").click( ) driver.find_element_by_link_text("SELECT").click() driver.find_element_by_xpath( "//div[@id='tab-stones']//a[.='Next']").click() driver.find_element_by_id("addToCart").click() driver.find_element_by_link_text("CHECKOUT").click() if not ("Shopping Bag (1 Item)" in driver.find_element_by_tag_name("html").text): success = False print("verifyTextPresent failed") #------Insert Script between these lines-----# finally: driver.quit() if not success: raise Exception("Test failed.")
class SeleniumTestCase(StaticLiveServerTestCase): def create_flights(self): c1 = Crew.objects.create(captain_name="Anna", captain_surname="Kramarska") c2 = Crew.objects.create(captain_name="Bartosz", captain_surname="Wojno") c3 = Crew.objects.create(captain_name="Ola", captain_surname="Grzyb") a1 = Airport.objects.create(name="Warsaw") a2 = Airport.objects.create(name="Modlin") air1 = Airplane.objects.create(licenseChars="ak385833", capacity=100) air2 = Airplane.objects.create(licenseChars="bw386385", capacity=50) Flight.objects.create(startingAirport=a1, landingAirport=a2, startingTime=datetime.now(), landingTime=datetime.now() + timedelta(hours=12), airplane=air1, crew=c1) Flight.objects.create(startingAirport=a2, landingAirport=a1, startingTime=datetime.now(), landingTime=datetime.now() + timedelta(hours=6), airplane=air2, crew=c2) def create_users(self): get_user_model().objects.create_user('temp', '*****@*****.**', 'temporary') get_user_model().objects.create_user('temp2', '*****@*****.**', 'temporary') def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.create_users() self.create_flights() def tearDown(self): self.selenium.quit() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/auth/login/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys('temp') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('temporary') self.selenium.find_element_by_xpath('//button[@type="submit"]').click() self.selenium.find_element_by_class_name("data") def test_add_passenger(self): self.test_login() self.selenium.get('%s%s' % (self.live_server_url, '/flight/1/')) name_input = self.selenium.find_element_by_id('id_name') name_input.send_keys("Anna") surname_input = self.selenium.find_element_by_id('id_surname') surname_input.send_keys("Kramarska") tickets_input = self.selenium.find_element_by_name('nrOfTickets') tickets_input.send_keys(10) self.selenium.find_element_by_id('buy').click() def test_assign_crew(self): self.selenium.get('%s%s' % (self.live_server_url, '/')) self.selenium.find_element_by_id('crews-link').click() # login user_input = self.selenium.find_element_by_id('user') user_input.send_keys('temp') pass_input = self.selenium.find_element_by_id('password') pass_input.send_keys('temporary') self.selenium.find_element_by_id('log').click() self.selenium.find_element_by_xpath('//button[text()="Logout"]') # assigning crew flight = self.selenium.find_element_by_id('flight') flight.send_keys(1) crew = self.selenium.find_element_by_id('crew') crew.send_keys('1') self.selenium.find_element_by_id('assign').click()
class LiveServerTest(object): fixtures = ['rules.json'] DOWNLOAD_DIRECTORY = '/tmp/work/downloads' ## List all ajax enabled pages that have initialization code and must wait AJAX_WAIT = ['mock_galaxy_factory', 'view_job'] SUMMARY_INDEX = str(len(MODULE_INDICES)+1) OUTPUT_FORMATS = [ {'value':'csv', 'text':'CSV (Text)', 'extension':'csv'}, {'value':'hdf5', 'text':'HDF5', 'extension':'hdf5'}, {'value': 'fits', 'text': 'FITS', 'extension': 'fits'}, {'value': 'votable', 'text': 'VOTable', 'extension': 'xml'} ] def wait(self, secs=1): time.sleep(secs * 1.0) def setUp(self): from selenium.webdriver.firefox.webdriver import FirefoxProfile fp = FirefoxProfile() fp.set_preference("browser.download.folderList", 2) fp.set_preference("browser.download.dir", self.DOWNLOAD_DIRECTORY) fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/html, application/zip, text/plain, application/force-download, application/x-tar") self.selenium = WebDriver(firefox_profile=fp) self.selenium.implicitly_wait(1) # wait one second before failing to find # create the download dir if not os.path.exists(self.DOWNLOAD_DIRECTORY): os.makedirs(self.DOWNLOAD_DIRECTORY) def tearDown(self): self.selenium.quit() # remove the download dir for root, dirs, files in os.walk(self.DOWNLOAD_DIRECTORY, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) def lc_id(self, bare_field): return '#id_light_cone-%s' % bare_field def lc_2select(self, bare_field): return 'id_light_cone-output_properties_%s' % bare_field def rf_id(self, bare_field): return '#id_record_filter-%s' % bare_field def sed(self, bare_field): return 'id_sed-%s' % bare_field def mi_id(self, bare_field): return 'id_mock_image-%s' % bare_field def sed_id(self, bare_field): return '#%s' % self.sed(bare_field) def sed_2select(self, bare_field): return 'id_sed-band_pass_filters_%s' % bare_field def job_select(self, bare_field): return 'id-job_%s' % bare_field def job_id(self, bare_field): return '#%s' % self.job_select(bare_field) def get_parent_element(self, element): return self.selenium.execute_script('return arguments[0].parentNode;', element) def get_element_css_classes(self, element): list = [] found = element.get_attribute('class') if found is not None: list = found.split() return list def get_closest_by_class(self, element, css_class): while css_class not in self.get_element_css_classes(element): element = self.get_parent_element(element) return element def get_summary_selector(self, form_name, field_name): return 'div.summary_%s .%s' % (form_name, field_name) def get_summary_field(self, form_name, field_name): summary_selector = self.get_summary_selector(form_name, field_name) return self.selenium.find_element_by_css_selector(summary_selector) def get_summary_field_text(self, form_name, field_name): return self.get_summary_field(form_name, field_name).text def get_info_field(self, section, field): elem = self.selenium.find_element_by_css_selector("div.%(section)s-info .%(field)s" % {'section': section, 'field': field}) return elem.text def find_element_by_css_selector(self, selector): retries = 3 while retries > 0: try: elem = self.selenium.find_element_by_css_selector(selector) return elem except NoSuchElementException: retries -= 1 self.wait(1) # If it hasn't been found by now, try one more time and let the exception through return self.selenium.find_element_by_css_selector(selector) def find_element_by_id(self, elem_id): retries = 3 while retries > 0: try: elem = self.selenium.find_element_by_id(elem_id) return elem except NoSuchElementException: retries -= 1 self.wait(1) # If it hasn't been found by now, try one more time and let the exception through return self.selenium.find_element_by_id(elem_id) def assert_email_body_contains(self, email, text): pattern = re.escape(text) matches = re.search(pattern, email.body) self.assertTrue(matches, "Email does not contain " + text) def get_page_source(self): try: return self.selenium.page_source except: while True: self.wait(0.2) try: self.selenium.switch_to_alert().accept() except: return self.selenium.page_source def assertTrue(self, value, msg): if not value: raise AssertionError(msg) return def assertEqual(self, vala, valb): if vala != valb: msg = 'FAIL: "{0}" != "{1}"'.format(vala, valb) raise AssertionError(msg) return def assert_page_has_content(self, string): page_source = self.get_page_source() pattern = re.escape(string) self.assertTrue((string in page_source) or re.search(pattern, page_source), "page source did not contain %s" % pattern) def assert_page_does_not_contain(self, string): page_source = self.get_page_source() pattern = re.escape(string) self.assertFalse(re.search(pattern, page_source), "page source contained %s" % pattern) def assert_element_text_equals(self, selector, expected_value): text = self.find_visible_element(selector).text.strip() self.assertEqual(expected_value.strip(), text.strip()) def assert_element_value_equals(self, selector, expected_value): text = self.find_visible_element(selector).get_attribute('value') self.assertEqual(expected_value.strip(), text.strip()) def assert_selector_texts_equals_expected_values(self, selector_value): # selector_value is a dict of selectors to expected text values for selector, expected_value in selector_value.items(): self.assert_element_text_equals(selector, unicode(expected_value)) def assert_attribute_equals(self, attribute, selector_values): # selector_values is a dict of selectors to attribute values for selector, expected_value in selector_values.items(): element = self.find_visible_element(selector) actual_value = element.get_attribute(attribute) self.assertEqual(expected_value, actual_value) def assert_is_checked(self, selector): field = self.selenium.find_element_by_css_selector(selector) self.assertEqual('true', field.get_attribute('checked')) def assert_is_unchecked(self, selector): field = self.selenium.find_element_by_css_selector(selector) self.assertIsNone(field.get_attribute('checked')) def assert_is_enabled(self, selector): field = self.selenium.find_element_by_css_selector(selector) self.assertIsNone(field.get_attribute('disabled')) def assert_is_disabled(self, selector): field = self.selenium.find_element_by_css_selector(selector) self.assertEqual('true', field.get_attribute('disabled')) def assert_are_displayed(self, name): fields = self.selenium.find_elements_by_name(name) self.assertTrue([field.is_displayed() for field in fields]) def assert_are_displayed_by_class_name(self, name): fields = self.selenium.find_elements_by_class_name(name) self.assertTrue([field.is_displayed() for field in fields]) def assert_are_not_displayed(self, name): fields = self.selenium.find_elements_by_name(name) self.assertFalse(all([field.is_displayed() for field in fields])) def assert_is_displayed(self, selector): field = self.selenium.find_element_by_css_selector(selector) self.assertTrue(field.is_displayed()) def assert_not_displayed(self, selector): field = self.selenium.find_element_by_css_selector(selector) self.assertFalse(field.is_displayed()) def assert_not_in_page(self, selector): "Assert that the supplied selector is not part of the page content" elements = self.selenium.find_elements_by_css_selector(selector) self.assertTrue(len(elements) == 0) def assert_on_page(self, url_name, ignore_query_string=False): retries = 30 while retries > 0: try: self._assert_on_page(url_name, ignore_query_string) return except AssertionError: retries -= 1 print "assert_on_page: retry" self.wait(1) self._assert_on_page(url_name, ignore_query_string) def _assert_on_page(self, url_name, ignore_query_string=False): if not ignore_query_string: self.assertEqual(self.selenium.current_url, self.get_full_url(url_name)) else: split_url = self.selenium.current_url.split('?') url = split_url[0] self.assertEqual(url, self.get_full_url(url_name)) def assert_multi_selected_text_equals(self, id_of_select, expected): actual = self.get_multi_selected_option_text(id_of_select) remaining = [] for value in expected: if value not in actual: remaining.append(value) else: actual.remove(value) self.assertTrue(not actual and not remaining) def assert_summary_field_correctly_shown(self, expected_value, form_name, field_name): value_displayed = self.get_summary_field_text(form_name, field_name) self.assertEqual(expected_value, strip_tags(value_displayed)) def fill_in_fields(self, field_data, id_wrap=None, clear=False): for selector, text_to_input in field_data.items(): if id_wrap: selector = id_wrap(selector) elem = self.selenium.find_element_by_css_selector(selector) if elem.tag_name == 'select': self.select(selector, str(text_to_input)) else: if clear: elem.clear() elem.send_keys(str(text_to_input)) self.wait(0.5) def clear(self, selector): elem = self.selenium.find_element_by_css_selector(selector) elem.clear() def click(self, elem_id): elem = self.find_element_by_id(elem_id) elem.click() self.wait(0.5) def click_by_css(self, element_css): elem = self.selenium.find_element_by_css_selector(element_css) elem.click() self.wait(0.5) def click_by_class_name(self, class_name): elem = self.selenium.find_element_by_class_name(class_name) elem.click() self.wait(0.5) def login(self, username, password): self.visit('accounts/login') username_input = self.selenium.find_element_by_id('id_username') password_input = self.selenium.find_element_by_id('id_password') submit_button = self.selenium.find_element_by_tag_name('button') # TODO make this more specific username_input.send_keys(username) password_input.send_keys(password) submit_button.submit() def visit(self, url_name, *args, **kwargs): """ self.visit(name_of_url_as_defined_in_your_urlconf) """ self.selenium.get(self.get_full_url(url_name, *args, **kwargs)) if url_name in LiveServerTest.AJAX_WAIT: self.wait(2) self.assertTrue(self.selenium.execute_script('return (window.catalogue !== undefined ? catalogue._loaded : true)'), 'catalogue.js loading error') def get_actual_filter_options(self): option_selector = '%s option' % self.rf_id('filter') return [x.get_attribute('value').encode('ascii') for x in self.selenium.find_elements_by_css_selector(option_selector)] def get_expected_filter_options(self, data_set): def gen_bp_pairs(objs): for obj in objs: yield ('B-' + str(obj.id) + '_apparent') yield ('B-' + str(obj.id) + '_absolute') normal_parameters = datasets.filter_choices(data_set.simulation.id, data_set.galaxy_model.id) bandpass_parameters = datasets.band_pass_filters_objects() return ['D-' + str(x.id) for x in normal_parameters] + [pair for pair in gen_bp_pairs(bandpass_parameters)] def get_actual_snapshot_options(self): option_selector = '%s option' % self.lc_id('snapshot') return [x.get_attribute("innerHTML") for x in self.selenium.find_elements_by_css_selector(option_selector)] def get_expected_snapshot_options(self, snapshots): return [str("%.5g" % snapshot.redshift) for snapshot in snapshots] def get_full_url(self, url_name, *args, **kwargs): return "%s%s" % (self.job_params.BASE_URL, url_name) def get_selected_option_text(self, id_of_select): select = self.selenium.find_element_by_css_selector(id_of_select) options = select.find_elements_by_css_selector('option') selected_option = None for option in options: if option.get_attribute('selected'): selected_option = option return selected_option.text def get_multi_selected_option_text(self, id_of_select): select = self.selenium.find_element_by_css_selector(id_of_select) options = select.find_elements_by_css_selector('option') return [option.text for option in options] def get_selector_value(self, selector): return self.selenium.find_element_by_css_selector(selector).get_attribute('value') def select(self, selector, value): from selenium.webdriver.support.ui import Select elem = self.selenium.find_element_by_css_selector(selector) select = Select(elem) select.select_by_visible_text(value) def find_visible_elements(self, css_selector): elements = self.selenium.find_elements_by_css_selector(css_selector) return [elem for elem in elements if elem.is_displayed()] def find_visible_element(self, css_selector): elements = self.find_visible_elements(css_selector) num_elements = len(elements) if num_elements != 1: raise Exception("Found %s elements for selector %s" % (num_elements, css_selector)) return elements[0] def select_dark_matter_simulation(self, simulation): self.select(self.lc_id('dark_matter_simulation'), simulation.name) self.wait(0.5) def select_galaxy_model(self, galaxy_model): self.select(self.lc_id('galaxy_model'), galaxy_model.name) self.wait(0.5) def select_stellar_model(self, stellar_model): self.select(self.sed_id('single_stellar_population_model'), stellar_model.label) self.wait(0.5) def select_record_filter(self, filter, extension=None): text = '' if isinstance(filter, DataSetProperty): units_str = '' if filter.units is not None and len(filter.units) > 0: units_str = ' (' + filter.units + ')' text = filter.label + units_str elif isinstance(filter, BandPassFilter): text = filter.label if extension is not None: text += ' (' + extension.capitalize() + ')' else: raise TypeError("Unknown filter type") self.select(self.rf_id('filter'), text) #a function to make a list of list of text inside the table def table_as_text_rows(self, selector): table = self.selenium.find_element_by_css_selector(selector) rows = table.find_elements_by_css_selector('tr') cells = [[cell.text for cell in row.find_elements_by_css_selector('th, td')] for row in rows] return cells def submit_support_form(self): submit_button = self.selenium.find_element_by_css_selector('button[type="submit"]') submit_button.submit()
class EntrySeleleniumTests(StaticLiveServerTestCase): """Selenium tests for the entry form""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not settings.DEBUG: settings.DEBUG = True def setUp(self): """Handles login and things""" call_command('flush', interactive=False, verbosity=0) # Clears db call_command('loaddata', 'groups', commit=False, verbosity=0) call_command('loaddata', 'school', commit=False, verbosity=0) call_command('loaddata', 'permissions', commit=False, verbosity=0) call_command('loaddata', 'auth_users', commit=False, verbosity=0) call_command('loaddata', 'student', commit=False, verbosity=0) call_command('loaddata', 'advisor', commit=False, verbosity=0) call_command('loaddata', 'coordinator', commit=False, verbosity=0) call_command('loaddata', 'activityoptions', commit=False, verbosity=0) call_command('loaddata', 'learningobjectiveoptions', commit=False, verbosity=0) call_command('loaddata', 'sample_entries', commit=False, verbosity=0) self.selenium = WebDriver() self.selenium.set_window_size(1024, 800) self.selenium.get('{0}/{1}'.format(self.live_server_url, '')) self.selenium.find_element_by_xpath('//*[@id="djHideToolBarButton"]').click() self.selenium.implicitly_wait(10) self.selenium.find_element_by_link_text('Login').click() # Click on the student button in the gateway self.selenium.find_element_by_xpath('/html/body/center/md-content/div/div/div[1]/a').click() self.selenium\ .find_element_by_xpath("//img[@src='/static/journal/activities/img" "/journal_sign.png']") super() def tearDown(self): self.selenium.quit() super() def test_text_entry(self): """Test to ensure that a student can add a text entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(entry in box_text) def test_image_entry(self): """Test to ensure that a student can add an image entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(entry) # click on the inset image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists on the page. self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") def test_video_entry(self): """Test to ensure that a student can add a video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert video self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(entry) # click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_image_text_entry(self): """Test to ensure that a student can add image+text entries""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time with a flower.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Insert the image self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the insert image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.implicitly_wait(10) self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure the text is on the entries page box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(entry in box_text) # Ensure the image is on the entries page self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") def test_video_text_entry(self): """Test to ensure that a student can add an text+video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath( '/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(entry) # Insert video self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button')\ .click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div')\ .text self.assertTrue(entry in box_text) self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_text_image_video_entry(self): """Test to ensure that a student can add an text+image+video entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text text_entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(text_entry) # Insert image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the inset image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(text_entry in box_text) self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') def test_delete_entry(self): """Test to ensure that a student can delete an entry""" # Click on the first activity box: Walking around the block self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div/div[3]/a/div').click() self.selenium.find_element_by_link_text('Add an entry').click() # The following has 2 matching: Just walking and Adding entry...block header_text = self.selenium.find_elements_by_tag_name('h3')[1].text self.assertTrue('Adding entry for Walking around the block!' in header_text) # Switching to iframe focus self.selenium.switch_to_frame(self.selenium.find_element_by_id('id_entry_iframe')) # Insert text text_entry = 'I think I will bring my cat out next time.' self.selenium.find_element_by_class_name('note-editable')\ .send_keys(text_entry) # Insert image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[2]').click() image_entry = 'http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/input')\ .send_keys(image_entry) # Click on the inset image button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div/div/div[3]/button').click() # Insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[5]/div[3]/button[3]').click() video_entry = 'https://www.youtube.com/watch?v=Rk_bV0RJRhs&index=20&list=PLJU_WCB1rA2SFwFy3lEvY_NH23ql1-Cgi' self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[2]/div/input')\ .send_keys(video_entry) # Click on the insert video button self.selenium.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/div/div[3]/button').click() # Switch back out of the iframe. self.selenium.switch_to_default_content() # Click on the submit button self.selenium.find_element_by_class_name('btn-success').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that entry exists as the first box on the page. box_text = self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a/div').text self.assertTrue(text_entry in box_text) self.selenium.find_element_by_xpath("//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']") self.selenium.find_element_by_xpath('//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]') # Click on the entry that was created self.selenium.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[1]/a').click() # Click on the delete button self.selenium.find_element_by_class_name('btn-danger').click() self.selenium.find_element_by_xpath('//*[@id="delete-modal"]/div/div/div[3]/a').click() # Ensure that we are back on the entries page. self.selenium.find_element_by_link_text('Add an entry') # Ensure that the entry created is no longer on the entries page main_text = self.selenium.find_element_by_class_name('main').text # Check for text self.assertFalse(text_entry in main_text) # Check for image image_entry_xpath = "//img[@src='http://images.jfdaily.com/jiefang/wenyu/new/201409/W020140919421426345484.jpg']" self.assertFalse(image_entry_xpath in main_text) # Check for video video_entry_xpath = '//iframe[@src="//www.youtube.com/embed/Rk_bV0RJRhs"]' self.assertFalse(video_entry_xpath in main_text)
#script, country = argv success = True wd = WebDriver() wd.implicitly_wait(2) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("http://en.wikipedia.org/wiki/Main_Page") wd.find_element_by_id("searchInput").click() wd.find_element_by_id("searchInput").clear() wd.find_element_by_id("searchInput").send_keys("madagascar") wd.find_element_by_id("searchButton").click() if not ("Malagasy" in wd.find_element_by_css_selector( "a[title=\"Malagasy people\"]").txt): success = False print("verifyTextPresent failed") print("Malagasy") finally: wd.quit() if not success: raise Exception("Test failed.")
try: wd.get( "http://www.jared.com/en/jaredstore/searchterm/731434000/true/731434000" ) if not ("items" in wd.find_element_by_tag_name("html").text): success = False print("verifyTextPresent failed") wd.find_element_by_partial_link_text( "Mother's Bracelet Round Birthstones Design in Silver").click() if not wd.find_element_by_xpath( "//select[@id='configSelect']//option[2]").is_selected(): wd.find_element_by_xpath( "//select[@id='configSelect']//option[2]").click() wd.find_element_by_id("btnStartCustomizing").click() if not wd.find_element_by_xpath( "//select[@id='metalTypeSelect']//option[2]").is_selected(): wd.find_element_by_xpath( "//select[@id='metalTypeSelect']//option[2]").click() wd.find_element_by_id("next-step").click() if not wd.find_element_by_xpath( "//select[@id='stoneTypeSelect']//option[2]").is_selected(): wd.find_element_by_xpath( "//select[@id='stoneTypeSelect']//option[2]").click() wd.find_element_by_xpath("//div[@id='tab-stoneType']//a[.='Next']").click() wd.find_element_by_css_selector("span.month_text").click() wd.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[2]").click() wd.find_element_by_xpath( "//div[@id='tab-stones-1']/div/ul[2]/li[1]/label/span[1]").click()
class BaseSeleniumPoolStatsTestCase(BasePoolStatsTestCase): def setUp(self): self.vdisplay = Xvfb(width=1280, height=1024) self.vdisplay.start() self.selenium = WebDriver() super(BaseSeleniumPoolStatsTestCase, self).setUp() def tearDown(self): self.selenium.quit() self.vdisplay.stop() super(BaseSeleniumPoolStatsTestCase, self).tearDown() def score_sheet_create(self, match_id=BasePoolStatsTestCase.DEFAULT_TEST_MATCH_ID, week_id=BasePoolStatsTestCase.DEFAULT_TEST_WEEK_ID): self.selenium.get('{}week/{}'.format(self.base_url, week_id)) self.selenium.find_element_by_id('score_sheet_create_button_match_{}'.format(match_id)).click() def populate_lineup(self, away_players=4, home_players=4): # get the lineup form, set the first player to 1, second to 2, etc for location_name in location_names: # first, make sure the form you are about to interact with is visible, to avoid a # selenium.common.exceptions.ElementNotInteractableException being thrown. self.selenium.find_element_by_id('toggle-{}_lineup'.format(location_name)).click() lineup_form = self.selenium.find_element_by_id('{}_lineup'.format(location_name)) # referring to away_players and home_players only via eval() makes them look unused ... for inc in range(0, eval('{}_players'.format(location_name))): select = Select(lineup_form.find_element_by_id('id_form-{}-player'.format(inc))) select.select_by_index(inc + 1) # 'inc + 1' as the first option in the select is '------' or similar # submit the form self.selenium.find_element_by_id('{}_lineup_save'.format(location_name)).click() def set_substitution(self, away_home, game_index, player_index=1, substitution_index=0): self.selenium.find_element_by_id('toggle-{}_substitutions'.format(away_home)).click() substitution_form = self.selenium.find_element_by_id('{}_substitutions'.format(away_home)) game_select = Select(substitution_form.find_element_by_id('id_form-{}-game_order'.format(substitution_index))) if game_index is not None: game_select.select_by_index(game_index) player_select = Select(substitution_form.find_element_by_id('id_form-{}-player'.format(substitution_index))) # select the 1th player; zero is '------' or similar player_select.select_by_index(player_index) selected_player = player_select.first_selected_option self.selenium.find_element_by_id('{}_substitutions_save'.format(away_home)).click() return selected_player def set_winners(self, forfeits=0, table_runs=0, random_wins=True): games_form = self.selenium.find_element_by_name('score_sheet_games_form') # hard-coding game count here, is there a way to not do that? # id_form-1-winner_0 win_counts = { 'home': 0, 'away': 0, } forfeit_games = [] tr_games = [] for inc in range(0, 16): # choose whether home (0) or away (1) wins "randomly" if random_wins: winner = randrange(0, 2) else: winner = inc % 2 win_counts[location_names[winner]] += 1 button = games_form.find_element_by_id('id_form-{}-winner_{}'.format(inc, winner)) button.click() # set some forfeits! while len(forfeit_games) < forfeits: candidate = randrange(0, 16) while candidate in forfeit_games: candidate = randrange(0, 16) forfeit_games.append(candidate) while len(tr_games) < table_runs: candidate = randrange(0, 16) while candidate in forfeit_games or candidate in tr_games: candidate = randrange(0, 16) tr_games.append(candidate) for forfeit_game in forfeit_games: games_form.find_element_by_id('id_form-{}-forfeit'.format(forfeit_game)).click() for tr_game in tr_games: games_form.find_element_by_id('id_form-{}-table_run'.format(tr_game)).click() games_form.find_element_by_id('games-save-button').click() return win_counts @staticmethod def count_player_stats_in_table(table): player_rows = table.find_elements_by_xpath('tbody/tr') wins = 0 losses = 0 trs = 0 for player_row in player_rows: player_cells = player_row.find_elements_by_tag_name('td') wins += int(player_cells[3].text) losses += int(player_cells[4].text) trs += int(player_cells[7].text) return { 'wins': wins, 'losses': losses, 'trs': trs, } @property def base_url(self): return '{}/stats/'.format(self.live_server_url)
wd = WebDriver() wd.implicitly_wait(60) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("http://localhost/addressbook/") wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").send_keys("\\undefined") wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").click() if not wd.find_element_by_id("140").is_selected(): wd.find_element_by_id("140").click() wd.find_element_by_xpath("//table[@id='maintable']/tbody/tr[12]/td[8]/a/img").click() wd.find_element_by_link_text("groups").click() if not wd.find_element_by_xpath("//div[@id='content']/form/span[2]/input").is_selected(): wd.find_element_by_xpath("//div[@id='content']/form/span[2]/input").click() wd.find_element_by_name("edit").click() wd.find_element_by_link_text("home").click() if not wd.find_element_by_xpath("//div[@class='right']/select//option[2]").is_selected(): wd.find_element_by_xpath("//div[@class='right']/select//option[2]").click() if not wd.find_element_by_id("155").is_selected(): wd.find_element_by_id("155").click() if not wd.find_element_by_id("153").is_selected(): wd.find_element_by_id("153").click() if wd.find_element_by_id("155").is_selected(): wd.find_element_by_id("155").click()
import time success = True wd = WebDriver() wd.implicitly_wait(60) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("https://apptimize.com/30-day-trial") wd.find_element_by_id("jobtitle").click() wd.find_element_by_id("jobtitle").send_keys("\\undefined") wd.find_element_by_id("password").click() wd.find_element_by_id("password").send_keys("\\undefined") wd.find_element_by_id("fname").click() wd.find_element_by_id("fname").clear() wd.find_element_by_id("fname").send_keys("Vamsavardhana") wd.find_element_by_id("lname").click() wd.find_element_by_id("lname").clear() wd.find_element_by_id("lname").send_keys("Vijay") wd.find_element_by_id("email").click() wd.find_element_by_id("email").clear() wd.find_element_by_id("email").send_keys("*****@*****.**") wd.find_element_by_id("company").click() wd.find_element_by_id("company").clear() wd.find_element_by_id("company").send_keys("Apptimize Candidate")
class UITestCase(LiveServerTestCase): def use_xvfb(self): from pyvirtualdisplay import Display self.display = Display('xvfb', visible=1, size=(1280, 1024)) self.display.start() self.driver = WebDriver() def setUp(self): try: self.driver = WebDriver() ui_is_not_available = False except WebDriverException: ui_is_not_available = True if ui_is_not_available: self.use_xvfb() self.driver.implicitly_wait(10) super(UITestCase, self).setUp() def tearDown(self): self.driver.quit() if hasattr(self, 'display'): self.display.stop() # I believe this line is no longer necessary, but I'm leaving it here # until the UI tests have run many times without deadlocking. # -RM 20140522 #self.kill_pending_transactions() super(UITestCase, self).tearDown() def kill_pending_transactions(self): # The super.tearDown sometimes hangs when truncating tables # because of lingering pending transactions with locks on those tables. # Kill them to avoid deadlock! try: dbname = settings.DATABASES['default']['NAME'] sql = "select pg_terminate_backend(procpid)" + \ " from pg_stat_activity where datname='%s'" % dbname + \ " and current_query='<IDLE> in transaction';" connection.cursor().execute(sql) except InterfaceError: # Sometimes we get "connection already closed" pass def click(self, selector): self.find(selector).click() def click_when_visible(self, selector): element = self.find(selector) self.wait_until_visible(element) element.click() def find(self, selector): return self.driver.find_element_by_css_selector(selector) def find_name(self, name): return self.driver.find_element_by_name(name) def find_id(self, id): return self.driver.find_element_by_id(id) def process_login_form(self, username, password): username_elmt = self.wait_until_present('[name="username"]') password_elmt = self.find_name('password') username_elmt.send_keys(username) password_elmt.send_keys(password) self.click('form * button') def browse_to_url(self, url): self.driver.get(self.live_server_url + url) def find_anchor_by_url(self, url): return self.find("[href='%s']" % url) def wait_until_present(self, selector, timeout=10): """ Wait until an element with CSS 'selector' exists on the page. Useful for detecting that an operation loads the page you're expecting. """ element = [None] # use list so it can be set by inner scope def is_present(driver): element[0] = self.find(selector) return element[0] is not None WebDriverWait(self.driver, timeout).until(is_present) return element[0] def wait_until_text_present(self, text, timeout=10): """ Wait until 'text' exists on the page. Useful for detecting that an operation loads the page you're expecting. """ WebDriverWait(self.driver, timeout).until( lambda driver: text in driver.page_source) def wait_until_enabled(self, element_or_selector, timeout=10): """ Wait until 'element_or_selector' is enabled. """ element = self._get_element(element_or_selector) WebDriverWait(self.driver, timeout).until( lambda driver: element.get_attribute("disabled") is None) return element def wait_until_visible(self, element_or_selector, timeout=10): """ Wait until 'element_or_selector' (known to already exist on the page) is displayed. """ element = self._get_element(element_or_selector) WebDriverWait(self.driver, timeout).until( lambda driver: element.is_displayed()) return element def wait_until_invisible(self, element_or_selector, timeout=10): """ Wait until 'element_or_selector' (known to already exist on the page) is not displayed. """ element = self._get_element(element_or_selector) def is_invisible(driver): try: return not element.is_displayed() except StaleElementReferenceException: return True WebDriverWait(self.driver, timeout).until(is_invisible) return element def _get_element(self, element_or_selector): if isinstance(element_or_selector, basestring): return self.find(element_or_selector) else: return element_or_selector
import time success = True wd = WebDriver() wd.implicitly_wait(60) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("http://b11test4a.mentoringmindsonline.com/mysdb_m3_test4/_design/mys/mmloginw.html") wd.find_element_by_id("loginUserID").click() wd.find_element_by_id("loginUserID").clear() wd.find_element_by_id("loginUserID").send_keys("113177") wd.find_element_by_id("userPasswd").click() wd.find_element_by_id("userPasswd").clear() wd.find_element_by_id("userPasswd").send_keys("Ctfl*5258") wd.find_element_by_id("sign-in").click() wd.find_element_by_id("reportsBigBtnBtn").click() wd.find_element_by_id("selectReportTypeW").click() wd.find_element_by_id("dijit_MenuItem_30_text").click() wd.find_element_by_id("dijit_MenuItem_39_text").click() wd.find_element_by_id("dijit_MenuItem_92_text").click() wd.find_element_by_id("generateReportBtn").click() wd.find_element_by_css_selector("#dojox_mobile_ToolBarButton_34 > span.mblToolBarButtonBody.mblColorDefault > table.mblToolBarButtonText > tbody > tr > td.mblToolBarButtonLabel").click() wd.find_element_by_css_selector("#dojox_mobile_ToolBarButton_4 > span.mblToolBarButtonBody.mblColorDefault > table.mblToolBarButtonText > tbody > tr > td.mblToolBarButtonLabel").click() wd.find_element_by_css_selector("td.mblToolBarButtonLabel").click()
import time success = True wd = WebDriver() wd.implicitly_wait(60) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.get("http://*****:*****@class='form-signin']/button").click() wd.find_element_by_xpath("//div/div[1]/div[2]/div/div[2]/div/ul/li[1]/a").click() wd.find_element_by_xpath("//div/div[1]/div[2]/div/div[2]/div/ul/li[1]/ul/li[2]/a").click() wd.find_element_by_xpath("//div[2]/div[1]/div[2]/div/div[2]/div/ul/li[1]/a").click() wd.find_element_by_xpath("//div[2]/div[1]/div[2]/div/div[2]/div/ul/li[1]/ul/li[1]/a").click() wd.find_element_by_id("id_nombre_usuario").click() wd.find_element_by_id("id_nombre_usuario").clear() wd.find_element_by_id("id_nombre_usuario").send_keys("Nuevo Usuario2") wd.find_element_by_id("id_password").click() wd.find_element_by_id("id_password").clear()
from selenium.webdriver.firefox.webdriver import WebDriver as Firefox from selenium.webdriver.support.select import Select import os from selenium.webdriver.support.ui import WebDriverWait import time driver = Firefox() driver.get('http://console.ezparking.com.cn/console/a?login') title = driver.title print(title) #selector = Select(driver.find_element_by_id("selectdemo")) #selector.select_by_index("2") driver.find_element_by_id('username').send_keys('15123532344') driver.find_element_by_id('password').send_keys('Luobo123') driver.find_element_by_xpath( ".//*[@id='normal_login']/div/div/div[3]/button").click() ''' driver.find_element_by_xpath(".//*[@id='main-sidebar']/section/ul/li[2]/a/span[1]").click() #停车场管理 driver.find_element_by_xpath(".//*[@id='main-sidebar']/section/ul/li[2]/ul/li[1]/a").click() driver.switch_to_frame('mainFrame') print('iFrame切换成功') a=WebDriverWait(driver,10,1).until(lambda x:x.find_element_by_xpath(".//*[@id='searchForm']/div[1]/div[2]/div/div/span/span[1]/span/span[2]")) print('1111111111') a.click() driver.find_elements_by_css_selector('[role="treeitem"]')[2].click() driver.find_element_by_xpath(".//*[@id='btnSubmit']").click() a=driver.find_element_by_xpath(".//*[@id='contentTable']/tbody/tr[2]/td[8]") print(a.text) driver.find_element_by_xpath(".//*[@id='main-sidebar']/section/ul/li[4]/a/span").click()
class OfferTest (LiveServerTestCase): def setUp(self): self.name_professor = 'teste' self.create_timePeriod_and_course() self.create_professor_and_schedule() self.browser = WebDriver() create_user_and_login(self.browser, self.live_server_url,'john','johnpassword','*****@*****.**') self.browser.implicitly_wait(40) def tearDown(self): cursor = MySQLConnection() [offer.delete() for offer in Offer.find()] [schedule.delete() for schedule in Schedule.find()] cursor.execute('DELETE FROM minitableDayOfTheWeek') [timePeriod.delete() for timePeriod in TimePeriod.find()] [course.delete() for course in Course.find()] [professor.delete() for professor in Professor.find()] self.browser.quit() def create_timePeriod_and_course(self): cursor = MySQLConnection() length = cursor.execute('SELECT idLength FROM minitableLength where length="Semestral"') if not length: cursor.execute('INSERT INTO minitableLength (length) values ("Semestral")') self.course = Course('tst9999', 'teste9999', '0000-00-00') self.course.store() length = cursor.execute('SELECT idLength FROM minitableLength where length="Semestral"') self.timePeriod = TimePeriod(1, 2014, 1) self.timePeriod.store() def create_professor_and_schedule(self): cursor = MySQLConnection() cursor.execute('INSERT INTO `minitableDayOfTheWeek` (dayOfTheWeek) VALUES ("Domingo"), ("Segunda"), ("Terça"), ("Quarta"), ("Quinta"), ("Sexta"), ("Sabado")') self.schedule = Schedule('Domingo', '14:00:00', 'weekly', '12:00:00') self.schedule.store() self.schedule = Schedule('Segunda', '19:00:00', 'weekly', '16:00:00') self.schedule.store() self.schedule = Schedule('Quarta', '16:00:00', 'weekly', '14:00:00') self.schedule.store() self.professor = Professor('Professor Teste') self.professor.store() self.second_professor = Professor('Professor Teste2') self.second_professor.store() def login_to_offer_page(self): open_page(self.browser, '/interface/', self.live_server_url) dropdown_timePeriod = self.browser.find_element_by_id('id_dropDownTimePeriod') dropdown_course = self.browser.find_element_by_id('id_dropDownCourse') select_timePeriod = Select(dropdown_timePeriod) select_timePeriod.select_by_value(str(self.timePeriod.idTimePeriod)) select_course = Select(dropdown_course) select_course.select_by_value(str(self.course.idCourse)) professor_interface = self.browser.find_element_by_link_text('Offer') professor_interface.click() self.assertIn('Interface - Offer', self.browser.title) def test_create_offer(self): self.login_to_offer_page() button_create_offer = self.browser.find_element_by_name('criar') button_create_offer.click() self.assertIn('Interface - Offer Create', self.browser.title) dropdown_professor = self.browser.find_element_by_id('id_dropDownProfessor') select_professor = Select(dropdown_professor) select_professor.select_by_value(str(self.professor.idProfessor)) input_classNumber = self.browser.find_element_by_id('id_classNumber') input_classNumber.send_keys('1') dropdown_practical = self.browser.find_element_by_id('id_dropDownTeoricaPratica') select_practical = Select(dropdown_practical) select_practical.select_by_value('1') input_numberOfRegistrations = self.browser.find_element_by_id('id_numberOfRegistrations') input_numberOfRegistrations.send_keys('10') self.browser.find_element_by_id("id_listSchedules_0").click() self.browser.find_element_by_id("id_listSchedules_1").click() self.browser.find_element_by_id("id_listSchedules_2").click() button_store = self.browser.find_element_by_name('Cadastrar') button_store.click() self.assertIn('Interface - Offer Detail', self.browser.title) id_courseCode = self.browser.find_element_by_id('courseCode') self.assertEqual(id_courseCode.text, 'tst9999') id_name = self.browser.find_element_by_id('name') self.assertEqual(id_name.text, 'teste9999') id_professor_name = self.browser.find_element_by_id('professor_name') self.assertEqual(id_professor_name.text, 'Professor Teste') id_timePeriod = self.browser.find_element_by_id('timePeriod') self.assertEqual(id_timePeriod.text, 'Primeiro semestre de 2014') id_classNumber = self.browser.find_element_by_id('classNumber') self.assertEqual(id_classNumber.text, 'T01') id_practical = self.browser.find_element_by_id('practical') self.assertEqual(id_practical.text, "TEORICA") id_numberOfRegistrations = self.browser.find_element_by_id('numberOfRegistrations') self.assertEqual(id_numberOfRegistrations.text, '10') id_schedules = self.browser.find_element_by_id('schedules') self.assertIn("Domingo 12:00 - 14:00", id_schedules.text) self.assertIn("Segunda 16:00 - 19:00", id_schedules.text) self.assertIn("Quarta 14:00 - 16:00", id_schedules.text) def test_edit_offer(self): timePeriod = TimePeriod.find()[0] course = Course.find()[0] first_professor = Professor.find()[0] schedules = Schedule.find() offer = Offer(timePeriod, course, 10, 0, first_professor) offer.setNumberOfRegistrations(10) offer.setSchedules(schedules) offer.store() open_page(self.browser, '/interface/offer/' + str(offer.idOffer), self.live_server_url) self.assertIn('Interface - Offer Detail', self.browser.title) button_edit = self.browser.find_element_by_name('editar') button_edit.click() self.assertIn('Interface - Offer Edit', self.browser.title) dropdown_professor = self.browser.find_element_by_id('id_dropDownProfessor') select_professor = Select(dropdown_professor) select_professor.select_by_value(str(self.second_professor.idProfessor)) input_classNumber = self.browser.find_element_by_id('id_classNumber') input_classNumber.send_keys('1') dropdown_practical = self.browser.find_element_by_id('id_dropDownTeoricaPratica') select_practical = Select(dropdown_practical) select_practical.select_by_value('1') input_numberOfRegistrations = self.browser.find_element_by_id('id_numberOfRegistrations') input_numberOfRegistrations.send_keys('1') self.browser.find_element_by_id("id_listSchedules_1").click() self.browser.find_element_by_id("id_listSchedules_2").click() button_apply = self.browser.find_element_by_name('Aplicar') button_apply.click() self.assertIn('Interface - Offer Detail', self.browser.title) id_courseCode = self.browser.find_element_by_id('courseCode') self.assertEqual(id_courseCode.text, 'tst9999') id_name = self.browser.find_element_by_id('name') self.assertEqual(id_name.text, 'teste9999') id_professor_name = self.browser.find_element_by_id('professor_name') self.assertEqual(id_professor_name.text, 'Professor Teste2') id_timePeriod = self.browser.find_element_by_id('timePeriod') self.assertEqual(id_timePeriod.text, 'Primeiro semestre de 2014') id_classNumber = self.browser.find_element_by_id('classNumber') self.assertEqual(id_classNumber.text, 'T101') id_practical = self.browser.find_element_by_id('practical') self.assertEqual(id_practical.text, "PRATICA") id_numberOfRegistrations = self.browser.find_element_by_id('numberOfRegistrations') self.assertEqual(id_numberOfRegistrations.text, '101') id_schedules = self.browser.find_element_by_id('schedules') self.assertIn("Domingo 12:00 - 14:00", id_schedules.text) self.assertNotIn("Segunda 16:00 - 19:00", id_schedules.text) self.assertNotIn("Quarta 14:00 - 16:00", id_schedules.text) def test_delete_offer(self): timePeriod = TimePeriod.find()[0] course = Course.find()[0] first_professor = Professor.find()[0] schedules = Schedule.find() offer = Offer(timePeriod, course, 10, 0, first_professor) offer.setNumberOfRegistrations(10) offer.setSchedules(schedules) offer.store() open_page(self.browser, '/interface/offer/' + str(offer.idOffer), self.live_server_url) self.assertIn('Interface - Offer Detail', self.browser.title) button_delete = self.browser.find_element_by_name('deletar') button_delete.click() alert = self.browser.switch_to.alert alert.accept() self.assertIn('Interface', self.browser.title) open_page(self.browser, '/interface/offer/' + str(offer.idOffer), self.live_server_url) self.assertNotIn('Interface - Offer Detail', self.browser.title)