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 installAddon_cleanTabs_getLoginWindow(self, driver: WebDriver) -> None: """ 1) Install UblockOrigin 2) If any "welcome" windows open, close them 3) Click on login button """ driver.install_addon( f"{self.cfg['EXTENSIONS']['FOX_EXT_BASE_PATH']}/{self.cfg['EXTENSIONS']['UBO']}" ) driver.get(self.cfg["LOGIN"]["LOGIN_FROM"]) WebDriverWait(self.driver, 7).until( EC.presence_of_all_elements_located((By.TAG_NAME, "main"))) # wait for the page to load # Points to ww login-page MAIN_HANDLE: str = driver.current_window_handle for window_handle in driver.window_handles: if window_handle != MAIN_HANDLE: driver.switch_to.window(window_handle) # after closing all irrelevant tabs driver will focus back to the main one driver.close() # Puts focus back on ww login-page driver.switch_to.window(MAIN_HANDLE) # Use this stuff to setup the login window (You don't want any junk in some new tab) sleep(2) # click the first button on the page, it will make login button visible driver.execute_script( self.clickFirstElementFromElementList("button") + self.clickElementWithInnerTextS("button", "log in"))
class FunctionalTest(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(5) def tearDown(self): self.browser.quit() def wait_for(self, function_with_assertion, timeout=DEFAULT_WAIT): start_time = time.time() while time.time() - start_time < timeout: try: return function_with_assertion() except (AssertionError, WebDriverException): time.sleep(0.1) return function_with_assertion() def create_pre_authenticated_session(self, email, password, *args, **kwargs): session_key = create_pre_authenticated_session(email, password, *args, **kwargs) # To set a cookie we need to first visit the domain... # 404 pages load the fastest... self.browser.get(self.live_server_url + '/404_no_such_url/') self.browser.add_cookie({ 'name': settings.SESSION_COOKIE_NAME, 'value': session_key, 'path': '/' })
def _parse_caption_with_js(driver: WebDriver, language_code: str, page_id: str, img_id: str, icons: Set[str], debug_info: bool) -> Optional[str]: caption = None if img_id in _KNOWN_ICONS or img_id in icons: if debug_info: print('Skipping known icon', img_id) return caption url = 'https://{}.wikipedia.org/wiki/{}#/media/{}{}'.format( language_code, page_id, _get_translated_file_label(language_code), img_id) if debug_info: print('Downloading captions for', url) driver.get(url) sleep_time = 1 retry_count = 2 time.sleep(sleep_time) # reqired for JS to load content for k in range(retry_count): try: # TODO: there is a bug when trying to parse noviewer thum. Driver returns caption from previous page # Currently not reproducible when invalidate_cache=False and caption already exists caption = driver.find_element_by_class_name("mw-mmv-title").text if caption == "": caption = None raise Exception else: break except: time.sleep(sleep_time) # reqired for JS to load content print("RETRY", k, " ||| ", img_id) # closing the tab so that we won't read it again if next page fails to load default_url = 'https://www.wikipedia.org/' driver.get(default_url) return caption
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 download_lesson(driver: WebDriver, lesson: WebElement, module_path: pathlib.Path) -> None: lesson_url = lesson.get_attribute('href') course_page = driver.current_window_handle driver.execute_script('window.open()') driver.switch_to.window(driver.window_handles[1]) driver.get(lesson_url) youtube_url = get_youtube_url(driver) if youtube_url is not None: # BUG: the output option is not working; fix it; output_path = module_path / '%(title)s.%(ext)s' ydl_opts = { 'output': str(output_path), 'retries': 10, } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([youtube_url]) except youtube_dl.utils.DownloadError as e: print(e) driver.close() driver.switch_to.window(course_page)
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 test_add_todo(driver: WebDriver, app_with_temp_db): driver.get('http://localhost:5000/') add_todo(driver, todo_name="test") new_todo = driver.find_element_by_css_selector('[aria-label="todo test label"]') assert new_todo.text == 'test' assert driver.title == 'To-Do App'
def test_can_mark_todo_as_not_complete(driver: WebDriver, app_with_temp_db): driver.get('http://localhost:5000/') click_todo_checkbox(driver, todo_name="test") is_checked = driver.find_element_by_css_selector(f'[aria-label="todo test checkbox"]').is_selected() assert is_checked == False
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 webHelper(): def __init__(self): self.success = True self.wd = WebDriver() self.wd.implicitly_wait(60) def setText(self, locator, text): self.wd.find_element_by_xpath(locator).click() self.wd.find_element_by_xpath(locator).clear() self.wd.find_element_by_xpath(locator).send_keys(text) def selectCheckbox(self, locator): if not self.wd.find_element_by_xpath(locator).is_selected(): self.wd.find_element_by_xpath(locator).click() def unselectCheckBox(self, locator): if self.wd.find_element_by_xpath(locator).is_selected(): self.wd.find_element_by_xpath(locator).click() def clickButton(self, locator): self.wd.find_element_by_xpath(locator).click() def open(self,locator): self.wd.get(locator)
def _perform_navigation(browser: webdriver.WebDriver, url: str): try: browser.get(url) wait() except WebDriverException: logging.error(f"Something went wrong while executing the task") logging.error(traceback.format_exc())
class LoginMixin(object): def wait(self, delay, element): try: myElem = WebDriverWait(self.selenium, delay).until( EC.presence_of_element_located((By.NAME, element))) except TimeoutException: print('Loading took too much time!') return myElem def setUp(self): super().setUp() self.user = User.objects.create_user( username='******', password='******' ) self.user.is_active = True self.user.save() self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.selenium.get(f'{self.live_server_url}/') username = self.selenium.find_element_by_name('username') username.send_keys('usuario') password = self.selenium.find_element_by_name('password') password.send_keys('usuario') self.selenium.find_element_by_name('login').click() def tearDown(self): self.selenium.quit() super().tearDown()
def handle(self, *args, **options): xvfb = Xvfb(width=1600, height=720) xvfb.start() browser = WebDriver() browser.get(settings.DOMAIN) sleep(1) browser.find_element_by_css_selector("#disclaimer button").click() sleep(0.7) browser.find_elements_by_css_selector(".officer .checkmark")[4].click() sleep(2) browser.find_element_by_css_selector( ".complaint-row .col-md-3").click() sleep(1) content = browser.get_screenshot_as_png() now = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S") file_name = "{now}.png".format(now=now) file_path = os.path.join(settings.BASE_DIR, 'static', file_name) with open(file_path, "wb") as f: f.write(content) browser.quit() email = EmailMessage(subject='CPDB Homepage screenshot %s' % now, body='FYI', to=['*****@*****.**']) email.attach_file(file_path) email.send() xvfb.stop()
class BaseLiveServerTestCase(LiveServerTestCase): def setUp(self): get_or_create_test_admin() self.browser = WebDriver() self.do_admin_login('test', 'test') def tearDown(self): self.browser.quit() def do_admin_login(self, username, password): self.browser.get('%s%s' % (self.live_server_url, '/admin/')) username_input = self.browser.find_element_by_name("username") username_input.send_keys(username) password_input = self.browser.find_element_by_name("password") password_input.send_keys(password) self.browser.find_element_by_xpath('//input[@value="Log in"]').click() def new_window(self, name='other'): self.browser.execute_script('window.open("/admin/", "'+ name +'")') self.browser.switch_to_window(self.browser.window_handles[1]) while self.warning_element() is False: time.sleep(0.1) self.browser.switch_to_window(self.browser.window_handles[0]) def press_space(self): a = ActionChains(self.browser) a.key_down(Keys.SPACE) a.perform() def wait_for_pages_loaded(self): for win in self.browser.window_handles: while self.warning_element() is False: time.sleep(0.1)
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 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 process_search(d: WebDriver, email: str) -> int: d.get(url=leakedsource_url) submit = d.find_element_by_xpath('/html/body/center[2]/div/form/div/div[2]/center/input') email_field = d.find_element_by_xpath('/html/body/center[2]/div[1]/form/div/div[2]/div[1]/div/input') email_field.send_keys(email) submit.click() result = WebDriverWait(d, 10).until( ec.presence_of_element_located((By.XPATH, '/html/body/center[2]/div[2]')) ) return 'no results found.' not in result.text.lower()
def log_out(browser: webdriver.WebDriver): try: # Sign out logging.info("Logging out") browser.get("https://www.banggood.com/") browser.get("https://www.banggood.com/index.php?com=account&t=logout") logging.info("Logout done!") except WebDriverException: logging.error(f"Something went wrong while executing the task") logging.error(traceback.format_exc())
def process_search(d: WebDriver, email: str) -> int: d.get(url=firefox_url) form = d.find_element_by_xpath('//*[@id="scan-user-email"]') email_field = d.find_element_by_xpath('//*[@id="scan-email"]') email_field.send_keys(email) form.submit() results_count = WebDriverWait(d, 10).until( ec.presence_of_element_located( (By.XPATH, '/html/body/main/div[1]/div/h2/span'))) return int(results_count.text)
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.")
class CoreTestIndexPage(StaticLiveServerTestCase): def setUp(self): self.url = "{}{}".format(self.live_server_url, reverse('core:index')) self.driver = WebDriver() self.driver.implicitly_wait(5) def test_index_page_is_working_message(self): self.driver.get(self.url) working_message = self.driver.find_element_by_xpath('//h1').text self.assertEquals('Django Boilerplate is working !', working_message)
class CalculatorTests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(CalculatorTests, cls).setUpClass() User.objects.create_superuser(username='******', password='******', email='*****@*****.**') @classmethod def tearDownClass(cls): super(CalculatorTests, cls).tearDownClass() def setUp(self): self.selenium = WebDriver(executable_path='/usr/local/bin/geckodriver') self.selenium.implicitly_wait(10) print('<<<< SETUP') def tearDown(self): #self.selenium.quit() print('<<<< TD') def test_calculator(self): """ Django Admin login test """ # Open the admin index page self.selenium.get(self.live_server_url + reverse('calendar:calculator')) # Selenium knows it has to wait for page loads (except for AJAX requests) # so we don't need to do anything about that, and can just # call find_css. Since we can chain methods, we can # call the built-in send_keys method right away to change the # value of the field self.selenium.find_element_by_xpath( '//*[@id="id_start_date"]').send_keys(4 * Keys.BACKSPACE) self.selenium.find_element_by_xpath( '//*[@id="id_start_date"]').send_keys("2017-10-01") # for the password, we can now just call find_css since we know the page # has been rendered self.selenium.find_element_by_xpath( '//*[@id="id_end_date"]').send_keys(4 * Keys.BACKSPACE) self.selenium.find_element_by_xpath( '//*[@id="id_end_date"]').send_keys('2017-10-31') # You're not limited to CSS selectors only, check # http://seleniumhq.org/docs/03_webdriver.html for # a more compreehensive documentation. self.selenium.find_element_by_xpath( '/html/body/div[2]/form/input[2]').click() # /html/body/div[2]/form/input[2] element = self.selenium.find_element_by_xpath( '/html/body/div[2]/h3') # /html/body/div[2]/form/input[2] message = '22 working days' self.assertEqual(element.text, message)
def parse_all_saints(driver: WebDriver, url): driver.get(get_url_view(url)) driver.implicitly_wait(30) time.sleep(10) try: driver.execute_script("window.scrollTo(0, 40000)") time.sleep(10) except NoSuchElementException: pass product_list = make_soup(driver.page_source).find_all("div", class_="product") return map(parse_product, product_list)
class Application: def __init__(self): self.driver = WebDriver() self.driver.implicitly_wait(30) self.session = SessionHelper(self) self.vacancy = VacancyHelper(self) def open_home_page(self): self.driver.get("http://playtogether-001-site1.htempurl.com/login") def destroy(self): self.driver.quit()
def get_links_on_deskop_website(driver: WebDriver) -> List[str]: links = [] for url in politics_pages: driver.get(url) html = driver.page_source.encode('utf-8') # Get politics links new_links = get_links_from_driver(driver) links += new_links print(f'Found {len(new_links)} links on \'{url}\'') print(f'Found {len(links)} links on desktop') return links
class LoginTest(StaticLiveServerTestCase): fixtures = ['user_testdata.json'] def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.selenium.get('%s%s' % (self.live_server_url, '/account/login/')) def tearDown(self): self.selenium.quit() def __get_page(self): class LoginPage(object): def __init__(self, selenium): self.selenium = selenium self.username = self.selenium.find_element_by_id('id_username') self.password = self.selenium.find_element_by_id('id_password') self.button = WebDriverWait(self.selenium, 10).until( EC.presence_of_element_located((By.TAG_NAME, "button"))) return LoginPage(self.selenium) @staticmethod def __send_keys_scrolling(input_element, keys): _ = input_element.location_once_scrolled_into_view time.sleep(1) input_element.send_keys(keys) def test_successful_login(self): page = self.__get_page() self.__send_keys_scrolling(page.username, 'test') self.__send_keys_scrolling(page.password, 'kossarnajafi1') page.button = WebDriverWait(self.selenium, 10).until( EC.presence_of_element_located((By.TAG_NAME, "button"))) page.button.click() WebDriverWait( self.selenium, 10).until(lambda driver: driver.find_element_by_tag_name('body')) def test_wrong_email_login(self): page = self.__get_page() self.__send_keys_scrolling(page.username, 'soroush1') self.__send_keys_scrolling(page.password, '123') page.button.click() _ = self.selenium.find_element_by_class_name('alert-danger') def test_wrong_password_login(self): page = self.__get_page() self.__send_keys_scrolling(page.username, 'soroush') self.__send_keys_scrolling(page.password, 'xxx') page.button.click() _ = self.selenium.find_element_by_class_name('alert-danger')
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 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 _login_to_admin(self, webdriver: WebDriver): """ Login to admin """ webdriver.get('{}/admin/'.format(self.live_server_url)) form = webdriver.find_element_by_css_selector( 'form[data-ui-relevance="main-login"]') form.find_element_by_css_selector('input[name="username"]').send_keys( self.admin_username) form.find_element_by_css_selector('input[name="password"]').send_keys( self.admin_password) form.find_element_by_css_selector('input[name="otp"]').send_keys( str(get_otp(self.admin_secret))) form.find_element_by_css_selector('button[type="submit"]').click()
class CalculatorTests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(CalculatorTests, cls).setUpClass() User.objects.create_superuser(username='******', password='******', email='*****@*****.**') @classmethod def tearDownClass(cls): super(CalculatorTests, cls).tearDownClass() def setUp(self): self.selenium = WebDriver(executable_path='/usr/local/bin/geckodriver') self.selenium.implicitly_wait(10) print('<<<< SETUP') def tearDown(self): #self.selenium.quit() print('<<<< TD') def test_calculator(self): """ Django Admin login test """ # Open the admin index page self.selenium.get(self.live_server_url + reverse('calendar:calculator')) # Selenium knows it has to wait for page loads (except for AJAX requests) # so we don't need to do anything about that, and can just # call find_css. Since we can chain methods, we can # call the built-in send_keys method right away to change the # value of the field self.selenium.find_element_by_xpath('//*[@id="id_start_date"]').send_keys(4 * Keys.BACKSPACE) self.selenium.find_element_by_xpath('//*[@id="id_start_date"]').send_keys("2017-10-01") # for the password, we can now just call find_css since we know the page # has been rendered self.selenium.find_element_by_xpath('//*[@id="id_end_date"]').send_keys(4 * Keys.BACKSPACE) self.selenium.find_element_by_xpath('//*[@id="id_end_date"]').send_keys('2017-10-31') # You're not limited to CSS selectors only, check # http://seleniumhq.org/docs/03_webdriver.html for # a more compreehensive documentation. self.selenium.find_element_by_xpath('/html/body/div[2]/form/input[2]').click() # /html/body/div[2]/form/input[2] element = self.selenium.find_element_by_xpath('/html/body/div[2]/h3') # /html/body/div[2]/form/input[2] message = '22 working days' self.assertEqual(element.text, message)
def login(browser: webdriver.WebDriver): browser.set_page_load_timeout(5) try: browser.get(wbm_cfg.homepage_url) except WebDriverException: browser.refresh() finally: pyautogui.typewrite(wbm_cfg.login_user_value) pyautogui.typewrite("\t") pyautogui.typewrite(wbm_cfg.login_pw_value) pyautogui.typewrite("\n") logging.info("Login executed") wait_for_page(browser, wbm_cfg.homepage_url, wbm_cfg.main_page_attr_xpath)
def run(*, driver: WebDriver, url: str, opt: int): driver.get(url) try: main_node = driver.find_element_by_xpath("/html/body/form/div[1]") els: list = main_node.find_elements_by_tag_name("input") el = els[int(opt) - 1] driver.execute_script("arguments[0].click();", el) # delay time.sleep(3) logger.info("ok") except: # noqa logger.info("ko") finally: driver.close()
def pass_xing_login(driver: WebDriver, xing_login: str, xing_pass: str) -> bool: """ pass login on XING using driver and login/password :Returns: * True - login successfull * False - can't login """ url = 'https://loginix.com/' driver.get(url) sleep(3) try: permission_accept: WebElement = driver.find_element_by_xpath( '//*[@id="consent-accept-button"]') permission_accept.click() except NoSuchElementException: # no question about privacy pass try: driver.find_element_by_name("username").send_keys(xing_login) except NoSuchElementException: print("no element by name: username") return False try: driver.find_element_by_name("password").send_keys(xing_pass) except NoSuchElementException: print("no element by name: password") return False try: driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div/div[2]/section/div/main/div/div/div/div/div/form/div[5]/button/div" ).click() except NoSuchElementException: print("no element button login ") return False sleep(2) try: driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div/div[2]/section/div/main/div/div/div/div/div[2]/div[2]/button[1]/div/span" ).click() sleep(2) except NoSuchElementException: # no element 'Try two factor authentication' with button Skip pass return True
def go_to_page(browser: webdriver.WebDriver, url, test_element_xpath): if browser.current_url != url: browser.set_page_load_timeout(3) try: browser.get(url) except TimeoutException: try: browser.set_page_load_timeout(10) browser.get(url) except TimeoutException: logging.error("The URL " + url + " is unreachable") browser.close() wait_for_page(browser, url, test_element_xpath)
class BasicViewTests(unittest.TestCase): """ Just visit all the views and make sure they look okay """ 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() def test_home(self): self.selenium.get(self.live_server_url + '/') # two project links are there self.selenium.find_element_by_link_text('1000 Genomes') def test_project_home(self): self.selenium.get(self.live_server_url + '/project/1kg') def test_family_home(self): self.selenium.get(self.live_server_url + '/project/1kg/family/HG1') def tearDown(self): self.selenium.quit()
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()
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()
class VisitorTest(LiveServerTestCase): """ Test as a visitor (unregistered user) """ def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(3) self.n1 = Node.objects.create( title='TestNodeOne', description='The first test node' ) self.u1 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.u2 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) # Create 99 topics for i in range(1, 100): setattr( self, 't%s' % i, Topic.objects.create( title='Test Topic %s' % i, user=self.u1, content_raw='This is test _topic __%s__' % i, node=self.n1 ) ) def tearDown(self): self.browser.quit() def test_index(self): self.browser.get(self.live_server_url+reverse('niji:index')) body = self.browser.find_element_by_tag_name('body') self.assertIn('niji', body) def test_topic_page(self): pass def test_node_page(self): pass def test_pagination(self): pass
def get_fail_tests(url): """ """ browser = Firefox() browser.get(url) # get new failures tests = [e.text.strip() for e in browser.find_elements_by_css_selector( "#new-failed-tests .test-name")] # get existing tests tests = tests + [e.text.strip() for e in browser.find_elements_by_css_selector( "#existing-failed-tests .test-name")] browser.quit() return tests
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
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 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 _process_login_form(self, username, password): username_elmt = self.driver.find_element_by_name('username') password_elmt = self.driver.find_element_by_name('password') username_elmt.send_keys(username) password_elmt.send_keys(password) submit = self.driver.find_element_by_css_selector('form * button') submit.click() def _browse_to_url(self, url): self.driver.get(self.live_server_url + url) def find_anchor_by_url(self, url): return self.driver.find_element_by_css_selector("[href='%s']" % url)
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)
class JavaScriptTestCase(unittest.TestCase): def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(1) # wait one second before failing to find def tearDown(self): self.selenium.quit() def test_catalogue_extender_required(self): self.selenium.get(self._load('test_catalogue_extender_required')) self.assert_zero_failures() def _load(self, page): return 'file://' + opath.join(opath.dirname(__file__), 'qunit', page+'.html') def assert_zero_failures(self): elem = self.selenium.find_element_by_css_selector('#qunit-testresult span.failed') self.assertTrue(int(elem.text) == 0, "Failures found: " + elem.text)
class HomePageSeleleniumTests(StaticLiveServerTestCase): """Selenium tests for the home page""" def setUp(self): """Opens the home page""" self.selenium = WebDriver() self.selenium.get('{0}{1}'.format(self.live_server_url, '/')) def tearDown(self): self.selenium.quit() super() def test_elements(self): """Tests to ensure the proper elements are present""" self.selenium.find_elements_by_link_text('iU') self.selenium.find_elements_by_link_text('Welcome') about_us = self.selenium\ .find_elements_by_xpath('//*[@href="#about-us"]') assert_true(len(about_us), 2) self.selenium.find_element_by_link_text('Features').click()
class WebObject(StaticLiveServerTestCase): """Base class for page objects.""" @classmethod def setUpClass(self): super(WebObject, self).setUpClass() self.driver = WebDriver() self.driver.set_window_size(1024, 768) self.driver.maximize_window() self.driver.implicitly_wait(15) @classmethod def tearDownClass(self): self.driver.quit() super(WebObject, self).tearDownClass() def create_login_session(self, username): session_cookie = create_session_for_given_user(username) self.driver.get(self.live_server_url) self.driver.add_cookie(session_cookie)
class AnonymousUseCaseTests(LiveServerTestCase): fixtures = ['user'] @classmethod def setUpClass(self): self.selenium = WebDriver() super(AnonymousUseCaseTests, self).setUpClass() self.timeout = 10 @classmethod def tearDownClass(self): super(AnonymousUseCaseTests, self).tearDownClass() self.selenium.quit() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/login/')) self.assertEquals(self.selenium.title, "Squire Learning Application") username_input = self.selenium.find_element_by_name("username") username_input.send_keys('super') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('super') self.selenium.find_element_by_xpath('//input[@value="Login"]').click() WebDriverWait(self.selenium, self.timeout).until( lambda driver: driver.find_element_by_tag_name('body')) self.assertEquals(self.selenium.current_url, '%s%s' % (self.live_server_url, '/hr/profile/')) def test_unsuccessful_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/login/')) self.assertEquals(self.selenium.title, "Squire Learning Application") username_input = self.selenium.find_element_by_name("username") username_input.send_keys('super') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('duper') self.selenium.find_element_by_xpath('//input[@value="Login"]').click() WebDriverWait(self.selenium, self.timeout).until( lambda driver: driver.find_element_by_tag_name('body')) self.assertEquals(self.selenium.current_url, '%s%s' % (self.live_server_url, '/login/')) self.assertTrue( self.selenium.page_source.find("Please try again.") > 0)
class StickToTopTest(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(3) self.n1 = Node.objects.create( title='TestNodeOne', description='The first test node' ) self.u1 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.super_user = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.super_user.is_superuser = True self.super_user.is_staff = True self.super_user.save() # Create 99 topics for i in range(1, 100): setattr( self, 't%s' % i, Topic.objects.create( title='Test Topic %s' % i, user=self.u1, content_raw='This is test topic __%s__' % i, node=self.n1 ) ) def tearDown(self): self.browser.quit() def test_stick_to_top_admin(self): self.browser.get(self.live_server_url + reverse("niji:index")) login(self.browser, 'super', '123') self.assertIn("Log out", self.browser.page_source) lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={"pk": lucky_topic1.pk})) self.browser.find_element_by_class_name('move-topic-up').click() up_level = WebDriverWait( self.browser, 10 ).until( expected_conditions.presence_of_element_located( (By.NAME, 'move-topic-up-level') ) ) up_level = Select(up_level) up_level.select_by_visible_text('1') time.sleep(1) self.browser.execute_script("$('.modal-confirm').click()") self.browser.get(self.live_server_url+reverse('niji:index')) first_topic_title = self.browser.find_elements_by_class_name('entry-link')[0].text self.assertEqual(first_topic_title, lucky_topic1.title)
class Fox(object): ''' Fox is an abstraction around Selenium web testing ''' def __init__(self): try: self.fox = WebDriver() except: print "No web server detected; skipping web tests" self.fox = None def login(self, page='/login', name='josh', password='******', t=5): self.get(page) WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[name=username]'))).send_keys(name) WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[name=password]'))).send_keys(password) WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input'))).click() def get(self, i): return self.fox.get(i) def click(self, css, t=5): return WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css))).click() def clickx(self, xpath, t=5): return WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.XPATH, xpath))).click() def click_last(self, css): e = self.fox.find_elements_by_css_selector('.modal-open .btn-primary')[-1] return e.click() def val(self, css, val, t=5): return WebDriverWait(self.fox, t).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css))).send_keys(val) def fill(self, form, field, value): css = '#{} [name={}]'.format(form, field) return self.val(css, value) def form(self, form, values): for k, v in values: self.fill(form, k, v) def wait_for_destroy(self, css, t=5): element = self.fox.find_element_by_css_selector(css) return WebDriverWait(self.fox, t).until(EC.staleness_of(element)) def close(self): if not self.fox: return self.fox.quit()
class LoginRegUrlSettingsTest(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(3) self.n1 = Node.objects.create( title='TestNodeOne', description='The first test node' ) self.u1 = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) self.t1 = Topic.objects.create( title='Test Topic 1', user=self.u1, content_raw='This is test topic __1__', node=self.n1, ) def tearDown(self): self.browser.quit() @override_settings(NIJI_LOGIN_URL_NAME="niji:reg") def test_login_url_name(self): self.browser.get(self.live_server_url+reverse("niji:index")) login_btn = self.browser.find_element_by_link_text("Log in") self.assertEqual(login_btn.get_attribute("href"), self.live_server_url+reverse("niji:reg")) self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": self.t1.pk})) login_link = self.browser.find_element_by_link_text("Login") self.assertEqual(login_link.get_attribute("href"), self.live_server_url+reverse("niji:reg")) @override_settings(NIJI_REG_URL_NAME="niji:login") def test_reg_url_name(self): self.browser.get(self.live_server_url+reverse("niji:index")) reg_btn = self.browser.find_element_by_link_text("Reg") self.assertEqual(reg_btn.get_attribute("href"), self.live_server_url+reverse("niji:login")) self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": self.t1.pk})) reg_link = self.browser.find_element_by_link_text("Create a New User") self.assertEqual(reg_link.get_attribute("href"), self.live_server_url+reverse("niji:login"))
class TunesFunctionalTestCase(LiveServerTestCase): @classmethod def setUpClass(self): self.user = User.objects.create(email="*****@*****.**") self.user.set_password("password") self.user.save() self.selenium = WebDriver() super(TunesFunctionalTestCase, self).setUpClass() @classmethod def tearDownClass(self): self.selenium.quit() super(TunesFunctionalTestCase, self).tearDownClass() def test_login_and_add_tune_info(self): """ Log in to the site, find a tune by name, and add some info about it. """ # Jill goes to the home page of the site and logs in self.selenium.get(self.live_server_url) self.selenium.find_element_by_css_selector("a#tuw-login").click() 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('password') self.selenium.find_element_by_css_selector('form#tuw-login button#tuw-submit-login').click() # she clicks the "Tunes" nav button self.selenium.find_element_by_css_selector('a#tuw-tunes').click() # and then clicks "Add a New Tune" self.selenium.find_element_by_css_selector('a#tuw-new-tune').click() # she searches for the word "Night" search_form = self.selenium.find_element_by_name("search") search_form.send_keys("Night") self.selenium.find_element_by_css_selector('form#tuw-login input#tuw-submit-search') # and sees a few options # "The Night Has a Thousand Eyes" # "Night in Tunisia" # "Night Train" # She selects "Night Train, and since we already have some info # about this tune in the database, she sees and partially # filled form # She adds what data she can about "Night Train" and # saves the form # She wants to add another tune to the database, so she clicks # "Edit Another Tune" # She searches for the word "Mood" # and sees a few options # "Mood Indigo" # "In a Sentimental Mood" # She selects "In a Sentimental Mood", and since there's no # info in the database about this tune yet, she see's a # completely empty form # She enters all the information she knows about this tune in # in the form and clicks save. # When shes's done, she goes to the home page to the home page # and sees the newly added tunes self.fail("FINISH THE TEST")
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
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://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()
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)
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)
class BaseStoreTest(StaticLiveServerTestCase): def by_id(self, id): return self.selenium.find_element_by_id(id) def by_css(self, selector: str, multiple: bool = False): if multiple: return self.selenium.find_elements_by_css_selector(selector) else: return self.selenium.find_element_by_css_selector(selector) def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(SELENIUM_WAIT_SEC) user = create_user(TEST_USER, TEST_PASSWORD, TEST_EMAIL) user.firstname = 'live' user.lastname = 'test' user.save() def tearDown(self): try: delete_user(TEST_USER) except Exception: pass super().tearDown() self.selenium.quit() def go_to(self, url_name: str, kwargs: Dict[str, str] = None) -> None: app_url = reverse(url_name, kwargs=kwargs) self.selenium.get('%s%s' % (self.live_server_url, app_url)) def go_to_app(self, app_id): self.go_to('app-detail', {'id': app_id}) def go_to_app_register(self): self.go_to('app-register') def go_to_app_upload(self): self.go_to('app-upload') def go_to_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/login/')) def login(self, user: str = TEST_USER, password: str = TEST_PASSWORD): self.go_to_login() user_input = self.selenium.find_element_by_name("login") user_input.send_keys(user) pass_input = self.selenium.find_element_by_name("password") pass_input.send_keys(password) self.selenium.find_element_by_xpath('//button[@type="submit"]').click() def assert_can_not_login(self): self.go_to('home') self.go_to_login() self.by_id('id_login').clear() self.by_id('id_login').send_keys('livetest') self.by_id('id_password').clear() self.by_id('id_password').send_keys('livetest') self.by_css('.auth-form button[type="submit"]').click() error = self.by_css('.auth-form .text-danger') self.assertTrue(error.is_displayed()) self.assertOnPage('account_login') def logout(self): self.findNavigationLink('account_logout').click() def wait_for(self, selector: str, then: Callable[[WebElement], None]) -> Any: element = WebDriverWait(self.selenium, SELENIUM_WAIT_SEC).until( EC.visibility_of_element_located((By.CSS_SELECTOR, selector))) return then(element) def wait_for_url(self, url: str) -> Any: WebDriverWait(self.selenium, SELENIUM_WAIT_SEC).until( EC.url_contains(url) ) def assertOnPage(self, url_name: str, kwargs: Dict[str, str] = None) -> None: parsed = urlparse(self.selenium.current_url) url = reverse(url_name, kwargs=kwargs) self.assertEqual(url, parsed.path) def findNavigationLink(self, url_name: str, kwargs: Dict[str, str] = None): route = reverse(url_name, kwargs=kwargs) return self.by_css('#navbar a[href="%s"]' % route)
# -*- coding: utf-8 -*- from selenium.webdriver.firefox.webdriver import WebDriver 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/addressbook/index.php") wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys("admin") wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys("secret") wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").click() wd.find_element_by_link_text("groups").click() wd.find_element_by_name("new").click() wd.find_element_by_name("group_name").click() wd.find_element_by_name("group_name").clear() wd.find_element_by_name("group_name").send_keys("adfadf") wd.find_element_by_name("group_header").click() wd.find_element_by_name("group_header").clear() wd.find_element_by_name("group_header").send_keys("adfadfadf")