class LoginTests(unittest.TestCase): log = custom_log(logging.INFO) base_url = 'https://learn.letskodeit.com/p/practice' driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(5) test_obj = lp(driver) @pytest.mark.run(order=2) def test_validLogin(self): LoginTests.driver.get(LoginTests.base_url) LoginTests.test_obj.login('*****@*****.**', 'abcabc') result = LoginTests.test_obj.verifyLoginSuccess() assert result == True LoginTests.driver.quit() @pytest.mark.run(order=1) def test_invalidLogin(self): LoginTests.driver.get(LoginTests.base_url) # obj_test2 = lp(LoginTests.driver) LoginTests.test_obj.login('*****@*****.**', 'abcabc') result = LoginTests.test_obj.verifyLoginFailed() assert result == True
class LoginPage(SeleniumDriver): log = custom_log(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #locators _login_link = '//a[contains(text(),"Login")]' _email_field = 'user_email' _pass_field = 'user_password' _login_button = 'commit' _search_course_field = 'search-courses' _login_error = '//div[contains(text(),"Invalid email or password")]' def clickLoginLink(self): # self.getLoginLink().click() self.element_click(LoginPage._login_link, locatortype='xpath') def enterUserName(self, username): # self.getEmailField().send_keys(username) self.enter_text(username,LoginPage._email_field) def enterPassword(self, password): # self.getPassField().send_keys(password) self.enter_text(password, LoginPage._pass_field) def clickLoginButton(self): # self.getLoginButton().click() self.element_click(LoginPage._login_button,locatortype='name') def verifyLoginSuccess(self): result = self.is_element_present(LoginPage._search_course_field) return result def verifyLoginFailed(self): result = self.is_element_present(LoginPage._login_error,locatortype='xpath') return result def clearLoginFields(self): emailField = self.get_element(LoginPage._email_field) emailField.clear() passField = self.get_element(LoginPage._pass_field) passField.clear() def login(self, username="", password=""): self.clickLoginLink() self.enterUserName(username) self.enterPassword(password) self.clickLoginButton()
class TestRunStatus(SeleniumDriver): log= custom_log(logging.INFO) def __init__(self,driver): super().__init__(driver) self.resultlist=[] def setResult(self,result,resultMessage): try: if result is not None: if result: self.resultlist.append('PASS') self.log.info('### VERIFICATION SUCCESS') else: self.resultlist.append('FAIL') self.log.info('### VERIFICATION FAILED '+resultMessage) self.screenshot(resultMessage) else: self.resultlist.append('FAIL') self.log.info('### VERIFICATION FAILED ' + resultMessage) self.screenshot(resultMessage) except: self.resultlist.append('FAIL') self.log.info('### EXCEPTION OCCURED!!!') def mark(self,result,resultMessage): self.setResult(result,resultMessage) def markFinal(self,testcase, result, resultMessage): self.setResult(result,resultMessage) if 'FAIL' in self.resultlist: self.log.error(testcase + '### TEST FAILED') self.resultlist.clear() assert True == False else: self.log.info(testcase + '### TEST PASSED') self.resultlist.clear() assert True == True
class TestResult(SeleniumDriver): def __init__(self, driver): super(TestResult, self).__init__(driver) # instance to logger class log = cl.custom_log(logging.DEBUG) # list to store the test status test_status_list = [] def test_status(self, result, result_message): if result is not None: if result: self.test_status_list.append(True) self.log.info( str(result) + " " + "added into the list" + result_message) else: self.test_status_list.append(False) self.log.info( str(result) + " " + "added into the list" + result_message) self.take_screenshots(result_message) allure.attach(self.driver.get_screenshot_as_png(), name=result_message, attachment_type=AttachmentType.png) else: self.log.error("No result was available" + result_message) self.take_screenshots(result_message) def mark(self, result, result_message): self.test_status(result, result_message) def mark_final(self, result, result_message): self.test_status(result, result_message) print("*" * 20) print(self.test_status_list) if False in self.test_status_list: # clears the list values self.test_status_list.clear() return False else: # clears the list values self.test_status_list.clear() return True
class SeleniumDriver(): log = custom_log(logging.INFO) def __init__(self, driver): self.driver = driver ################################################################## def launch_url(self, url): ''' launch the url paramater: URL return value: None ''' try: self.driver.get(url) SeleniumDriver.log.info('URL: "{}" launch: Pass '.format(url)) except Exception as e: SeleniumDriver.log.info( 'URL: "{}" launch: fail... Exception error: "{}" '.format( url, e)) ################################################################## def verify_title(self, text): ''' verify the title paramater: title text to verify return value: True or False ''' text = text.lower() captured_title = self.driver.title if text == captured_title.lower(): SeleniumDriver.log.info( 'title match - pass, title from the browser is ' + captured_title) return True else: SeleniumDriver.log.info( 'title match - fail, title from the browser "{}", excepted browser title: "{}" ' .format(captured_title, text)) return False ################################################################## def get_by_type(self, locatortype): ''' function to get locator type parameter: locator type like ID,XPATH, CSS.. et return value: by. ID, by.XPATH..etc ''' locatortype = locatortype.lower() if locatortype == 'id': return By.ID elif locatortype == 'xpath': return By.XPATH elif locatortype == 'css': return By.CSS_SELECTOR elif locatortype == 'name': return By.NAME elif locatortype == 'link': return By.LINK_TEXT elif locatortype == 'partiallink': return By.PARTIAL_LINK_TEXT elif locatortype == 'tagname': return By.TAG_NAME else: SeleniumDriver.log.info( 'locator type: "{}" is invalid'.format(locatortype)) return None ################################################################## def get_element(self, locator, locatortype='id'): ''' enter the text in the editbox field parameters: locatortype, locator return value: element or None ''' element = None try: by_value = self.get_by_type(locatortype) element = self.driver.find_element(by_value, locator) SeleniumDriver.log.info( 'Element with locator "{}" using locator type "{}" found status: Pass' .format(locator, locatortype)) return element except NoSuchElementException as e: SeleniumDriver.log.info( 'Element with locator "{}" using locator type "{}" found status: Fail, ' 'exception message: "{}"'.format(locator, locatortype, str(e))) except Exception as e: SeleniumDriver.log.info( 'Element with locator "{}" using locator type "{}" found status: Fail, ' 'exception message: "{}"'.format(locator, str(e))) return element ################################################################## def enter_text(self, data, locator, locatorid='id'): ''' enter the value in the element :parameter: data, locator, locator id return: ''' try: element = self.get_element(locator, locatorid) element.send_keys(data.strip()) SeleniumDriver.log.info( 'Data "{}" enter status on the element with locator "{}" using locator type "{}" : pass' .format(data.strip(), locator, locatorid)) except Exception as e: SeleniumDriver.log.info( 'Data "{}" enter status on the element with locator "{}" using locator type "{}" : fail, ' 'exception message: "{}"'.format(data.strip(), locator, locatorid, str(e))) ################################################################## def wait_for_element(self, locator, timeout=10, locatortype='ID', poll_frequency=1): ''' Explicit wait paramters: locator, locator type, timeout return: ''' element = None try: locatortype = locatortype.lower() byType = self.get_by_type(locatortype) wait = WebDriverWait(self.driver, timeout, poll_frequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until(ec.element_to_be_clickable((byType, locator))) SeleniumDriver.log.info( 'Element with locator "{}" locator type "{}" appeared on the web page' .format(locator, locatortype)) except Exception as e: SeleniumDriver.log.info( 'Element with locator "{}" ' 'using locator type "{}" is not appeared on the web page, exception message: "{}"' .format(locator, locatortype, str(e))) print_stack() return element ################################################################## def element_click(self, locator, locatortype='id'): ''' element to click :param locator: element locator :param locatortype: element locator type :return: ''' try: element = self.get_element(locator, locatortype) element.click() SeleniumDriver.log.info( 'Element with locator "{}" using locator type "{}" click status : Pass' .format(locator, locatortype)) except Exception as e: SeleniumDriver.log.info( 'Element with locator "{}" ' 'using locator type "{}" click status : fail, exception message :"{}"' .format(locator, locatortype, str(e))) print_stack() ################################################################## def is_element_present(self, locator, locatortype='id'): ''' method to verify element is present :param locator: :param locatortype: :return: True or False ''' try: element = self.get_element(locator, locatortype) if element is not None: SeleniumDriver.log.info( 'Element with locator "{}" ' 'using locator type "{}" is present '.format( locator, locatortype)) return True else: SeleniumDriver.log.info( 'Element with locator "{}" ' 'using locator type "{}" is not present '.format( locator, locatortype)) return False except: print_stack() return False ################################################################## def element_clear(self, locator, locatortype='id'): ''' element to clear :param locator: element locator :param locatortype: element locator type :return: ''' try: element = self.get_element(locator, locatortype) element.clear() SeleniumDriver.log.info( 'Element with locator "{}" using locator type "{}" clear status : Pass' .format(locator, locatortype)) except Exception as e: SeleniumDriver.log.info( 'Element with locator "{}" ' 'using locator type "{}" clear status : fail, exception message :"{}"' .format(locator, locatortype, str(e))) print_stack()
class SeleniumDriver: log = cl.custom_log(logging.DEBUG) def __init__(self, driver): self.driver = driver def take_screenshots(self, message): screenshots_directory = "..\screenshots\\" current_directory = os.path.dirname(__file__) # this gives the 'Name' for the screenshot file screenshot_filename = os.path.join(screenshots_directory, message + ".png") # this gives the 'Path' for the screenshot file : place where screenshots are saved destination_filename = os.path.join(current_directory, screenshot_filename) # path where the screenshots directory should be available new_directory_path = os.path.join(current_directory, screenshots_directory) # in case... if the screenshots directory is deleted, the below code creates a new 'Screenshots' directory if not (os.path.exists(new_directory_path)): os.mkdir(new_directory_path) # take screenshot self.driver.save_screenshot(destination_filename) def get_by_type(self, locator_type): locator_type = locator_type.lower() if locator_type == 'id': return By.ID if locator_type == 'name': return By.NAME if locator_type == 'classname': return By.CLASS_NAME if locator_type == 'linktext': return By.LINK_TEXT if locator_type == 'css': return By.CSS_SELECTOR if locator_type == 'xpath': return By.XPATH else: self.log.info("Locator Type" + locator_type + "not correct / supported") # self.log.info("Locator Type"+locator_type+"not correct / supported") return False def is_element_present(self, locator_type, locator): _by_type = self.get_by_type(locator_type) element = self.driver.find_element(_by_type, locator) if element is not None: self.log.info("is_element_present : Element Found") return True else: self.log.info("is_element_present : Element Not Found") return False def get_element(self, locator_type, locator): _by_type = self.get_by_type(locator_type) element = self.driver.find_elements(_by_type, locator) if element is not None: self.log.info("Element Found") else: self.log.info("Element Not Found") return element def enter_data_into_text_field(self, locator_type, locator, value): _by_type = self.get_by_type(locator_type) element = self.driver.find_element(_by_type, locator) if element is not None: self.log.info("Element Found") else: self.log.info("Element Not Found") element.send_keys(value) def keyboard_enter(self, locator_type, locator, value=""): _by_type = self.get_by_type(locator_type) element = self.driver.find_element(_by_type, locator) if element is not None: self.log.info("Element Found") element.send_keys(value, Keys.ENTER) return True else: self.log.info("Element not found") return False def element_click(self, locator_type, locator): _by_type = self.get_by_type(locator_type) element = self.driver.find_element(_by_type, locator) if element is not None: self.log.info("Element Clicked") element.click() else: self.log.info("Element could not be clicked") def clear_field(self, locator_type, locator): _by_type = self.get_by_type(locator_type) try: element = self.driver.find_element(_by_type, locator) element.clear() except NoSuchElementException: self.log.info("Element was not found") def validate_page_title(self, verify_page_title): page_title = self.driver.title print(verify_page_title) print(page_title) if verify_page_title == page_title: return True else: return False def wait_till_element_appears(self, locator_type, locator, timeout=30, poll_frequency=.5): try: by_type = self.get_by_type(locator_type) wait = WebDriverWait(self.driver, timeout, poll_frequency) wait.until(EC.element_to_be_clickable((by_type, locator))) except: self.log.info("Element not found ... till 30 seconds timeout") def wait_till_circle_disappears(self, timeout=30, poll_frequency=.5): try: by_type = "xpath" wait = WebDriverWait(self.driver, timeout, poll_frequency) locator = "//div[@class='loading-wrap']/img" # locator = ".loading-wrap>img" # Checking for Loading Circle ... # Loading Circle found ... polling till it disappears wait.until(EC.invisibility_of_element_located((by_type, locator))) except: # self.log.info.error("Loading Circle found ... till 30 seconds timeout") self.log.info("Loading Circle found ... till 30 seconds timeout") return None def wait_till_loading_disappears(self, timeout=30, poll_frequency=.5): try: by_type = "xpath" wait = WebDriverWait(self.driver, timeout, poll_frequency) locator = "//div/*[name()='svg']/*[name()='rect']" # Checking for Loading interface bar ... # Loading Interface bar found ... polling till it disappears wait.until(EC.invisibility_of_element_located((by_type, locator))) except: # self.log.info.error("Loading Circle found ... till 30 seconds timeout") self.log.info("Loading Circle found ... till 30 seconds timeout") return None def web_scroll(self, direction="up"): if direction == "up": self.driver.execute_script("window.scrollBy(0, -1000);") if direction == "down": self.driver.execute_script("window.scrollBy(0, 1000);")