def open_web_browser(self, browser): try: # Go to the correct domain self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title)
def simple_usage_generic_method(self, browser_name): try: self.driver = Driver(browser_name).get_driver() # create a drivers object self.driver.get(self.test_url) # open web browser on test web page self.driver.maximize_window() WebDriverWait(self.driver, 15).until(expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser_name).get_driver() # create a drivers object self.driver.get(self.test_url) # open web browser on test web page self.driver.maximize_window() WebDriverWait(self.driver, 15).until(expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False assert self.test_title in self.driver.title # verify webpage title elem = self.driver.find_element_by_name(self.test_name) # finds HTML element by name elem.clear() # clear the field elem.send_keys(self.test_str) # type test string in the search field elem.send_keys(Keys.RETURN) # press ENTER assert self.text_message not in self.driver.page_source # look for test message
def open_test_web_page(self, browser): # Open test web page and verify URL + Title try: self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title)
def open_web_browser(self, browser): try: # Launch webdriver on test web page + maximize window: self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.origin_window_name)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.origin_window_name)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.url, self.driver.current_url) self.assertEqual(self.origin_window_name, self.driver.title)
def open_web_browser(self, browser): try: # Launch webdriver on test web page + maximize window: self.driver = Driver(browser).get_driver() self.driver.maximize_window() self.driver.get(self.jscript_alerts_url) WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.jscript_alerts_title)) except TimeoutException as ec: print('\n', ec) is_webpage_loaded = False while not is_webpage_loaded: is_webpage_loaded = True try: if self.driver is not None: self.driver.quit() self.driver = Driver(browser).get_driver() self.driver.maximize_window() self.driver.get(self.jscript_alerts_url) WebDriverWait(self.driver, 5).until( expected_conditions.title_is( self.jscript_alerts_title)) except TimeoutException as ec: print('\n', ec) is_webpage_loaded = False finally: # Verify URL + Title self.assertEqual(self.jscript_alerts_url, self.driver.current_url) self.assertEqual(self.jscript_alerts_title, self.driver.title)
def __init__(self, parameters,logger ): ''' Constructor ''' Driver.__init__(self, parameters,logger ) self.last_write_count= 0 self.last_bytes_used_eth0= 0 self.last_bytes_used_wlan0= 0
def __init__(self, players, use_gui, iterations=1, switch_order=True, replay_deck=True, replay_destinations=True, print_debug=False, exception_on_bad_action=True, pause_between_turns=0, maximum_rounds=1000): Driver.__init__(self, players, use_gui, print_debug, exception_on_bad_action, pause_between_turns, maximum_rounds) self.iterations = iterations self.switch_order = switch_order self.replay_deck = replay_deck self.replay_destinations = replay_destinations self.original_players = deepcopy(self.players) self.wins = Counter({player.name: 0 for player in self.players}) # Create a list to use in the header of the CSV file, with Player 1, Player 2, etc.\. header_list = [] self.add_line_for_players(header_list, lambda player, idx: "Player %d" % (idx + 1)) self.add_line_for_players(header_list, lambda player, idx: "P%d Score" % (idx + 1)) self.add_line_for_players(header_list, lambda player, idx: "P%d Draws" % (idx + 1)) self.add_line_for_players( header_list, lambda player, idx: "P%d Connections" % (idx + 1)) self.add_line_for_players( header_list, lambda player, idx: "P%d Cars at End" % (idx + 1)) self.add_line_for_players( header_list, lambda player, idx: "P%d Points from Routes" % (idx + 1)) self.add_line_for_players( header_list, lambda player, idx: "P%d Points from Destinations" % (idx + 1)) self.add_line_for_players( header_list, lambda player, idx: "P%d Points lost from Destinations" % (idx + 1)) self.add_line_for_players( header_list, lambda player, idx: "P%d Win Rate" % (idx + 1)) header_list.append("Winner") # Create a name for the log file created. name = "i%d_s%s_deck%s_dest%s" % (iterations, "T" if switch_order else "F", "T" if replay_deck else "F", "T" if replay_destinations else "F") self.csv_log = CSVLog(name, *header_list)
def open_test_web_page(self, browser): # Open test web page and verify URL + Title self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until(EC.title_contains(self.test_title)) self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title)
def open_test_web_page(self, browser): # Open test web page and verify URL + Title self.driver = Driver(browser).get_driver() # Implicit wait self.driver.implicitly_wait(10) # seconds self.driver.get(self.test_url) self.driver.maximize_window() self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title)
def setUpClass(cls): ''' Runs only one time before all test method :return: ''' cls.driver = Driver('chrome').get_driver()
class TestParametrization(unittest.TestCase): """简单的unittest参数化""" url = ReadYaml(location.CONFIG_FILE).yaml_data()['URL'] phonenumber = ReadYaml(os.path.join( location.DATA_PATH, 'logindata.yaml')).yaml_data()['username'] password = ReadYaml(os.path.join(location.DATA_PATH, 'logindata.yaml')).yaml_data()['password'] param = list(zip(phonenumber, password)) def setUp(self): self.driver = Driver().driver() self.driver.get(self.url) self.driver.maximize_window() @parameterized.expand(param) @unittest.skip("测试强制跳过") # 装饰器调用时从下往上,执行时从上往下 def testLogin(self, username, password): """参数化测试登录""" LoginSys(self.driver, username, password).login() WebDriverWait(self.driver, 20, 0.5).until( ec.visibility_of_element_located(menu.MyWorkPanel)) self.assertEqual( self.driver.find_element(*menu.MyWorkPanel).is_displayed(), True) def tearDown(self): self.driver.quit()
def game_over(self, game): Driver.game_over(self, game) self.wins[self.winner] += 1 # Log results of game. scores = game.get_visible_scores() log_line = [] # Output each player and their scores. self.add_line_for_players(log_line, lambda player, idx: player.name) self.add_line_for_players(log_line, lambda player, idx: scores[player.name]) self.add_line_for_players( log_line, lambda player, idx: game.get_player_info(player).draws) self.add_line_for_players( log_line, lambda player, idx: game.get_player_info(player).connects) self.add_line_for_players( log_line, lambda player, idx: game.get_player_info(player).num_cars) self.add_line_for_players( log_line, lambda player, idx: game.get_player_info(player).get_route_points( )) self.add_line_for_players( log_line, lambda player, idx: game.get_player_info(player). get_destination_points()) self.add_line_for_players( log_line, lambda player, idx: game.get_player_info(player). get_destination_deductions()) self.add_line_for_players( log_line, lambda player, idx: "%.2f" % (self.wins[player.name] / float(sum(self.wins.values())))) log_line.append(game.is_game_over()[1]) # Add line to log. self.csv_log.append(*log_line)
def extract_performances(browser): url = "https://www.jameco.com/jameco/content/Mean-Well-Constant-Current-PFC-LED-Driver.html" browser.get(url) table = browser.find_element_by_class_name("table-container") result = [] current_driver = None for row in table.find_elements_by_tag_name("tr"): cells = row.find_elements_by_tag_name("td") if len(cells) == 1: model = cells[0].text.replace(" Series", "") if not re.match(r"(ELG|HLG|HVGC)-", model): current_driver = None continue current_driver = Driver(model, []) result.append(current_driver) print("done " + current_driver.model) continue if current_driver is None: continue if len(cells) == 8: product_code = cells[0].text if not product_code.endswith("B"): continue voltage = cells[3].text.split("-") min_voltage = float(voltage[0]) max_voltage = float(voltage[1]) current = float(cells[4].text) performance = Performance(current, min_voltage, max_voltage) current_driver.performances.append(performance) return result
def setUpClass(cls): cls.driver = Driver().driver() cls.driver.get(cls.url) cls.driver.maximize_window()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = 'https://www.seleniumeasy.com/test/' cls.test_title = 'Selenium Easy - Best Demo website to practice Selenium Webdriver Online' cls.simple_form_demo_xpath = '/html/body/div[3]/div/div[1]/div/div[2]/ul/li/ul/li[1]/ul/li[1]/a' cls.form_demo_title = 'Selenium Easy Demo - Simple Form to Automate using Selenium' cls.check_box_demo_xpath = '/html/body/div[2]/div/div[1]/div/div[2]/ul/li/ul/li[1]/ul/li[2]/a' cls.check_box_demo_title = 'Selenium Easy - Checkbox demo for automation using selenium' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): self.open_web_browser(browser) # Go to main menu and expand it self.driver.find_element( By.XPATH, '/html/body/div[3]/div/div[1]/div/div[2]/ul/li/ul/li[1]/a').click( ) time.sleep(1) # open simple form demo page simple_form_menu_item = WebDriverWait(self.driver, 10).\ until(expected_conditions.presence_of_element_located((By.XPATH, self.simple_form_demo_xpath))) simple_form_menu_item.click() time.sleep(1) self.assertEqual(self.form_demo_title, self.driver.title) # open check box demo page self.driver.find_element( By.XPATH, '/html/body/div[2]/div/div[1]/div/div[2]/ul/li/ul/li[1]/a').click( ) check_box_demo = WebDriverWait(self.driver, 10).\ until(expected_conditions.presence_of_element_located((By.XPATH, self.check_box_demo_xpath))) check_box_demo.click() time.sleep(1) self.assertEqual(self.check_box_demo_title, self.driver.title) # Go back to simple form demo page: self.driver.back() time.sleep(1) self.assertEqual(self.form_demo_title, self.driver.title) # Go back to main page: self.driver.back() time.sleep(1) self.assertEqual(self.test_title, self.driver.title) # Go forward to simple form demo page self.driver.forward() time.sleep(1) self.assertEqual(self.form_demo_title, self.driver.title) # Go forward to check box demo page self.driver.forward() time.sleep(1) self.assertEqual(self.check_box_demo_title, self.driver.title) def open_web_browser(self, browser): try: # Open test web site self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.url = 'http://demo.automationtesting.in/Frames.html' cls.window_name = 'Frames' cls.text_field_xpath = '/html/body/section/div/div/div/input' cls.single_iframe_btn_xpath = '/html/body/section/div[1]/div/div/div/div[1]/div/ul/li[1]/a' cls.single_iframe_id = 'singleframe' cls.multiple_iframes_btn_xpath = '/html/body/section/div[1]/div/div/div/div[1]/div/ul/li[2]/a' cls.multiple_frames_xpath = '/html/body/section/div[1]/div/div/div/div[2]/div[2]/iframe' cls.single_inside_multiple_iframe_xpath = '/html/body/section/div/div/iframe' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): self.open_web_browser(browser) # detect button single_iframe_btn = self.driver.find_element( By.XPATH, self.single_iframe_btn_xpath) # Click on 'Single iframe' button >>> # enter single iframe >>> single_iframe_btn.click() single_iframe = self.driver.find_element(By.ID, self.single_iframe_id) self.driver.switch_to.frame(single_iframe) # write text (single iframe) inside text field >>> # exit iframe txt_field = self.driver.find_element(By.XPATH, self.text_field_xpath) txt_field.send_keys('single iframe') time.sleep(1) self.assertEqual('single iframe', txt_field.get_attribute('value')) self.driver.switch_to.default_content() # detect button + click on it multiple_iframes_btn = self.driver.find_element( By.XPATH, self.multiple_iframes_btn_xpath) multiple_iframes_btn.click() # detect + switch to multiple iframe # implemented with wait due to slow performance of IE and FireFox wait = WebDriverWait(self.driver, 5) try: wait.until( expected_conditions.frame_to_be_available_and_switch_to_it( self.driver.find_element(By.XPATH, self.multiple_frames_xpath))) except TimeoutException as ec: print('\n', ec) print('\nTrying to refresh...') self.driver.refresh() wait.until( expected_conditions.frame_to_be_available_and_switch_to_it( self.driver.find_element(By.XPATH, self.multiple_frames_xpath))) # detect inner frame + switch to it inner_frame = self.driver.find_element( By.XPATH, self.single_inside_multiple_iframe_xpath) self.driver.switch_to.frame(inner_frame) # write text (single iframe) inside text field >>> # exit iframe try: WebDriverWait(self.driver, 5).until( expected_conditions.element_to_be_clickable( (By.XPATH, self.text_field_xpath))) except TimeoutException as ec: print('\n', ec) self.driver.switch_to.default_content() # detect inner frame + switch to it self.driver.switch_to.frame(inner_frame) WebDriverWait(self.driver, 5).until( expected_conditions.element_to_be_clickable( (By.XPATH, self.text_field_xpath))) txt_field = self.driver.find_element(By.XPATH, self.text_field_xpath) txt_field.send_keys('inner iframe') time.sleep(1) self.assertEqual('inner iframe', txt_field.get_attribute('value')) self.driver.switch_to.default_content() # click on iframe buttons back and forward: single_iframe_btn.click() time.sleep(1) multiple_iframes_btn.click() time.sleep(1) def open_web_browser(self, browser): try: # Launch webdriver on test web page + maximize window: self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.window_name)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.window_name)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: # Verify page title + url self.assertEqual(self.url, self.driver.current_url) self.assertEqual(self.window_name, self.driver.title) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.jscript_alerts_url = 'https://www.seleniumeasy.com/test/javascript-alert-box-demo.html' cls.jscript_alerts_title = 'Selenium Easy Demo - Automate All Scenarios' cls.jscript_alert_box_btn_xpath = '/html/body/div[2]/div/div[2]/div[1]/div[2]/button' cls.jscript_confirm_box_xpath = '/html/body/div[2]/div/div[2]/div[2]/div[2]/button' cls.configrm_demo_id = 'confirm-demo' cls.jscript_alert_box_prompt_xpath = '/html/body/div[2]/div/div[2]/div[3]/div[2]/button' cls.promt_demo_id = 'prompt-demo' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): self.open_web_browser(browser) try: # Test Java Script Alert Box self.alert_box_testing() # Test Java Script Confirm Box self.confirm_box_testing() # Test Java Script Prompt Box self.prompt_box_testing() except WebDriverException as ec: self.screen_shot() raise def alert_box_testing(self): # Open Java Script Alert Box self.driver.find_element(By.XPATH, self.jscript_alert_box_btn_xpath).click() alert_box = WebDriverWait(self.driver, 15).until( expected_conditions.alert_is_present()) # Verify alert box text and close the alert self.assertEqual('I am an alert box!', alert_box.text) time.sleep(1) alert_box.accept() # Back to the main window self.driver.switch_to.default_content() def confirm_box_testing(self): # Open Java Script Confirm Box self.driver.find_element(By.XPATH, self.jscript_confirm_box_xpath).click() confirm_box = WebDriverWait(self.driver, 15).until( expected_conditions.alert_is_present()) # Verify text >>> Hit OK button self.assertTrue('Press a button!' in confirm_box.text) time.sleep(1) confirm_box.accept() # Verify the result self.driver.switch_to.default_content() self.assertEqual( 'You pressed OK!', self.driver.find_element(By.ID, self.configrm_demo_id).text) time.sleep(1) # Open alert again self.driver.find_element(By.XPATH, self.jscript_confirm_box_xpath).click() confirm_box = WebDriverWait(self.driver, 15).until( expected_conditions.alert_is_present()) # Verify text >>> Hit CANCEL button self.assertTrue('Press a button!' in confirm_box.text) time.sleep(1) confirm_box.dismiss() # Verify the result self.driver.switch_to.default_content() self.assertEqual( 'You pressed Cancel!', self.driver.find_element(By.ID, self.configrm_demo_id).text) time.sleep(1) def prompt_box_testing(self): # Open prompt box and verify prompt text self.driver.find_element(By.XPATH, self.jscript_alert_box_prompt_xpath).click() prompt_box = WebDriverWait(self.driver, 15).until( expected_conditions.alert_is_present()) self.assertEqual('Please enter your name', prompt_box.text) time.sleep(1) # Cancel it and verify the result prompt_box.dismiss() self.driver.switch_to.default_content() self.assertEqual( '', self.driver.find_element(By.ID, self.promt_demo_id).text) time.sleep(1) # Open prompt again self.driver.switch_to.default_content() self.driver.find_element(By.XPATH, self.jscript_alert_box_prompt_xpath).click() prompt_box = WebDriverWait(self.driver, 15).until( expected_conditions.alert_is_present()) # Type name in prompt box time.sleep(1) prompt_box.send_keys('John Snow') time.sleep(1) # Accept it and verify text prompt_box.accept() self.driver.switch_to.default_content() self.assertEqual( 'You have entered \'John Snow\' !', self.driver.find_element(By.ID, self.promt_demo_id).text) time.sleep(1) def open_web_browser(self, browser): try: # Launch webdriver on test web page + maximize window: self.driver = Driver(browser).get_driver() self.driver.maximize_window() self.driver.get(self.jscript_alerts_url) WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.jscript_alerts_title)) except TimeoutException as ec: print('\n', ec) is_webpage_loaded = False while not is_webpage_loaded: is_webpage_loaded = True try: if self.driver is not None: self.driver.quit() self.driver = Driver(browser).get_driver() self.driver.maximize_window() self.driver.get(self.jscript_alerts_url) WebDriverWait(self.driver, 5).until( expected_conditions.title_is( self.jscript_alerts_title)) except TimeoutException as ec: print('\n', ec) is_webpage_loaded = False finally: # Verify URL + Title self.assertEqual(self.jscript_alerts_url, self.driver.current_url) self.assertEqual(self.jscript_alerts_title, self.driver.title) def screen_shot(self): """Take a Screen-shot of the webpage when test Failed.""" now = datetime.datetime.now() filename = 'screenshot-{}-{}.png'.format( self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) self.driver.save_screenshot(filename) print('\nScreenshot saved as {}'.format(filename)) @staticmethod def screenshots_collector(): ''' Collect all screenshots and put them into screenshots directory :return: ''' import os import shutil screenshots_folder = 'screenshots' if not os.path.exists(os.curdir + '\\screenshots'): os.mkdir(screenshots_folder) now = datetime.datetime.now() folder_name = '{}\\screenshots_{}'.format( screenshots_folder, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) files = os.listdir(os.curdir) for file in files: if '.png' in str(file): if not os.path.exists(os.curdir + '\\' + folder_name): os.mkdir(folder_name) shutil.move( file.split('\\')[-1], os.curdir + '\\' + folder_name) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.url = 'https://accounts.google.com/signup/v2/webcreateaccount?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&hl=en-GB&flowName=GlifWebSignIn&flowEntry=SignUp' cls.driver = None cls.title = 'Create your Google Account' cls.field_name = [ 'firstName', 'lastName', 'Username', 'Passwd', 'ConfirmPasswd' ] cls.user_account = { 'firstName': 'John', 'lastName': 'Snow', 'Username': '******', 'Passwd': 'The1AndOnly!', 'ConfirmPasswd': 'The1AndOnly!' } def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_opera(self): browser = 'opera' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_mozilla(self): browser = 'mozilla' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_edge(self): browser = 'edge' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_ie(self): browser = 'ie' self.generic_method(browser) def generic_method(self, browser): self.open_web_browser(browser) # Set predefine value for each field from # 'Create your Google Account' registration form: for name in self.field_name: element = self.driver.find_element_by_name(name) element.clear() element.send_keys(self.user_account[name]) # Verify all entered values: for name in self.field_name: expected = self.user_account[name] actual = self.driver.find_element_by_name(name).get_attribute( 'value') # print('expected: {}, actual: {}'.format(expected, actual)) # debug only self.assertEqual(expected, actual) # click on aye button in order to make # 'Confirm' field value visible: is_pswd_visible_btn = self.driver.find_element( By.XPATH, '/html/body/div[1]/div/div[2]/' 'div[1]/div[2]/form/div[2]/div/' 'div[1]/div[3]/div[2]/div') # verify that 'Confirm' field value is visible: expected = 'password' actual = self.driver.find_element_by_name( self.field_name[-1]).get_attribute("type") self.assertEqual(expected, actual) time.sleep(1) # click on aye button in order to make # 'Confirm' field value encrypted: is_pswd_visible_btn.click() # verify that 'Confirm' field value is visible: expected = 'text' actual = self.driver.find_element_by_name( self.field_name[-1]).get_attribute("type") self.assertEqual(expected, actual) time.sleep(1) # click on aye button in order to make # 'Confirm' field value encrypted: is_pswd_visible_btn.click() # verify that 'Confirm' field value is visible: expected = 'password' actual = self.driver.find_element_by_name( self.field_name[-1]).get_attribute("type") self.assertEqual(expected, actual) time.sleep(1) def take_screen_shot(self): """Take a Screen-shot of the webpage when test Failed.""" now = datetime.datetime.now() filename = 'screenshot-{}-{}.png'.format( self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) self.driver.save_screenshot(filename) print('\nScreenshot saved as {}'.format(filename)) def open_web_browser(self, browser): try: # Open web browser and verify page title: self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_contains(self.title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.url, self.driver.current_url) self.assertEqual(self.title, self.driver.title) @staticmethod def screenshots_collector(): ''' Collect all screenshots and put them into screenshots directory :return: ''' import os import shutil screenshots_folder = 'screenshots' if not os.path.exists(os.curdir + '\\screenshots'): os.mkdir(screenshots_folder) now = datetime.datetime.now() folder_name = '{}\\screenshots_{}'.format( screenshots_folder, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) files = os.listdir(os.curdir) for file in files: if '.png' in str(file): if not os.path.exists(os.curdir + '\\' + folder_name): os.mkdir(folder_name) shutil.move( file.split('\\')[-1], os.curdir + '\\' + folder_name) def tearDown(self): self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): cls.screenshots_collector() if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = 'http://automationpractice.com/index.php' cls.test_title = 'My Store' cls.women_text = 'Women' cls.women_link = 'http://automationpractice.com/index.php?id_category=3&controller=category' cls.women_title = 'Women - My Store' cls.dresses_text = 'Dres' cls.dresses_link = "http://automationpractice.com/index.php?id_category=8&controller=category" cls.dresses_title = 'Dresses - My Store' cls.t_shirts_text = 'T-shirts' cls.t_shirts_path = '//*[@id="block_top_menu"]/ul/li[3]/a' cls.t_shirts_link = "http://automationpractice.com/index.php?id_category=5&controller=category" cls.t_shirts_title = 'T-shirts - My Store' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None # @unittest.skip('not ready') def test_chrome(self): browser = 'chrome' self.generic_method(browser) # @unittest.skip('not ready') def test_ie(self): browser = 'ie' self.generic_method(browser) # @unittest.skip('not ready') def test_opera(self): browser = 'opera' self.generic_method(browser) # @unittest.skip('not ready') def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) # @unittest.skip('not ready') def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): try: # 1 open web page self.open_test_web_page(browser) # 2 click on 'Women' button and verify page title women_btn = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.LINK_TEXT, self.women_text))) women_btn.click() WebDriverWait(self.driver, 10).until(EC.title_contains(self.women_title)) self.assertEqual(self.women_title, self.driver.title) self.assertEqual(self.women_link, self.driver.current_url) # 3 dresses_btn = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable( (By.PARTIAL_LINK_TEXT, self.dresses_text))) dresses_btn.click() WebDriverWait(self.driver, 10).until(EC.title_contains(self.dresses_title)) self.assertEqual(self.dresses_title, self.driver.title) self.assertEqual(self.dresses_link, self.driver.current_url) # 4 t_shirts_btn = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, self.t_shirts_path))) t_shirts_btn.click() WebDriverWait(self.driver, 10).until(EC.title_contains(self.t_shirts_title)) self.assertEqual(self.t_shirts_title, self.driver.title) self.assertEqual(self.t_shirts_link, self.driver.current_url) except Exception as ec: print('\nERROR: {}'.format(ec)) self.take_screen_shot() raise def open_test_web_page(self, browser): # Open test web page and verify URL + Title self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until(EC.title_contains(self.test_title)) self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def take_screen_shot(self): """Take a Screen-shot of the webpage when test Failed.""" now = datetime.datetime.now() filename = 'screenshot-{}-{}.png'.format( self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) self.driver.save_screenshot(filename) print('\nScreenshot saved as {}'.format(filename)) def screenshots_collector(self): ''' Collect all screenshots and put them into screenshots directory :return: ''' import os import shutil screenshots_folder = 'screenshots' if not os.path.exists(os.curdir + '\\screenshots'): os.mkdir(screenshots_folder) now = datetime.datetime.now() folder_name = '{}\\screenshots_{}_{}'.format( screenshots_folder, self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) files = os.listdir(os.curdir) for file in files: if '.png' in str(file): if not os.path.exists(os.curdir + '\\' + folder_name): os.mkdir(folder_name) shutil.move( file.split('\\')[-1], os.curdir + '\\' + folder_name) def tearDown(self): self.screenshots_collector() self.driver.stop_client() self.driver.close() @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = 'https://jqueryui.com/droppable/' cls.test_title = 'Droppable | jQuery UI' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): self.open_web_page(browser) iframe = self.driver.find_element( By.XPATH, '/html/body/div[1]/div[2]/div/div[1]/iframe') self.driver.switch_to.frame(iframe) try: source = WebDriverWait(self.driver, 5).until( expected_conditions.presence_of_element_located( (By.ID, 'draggable'))) target = WebDriverWait(self.driver, 5).until( expected_conditions.presence_of_element_located( (By.ID, 'droppable'))) except Exception as ec: self.take_screen_shot() raise self.assertEqual("Drop here", target.text) time.sleep(2) actions = ActionChains(self.driver) actions.drag_and_drop(source, target).perform() time.sleep(2) try: self.assertEqual("Dropped!", target.text) except Exception as e: print('\nERROR: ', e.args) self.take_screen_shot() raise def open_web_page(self, browser): try: # Open web browser and verify page title: self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def take_screen_shot(self): """Take a Screen-shot of the webpage when test Failed.""" now = datetime.datetime.now() filename = 'screenshot-{}-{}.png'.format( self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) self.driver.save_screenshot(filename) print('\nScreenshot saved as {}'.format(filename)) @staticmethod def screenshots_collector(): ''' Collect all screenshots and put them into screenshots directory :return: ''' import os import shutil screenshots_folder = 'screenshots' if not os.path.exists(os.curdir + '\\screenshots'): os.mkdir(screenshots_folder) now = datetime.datetime.now() folder_name = '{}\\screenshots_{}'.format( screenshots_folder, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) files = os.listdir(os.curdir) for file in files: if '.png' in str(file): if not os.path.exists(os.curdir + '\\' + folder_name): os.mkdir(folder_name) shutil.move( file.split('\\')[-1], os.curdir + '\\' + folder_name) def tearDown(self): self.driver.stop_client() self.driver.close() @classmethod def tearDownClass(cls): cls.screenshots_collector() if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = "https://www.google.com/doodles/" cls.test_title = 'Google Doodles' cls.id = 'passwd-id' cls.name = 'passwd' cls.xpath = '//input[@id=\'passwd-id\']' cls.search_field_name = 'q' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.using_find_element_func(browser) def test_ie(self): browser = 'ie' self.using_find_element_func(browser) def test_edge(self): browser = 'edge' self.using_find_element_func(browser) def test_opera(self): browser = 'opera' self.using_find_element_func(browser) def test_mozilla(self): browser = 'mozilla' self.using_find_element_func(browser) def using_find_element_func(self, browser): self.open_web_browser(browser) # 1. find element by id. # If nothing can be found, a NoSuchElementException will be raised. with self.assertRaises(NoSuchElementException): self.driver.find_element_by_id(self.id) # 2. find element by name. # If nothing can be found, a NoSuchElementException will be raised. with self.assertRaises(NoSuchElementException): self.driver.find_element_by_name(self.name) # 3. find element by xpath. # If nothing can be found, a NoSuchElementException will be raised. with self.assertRaises(NoSuchElementException): self.driver.find_element_by_xpath(self.xpath) # 4. Send keys. # It is possible to call send_keys on any element, # which makes it possible to test keyboard shortcuts such as those used on GMail. search_field = self.driver.find_element_by_name(self.search_field_name) search_field.send_keys('python') time.sleep(2) search_field.send_keys(" and some", Keys.ARROW_LEFT) time.sleep(2) search_field.send_keys(" and some", Keys.ARROW_RIGHT) time.sleep(2) # You can easily clear the contents of a text field # or textarea with the clear method search_field.clear() def open_web_browser(self, browser): try: # Open web browser and verify page title: self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def tearDown(self): self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class SimpleUsage(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = "http://www.python.org" cls.test_name = 'q' cls.test_str = "pycon" cls.text_message = "No results found." cls.test_title = "Welcome to Python.org" def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): self.simple_usage_generic_method('chrome') def test_edge(self): self.simple_usage_generic_method('edge') def test_ie(self): self.simple_usage_generic_method('ie') def test_mozilla(self): self.simple_usage_generic_method('mozilla') def test_opera(self): self.simple_usage_generic_method('opera') def simple_usage_generic_method(self, browser_name): try: self.driver = Driver(browser_name).get_driver() # create a drivers object self.driver.get(self.test_url) # open web browser on test web page self.driver.maximize_window() WebDriverWait(self.driver, 15).until(expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser_name).get_driver() # create a drivers object self.driver.get(self.test_url) # open web browser on test web page self.driver.maximize_window() WebDriverWait(self.driver, 15).until(expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False assert self.test_title in self.driver.title # verify webpage title elem = self.driver.find_element_by_name(self.test_name) # finds HTML element by name elem.clear() # clear the field elem.send_keys(self.test_str) # type test string in the search field elem.send_keys(Keys.RETURN) # press ENTER assert self.text_message not in self.driver.page_source # look for test message def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
def setUpClass(cls): cls.driver = Driver('mozilla').get_driver() cls.test_url = 'https://www.ultimateqa.com/automation/' cls.test_title = 'Automation Practice - Ultimate QA'
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = 'http://newtours.demoaut.com/' cls.test_title = 'Welcome: Mercury Tours' cls.login_btn_name = 'login' cls.test_login_url = 'http://newtours.demoaut.com/mercurysignon.php' cls.test_login_title = 'Sign-on: Mercury Tours' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): # Allocate LOGIN button and click on it self.open_test_web_page(browser) login_btn = self.driver.find_element(By.NAME, self.login_btn_name) login_btn.click() time.sleep(1) # wait up to 10 secs for the url to change or else `TimeOutException` is raised. wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.title_is(self.test_login_title)) # Verify that you are on the LOGIN web page new_url = self.driver.current_url self.assertTrue(self.test_url in new_url) self.assertEqual(self.test_login_title, self.driver.title) time.sleep(1) # Try to allocate non existing object with self.assertRaises(NoSuchElementException): self.driver.find_element(By.NAME, 'some_name') def open_test_web_page(self, browser): # Open test web page and verify URL + Title try: self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = 'http://automationpractice.com/index.php' cls.test_title = 'My Store' cls.header_text = 'Automation Practice Website' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None # @unittest.skip('not ready') def test_chrome(self): browser = 'chrome' self.generic_method(browser) # @unittest.skip('not ready') def test_ie(self): browser = 'ie' self.generic_method(browser) # @unittest.skip('not ready') def test_opera(self): browser = 'opera' self.generic_method(browser) # @unittest.skip('not ready') def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) # @unittest.skip('not ready') def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): try: self.open_test_web_page(browser) header = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'h1'))) self.assertEqual(self.header_text, header.text) except Exception as ec: print('\nERROR: {}'.format(ec)) self.take_screen_shot() raise def open_test_web_page(self, browser): # Open test web page and verify URL + Title self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until(EC.title_contains(self.test_title)) time.sleep(1) self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def take_screen_shot(self): """Take a Screen-shot of the webpage when test Failed.""" now = datetime.datetime.now() filename = 'screenshot-{}-{}.png'.format( self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) self.driver.save_screenshot(filename) print('\nScreenshot saved as {}'.format(filename)) def screenshots_collector(self): ''' Collect all screenshots and put them into screenshots directory :return: ''' import os import shutil screenshots_folder = 'screenshots' if not os.path.exists(os.curdir + '\\screenshots'): os.mkdir(screenshots_folder) now = datetime.datetime.now() folder_name = '{}\\screenshots_{}_{}'.format( screenshots_folder, self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) files = os.listdir(os.curdir) for file in files: if '.png' in str(file): if not os.path.exists(os.curdir + '\\' + folder_name): os.mkdir(folder_name) shutil.move( file.split('\\')[-1], os.curdir + '\\' + folder_name) def tearDown(self): self.screenshots_collector() self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.url = 'http://demo.automationtesting.in/Windows.html' cls.new_url = 'http://www.sakinalium.in/' cls.origin_window_name = 'Frames & windows' cls.new_window_name = 'Sakinalium | Home' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_ie(self): browser = 'ie' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_opera(self): browser = 'opera' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_mozilla(self): browser = 'mozilla' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def test_edge(self): browser = 'edge' try: self.generic_method(browser) except Exception: self.take_screen_shot() raise def generic_method(self, browser): self.open_web_browser(browser) # Get current window handle: main_window = self.driver.current_window_handle try: # Hit on click button and switch to new window: btn = WebDriverWait(self.driver, 5).until( expected_conditions.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div/div/div[2]/div[1]/a/button'))) btn.click() time.sleep(1) # New tabs will be the last object in window_handles: self.driver.switch_to.window(self.driver.window_handles[-1]) self.driver.maximize_window() except WebDriverException as ec: print('\n', ec) self.screen_shot() raise # Wait for element to appear. # Implemented due to a very slow performance of IE and FireFox. try: WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.new_window_name)) except TimeoutException as ec: is_loaded = False while not is_loaded: is_loaded = True try: print('\n', ec) self.driver.close() time.sleep(1) self.driver.switch_to.window(main_window) btn.click() self.driver.switch_to.window(self.driver.window_handles[-1]) self.driver.maximize_window() WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.new_window_name)) except WebDriverException as ec: print('\n', ex) is_loaded = False # Verify new tab name + url: self.assertEqual(self.new_window_name, self.driver.title) self.assertEqual(self.new_url, self.driver.current_url) time.sleep(1) # Get a new window handle: new_window = self.driver.current_window_handle # Switch back to original window: self.driver.switch_to.window(main_window) self.assertEqual(self.origin_window_name, self.driver.title) self.assertEqual(self.url, self.driver.current_url) time.sleep(1) # Switch to a new tab: self.driver.switch_to.window(new_window) self.assertEqual(self.new_window_name, self.driver.title) self.assertEqual(self.new_url, self.driver.current_url) time.sleep(1) def open_web_browser(self, browser): try: # Launch webdriver on test web page + maximize window: self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.origin_window_name)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.origin_window_name)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.url, self.driver.current_url) self.assertEqual(self.origin_window_name, self.driver.title) def screen_shot(self): """Take a Screen-shot of the webpage when test Failed.""" now = datetime.datetime.now() filename = 'screenshot-{}-{}.png'.format(self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) self.driver.save_screenshot(filename) print('\nScreenshot saved as {}'.format(filename)) @staticmethod def screenshots_collector(): ''' Collect all screenshots and put them into screenshots directory :return: ''' import os import shutil screenshots_folder = 'screenshots' if not os.path.exists(os.curdir + '\\screenshots'): os.mkdir(screenshots_folder) now = datetime.datetime.now() folder_name = '{}\\screenshots_{}'.format(screenshots_folder, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S')) files = os.listdir(os.curdir) for file in files: if '.png' in str(file): if not os.path.exists(os.curdir + '\\' + folder_name): os.mkdir(folder_name) shutil.move(file.split('\\')[-1], os.curdir + '\\' + folder_name) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): cls.screenshots_collector() if cls.driver is not None: cls.driver.quit()
def setUp(self): self.driver = Driver().driver() self.driver.get(self.url) self.driver.maximize_window()
def __init__(self): self.driver = Driver.get_driver()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_title = 'Example Domain' cls.test_url = "http://www.example.com/" cls.cookie = {'name': 'foo', 'value': 'bar'} cls.page_title_xpath = '/html/body/div/h1' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): self.open_web_browser(browser) # Now set the cookie. This one's valid for the entire domain self.driver.add_cookie(self.cookie) # Verify the imported cookies self.assertTrue( self.cookie['name'] == self.driver.get_cookies()[0]['name']) self.assertTrue( self.cookie['value'] == self.driver.get_cookies()[0]['value']) def open_web_browser(self, browser): try: # Go to the correct domain self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 5).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()
class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = None cls.test_url = 'http://automationpractice.com/index.php' cls.search_id = 'search_query_top' cls.test_title = 'My Store' cls.search_item = 'shirt' cls.search_btn_name = 'submit_search' cls.search_title = 'Search - My Store' cls.expected_search_result = 'SEARCH "SHIRT" \n1 result has been found.' cls.search_title_xpath = '/html/body/div/div[2]/div/div[3]/div[2]/h1' def setUp(self): if self.driver is not None: self.driver.quit() self.driver = None def test_chrome(self): browser = 'chrome' self.generic_method(browser) def test_ie(self): browser = 'ie' self.generic_method(browser) def test_opera(self): browser = 'opera' self.generic_method(browser) def test_mozilla(self): browser = 'mozilla' self.generic_method(browser) def test_edge(self): browser = 'edge' self.generic_method(browser) def generic_method(self, browser): self.open_test_web_page(browser) # test for non existing item with self.assertRaises(NoSuchElementException): self.driver.find_element(By.ID, 'noname') # allocate search field search = self.driver.find_element(By.ID, self.search_id) # verify that search field is empty self.assertEqual('', search.get_attribute('value')) # enter search item and verify field value search.send_keys(self.search_item) self.assertEqual(self.search_item, search.get_attribute('value')) # hit on search button search_btn = self.driver.find_element(By.NAME, self.search_btn_name) search_btn.click() # wait till search page is loaded WebDriverWait(self.driver, 10).until( expected_conditions.presence_of_element_located( (By.XPATH, self.search_title_xpath))) time.sleep(1) search_header = self.driver.find_element(By.XPATH, self.search_title_xpath) # Verify search results # \xa0 is actually non-breaking space in Latin1 (ISO 8859-1), also chr(160). # You should replace it result = search_header.text.replace(u'\xa0', u'') self.assertListEqual(list(self.expected_search_result.lower().split()), list(result.strip().lower().split())) def open_test_web_page(self, browser): # Open test web page and verify URL + Title try: self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False while not is_loaded: is_loaded = True try: self.tearDown() self.driver = Driver(browser).get_driver() self.driver.get(self.test_url) self.driver.maximize_window() WebDriverWait(self.driver, 15).until( expected_conditions.title_is(self.test_title)) except TimeoutException as ec: print('\n', ec) is_loaded = False finally: self.assertEqual(self.test_url, self.driver.current_url) self.assertEqual(self.test_title, self.driver.title) def tearDown(self): for handle in self.driver.window_handles: self.driver.switch_to.window(handle) self.driver.stop_client() self.driver.close() time.sleep(1) @classmethod def tearDownClass(cls): if cls.driver is not None: cls.driver.quit()