class Util(object): log = cl.customLogger(logging.INFO) def sleep(self, sec, info=""): """ Put the program to wait for the specified amount of time """ if info is not None: self.log.info("Wait :: '" + str(sec) + "' seconds for " + info) try: time.sleep(sec) except InterruptedError: traceback.print_stack() def getAlphaNumeric(self, length, type='letters'): """ Get random string of characters Parameters: length: Length of string, number of characters string should have type: Type of characters string should have. Default is letters Provide lower/upper/digits for different types """ alpha_num = '' if type == 'lower': case = string.ascii_lowercase elif type == 'upper': case = string.ascii_uppercase
class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) #log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # locators _login_link = "guest-login-button" _email_field = "id_username" _password_field = "id_password" _loginbutton = "login_button" def clickLoginLink(self): self.elementClick(self._login_link, locatorType="id") def enterEmail(self, email): self.sendKeys(email, self._email_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._loginbutton, locatorType="id") print("summaya") def login(self, email="", password=""): self.clickLoginLink() self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccessfull(self): result = self.isElementPresent("//*[@id='user-profile-pic']", locatorType="xpath") #userIcon=driver.find_element(By.ID,"user-profile-pic") return result def verifyLoginFailed(self): result = self.isElementPresent("//*[@id='login-form']/div[1]/p", locatorType="xpath") return result def verifyAfterlogin_Recent_From_My_places(self): result = self.isElementPresent( "//*[@id='recentNewsCity']/div/h5/text()", locatorType='xpath') return result def verifyLoginTitle(self): return self.verifyPageTitle("NewsGallery | People's Own Media") def verifybeforeLogin(self): return self.isElementPresent( "//*[@id='wrapper']/div[3]/div/div[1]/div/div[1]/div/h3", locatorType="xpath")
class LoggingDemo2(): log = cl.customLogger(logging.DEBUG) def method1(self): self.log.debug('Debug Message') self.log.info('info message') self.log.warning('warn message') self.log.error('error message') self.log.critical('critical message') def method2(self): m2Log = cl.customLogger(logging.INFO) m2Log.debug('Debug Message') m2Log.info('info message') m2Log.warning('warn message') m2Log.error('error message') m2Log.critical('critical message') def method3(self): m3Log = cl.customLogger(logging.INFO) m3Log.debug('Debug Message') m3Log.info('info message') m3Log.warning('warn message') m3Log.error('error message') m3Log.critical('critical message')
class FindByIdName(unittest.TestCase): log = cl.customLogger(logging.DEBUG) def setUp(self): # setup and declaration of inputs required for sel and unittest to do its job # --------- Edit inputs here: ------------- baseUrl = "https://letskodeit.teachable.com/pages/practice" self.elementIdToFind = "name" self.elementNameToFind = "show-hide" # --------- Do not edit below this line: ------------- self.driver = webdriver.Firefox() self.driver.get(baseUrl) self.log.debug('Setup Complete') def testIdFind(self): #simple find by Id test, outputs message on completion elementById = self.driver.find_element_by_id(self.elementIdToFind) if elementById is not None: self.log.info("We found an element by the ID of " + self.elementIdToFind + ".") else: self.log.error("Could not find an element by the ID of " + self.elementIdToFind + ".") def testNameFind(self): # simple find by name test, outputs message on completion elementByName = self.driver.find_element_by_name(self.elementNameToFind) if elementByName is not None: self.log.info("We found an element by the name of " + self.elementNameToFind + ".") else: self.log.error("Could not find an element by the name of " + self.elementNameToFind + ".") def tearDown(self): #cleanup resources and close windows when test completes self.addCleanup(self.driver.quit) self.log.debug('Teardown complete')
def method3(self): m3Log = cl.customLogger(logging.INFO) m3Log.debug('Debug Message') m3Log.info('info message') m3Log.warning('warn message') m3Log.error('error message') m3Log.critical('critical message')
class LoggingDemo2(): log = cl.customLogger(logging.DEBUG) def method1(self): self.log.debug("Debug message") self.log.info("Info message") self.log.warning("Warning message") self.log.error("Error message") self.log.critical("Critical message") def method2(self): m2Log = cl.customLogger(logging.INFO) m2Log.debug("Debug message") m2Log.info("Info message") m2Log.warning("Warning message") m2Log.error("Error message") m2Log.critical("Critical message") def method3(self): m3Log = cl.customLogger(logging.WARNING) m3Log.debug("Debug message") m3Log.info("Info message") m3Log.warning("Warning message") m3Log.error("Error message") m3Log.critical("Critical message")
def method3(self): m3Log = cl.customLogger(logging.WARNING) m3Log.debug("Debug message") m3Log.info("Info message") m3Log.warning("Warning message") m3Log.error("Error message") m3Log.critical("Critical message")
def method2(self): m2Log = cl.customLogger(logging.INFO) m2Log.debug("Debug message") m2Log.info("Info message") m2Log.warning("Warning message") m2Log.error("Error message") m2Log.critical("Critical message")
def method2(self): m2Log = cl.customLogger(logging.INFO) m2Log.debug('debug message') m2Log.info('info message') m2Log.warn('warn message') m2Log.error('error message') m2Log.critical('critical message')
class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _login_link = "Login" _email_field = "user_email" _password_field = "user_password" _login_button = "commit" # Actions def clickLoginLink(self): self.elementClick(self._login_link, locatorType="link") def enterEmail(self, email): self.sendKeys(email, self._email_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._login_button, locatorType="name") # Use Actions def login(self, email, password): self.clickLoginLink() self.clearFields() self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccess(self): result = self.isElementPresent( "//*[@id=\"navbar\"]//img[@class=\"gravatar\"]", locatorType="xpath") return result def verifyLoginFailed(self): result = self.isElementPresent( "//div[contains(text(),\"Invalid email or password\")]", locatorType="xpath") return result def clearFields(self): emailField = self.getElement(locator=self._email_field) emailField.clear() passwordField = self.getElement(locator=self._password_field) passwordField.clear() def verifyLoginTitle(self): return self.verifyPageTitle( "Google") #False on purpose to test assert functionality
class TestStatus(SeleniumDriver): log = cl.customLogger(logging.INFO) def __init__(self, driver): """ Inits CheckPoint class """ super(TestStatus, self).__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 SUCCESSFUL :: + " + resultMessage) else: self.resultList.append("FAIL") self.log.error("### VERIFICATION FAILED :: + " + resultMessage) self.screenShot(resultMessage) else: self.resultList.append("FAIL") self.log.error("### VERIFICATION FAILED :: + " + resultMessage) self.screenShot(resultMessage) except: self.resultList.append("FAIL") self.log.error("### Exception Occurred !!!") self.screenShot(resultMessage) print_stack() def mark(self, result, resultMessage): """ Mark the result of the verification point in a test case """ self.setResult(result, resultMessage) def markFinal(self, testName, result, resultMessage): """ Mark the final result of the verification point in a test case This needs to be called at least once in a test case This should be final test status of the test case """ self.setResult(result, resultMessage) if "FAIL" in self.resultList: self.log.error(testName + " ### TEST FAILED") self.resultList.clear() assert True == False else: self.log.info(testName + " ### TEST SUCCESSFUL") self.resultList.clear() assert True == True
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def screenShot(self, resultMessage): """ Takes screenshot of the current open web page """ fileName = resultMessage + "." + str(round( time.time() * 2000)) + ".png" screenshotDirectory = "../screenshots/" relativeFileName = screenshotDirectory + fileName currentDirectory = os.path.dirname(__file__) destinationFile = os.path.join(currentDirectory, relativeFileName) destinationDirectory = os.path.join(currentDirectory, screenshotDirectory) try: if not os.path.exists(destinationDirectory): os.makedirs(destinationDirectory) self.driver.save_screenshot(destinationFile) self.log.info("Screenshot save to directory: " + destinationFile) except: self.log.error("### Exception Occurred") print_stack() def getTitle(self): return self.driver.title def getByType(self, locatorType): locatorType = locatorType.lower() if locatorType == "id": return By.ID elif locatorType == "name": return By.Name elif locatorType == "xpath": return By.XPATH elif locatorType == "css": return By.CSS_SELECTOR elif locatorType == "class": return By.CLASS_NAME elif locatorType == "link": return By.LINK_TEXT else: self.log.info("locator type " + locatorType + "not correct/supported") return False def getElement(self, locator, locatorType="id"): element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info("Element Found with locator: " + locator + "and locatorType: " + locatorType) except: self.log.info("Element not found with locator: " + locator + "and locatorType: " + locatorType) return element def getElementList(self, locator, locatorType="id"): """ NEW METHOD Get list of elements """ element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_elements(byType, locator) self.log.info("Element list found with locator: " + locator + "and locatorType:" + locatorType) except: self.log.info("Element list not found with locator : " + locator + "and locatorType:" + locatorType) return element def elementClick(self, locator, locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.click() self.log.info("clicked on element with locator : " + locator + "locatorType :" + locatorType) except: self.log.info("can not click on the element with locator: " + locator + "locatorType:" + locatorType) print_stack() def sendKeys(self, data, locator, locatorType="id", element=None): """ Send keys to an element -> Modified Either provide element or a combination of locator and locatorType """ try: if locator: #This means if locator is not empty element = self.getElement(locator, locatorType) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + "locatorType:" + locatorType) except: self.log.info("cannot sent data on the element with locator: " + locator + "locatorType:" + locatorType) print_stack() def getText(self, locator="", locatorType="id", element=None, info=""): """ NEW METHOD Get "Text" on an element Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty self.log.debug("In locator condition") element = self.getElement(locator, locatorType) self.log.debug("Before finding text") text = element.text self.log.debug("After finding element,size is : " + str(len(text))) if len(text) == 0: text = element.get_attribute("innerText") if len(text) != 0: self.log.info("Getting text on element :: " + info) self.log.info("The text is :: '" + text + "'") text = text.strip() except: self.log.error("Failed to get text on element" + info) print_stack() text = None return text def isElementPresent(self, locator="", locatorType="id", element=None): """ Check if element is present -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) if element is not None: self.log.info("Element present with locator: " + locator + "locatorType: " + locatorType) return True else: self.log.info("Element not present with locator: " + locator + "locatorType:" + locatorType) return False except: self.log.info("Element not found") return False def isElementDisplayed(self, locator="", locatorType="id", element=None): """ New Method Check if element is displyed Either provide element or a combination of locator and locatorType """ isDisplayed = False try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) if element is not None: isDisplayed = element.is_displayed() self.log.info("Element is displyed with locator: " + locator + "locatorType: " + locatorType) else: self.log.info("Element is not displyed with locator: " + locator + "locatorType:" + locatorType) return isDisplayed except: print("Element not found") return False def elementPresenceCheck(self, locator, byType): """ Check if element is present """ try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element present with locator: " + locator + "locatorType: " + str(byType)) return True else: self.log.info("Element is not present with locator: " + locator + "locatorType: " + str(byType)) return False except: self.log.info("Element not found") return False def waitForElement(self, locator, locatorType="id", timout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timout) + ":: second for element to be clickable") wait = WebDriverWait(self.driver, 10, poll_frequency=1, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until( EC.element_to_be_clickable((byType, "stopFilter_stop-0"))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") print_stack() return element def webscroll(self, direction="up"): """ NEW METHOD """ if direction == "up": # scroll up self.driver.execute_script("window.scrollBy(0,-1000);") if direction == "down": #Scroll Down self.driver.execute_script("window.scrollBy(0,1000):")
class RegisterCoursesPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _login_link = "Sign Up or Log In" _email_field = "email" _password_field = "password" _login_button = "//input[@type='submit']" _search_box = "search" _enter_search = "//button[@type='submit']" _choice_course = "//h4[@class='dynamic-heading']" _enroll_course = "//span[@class='fas fa-arrow-circle-right btn-icon-after']" _cc_num = "//input[@aria-label='Credit or debit card number']" _cc_exp = "//input[@name='exp-date']" _cc_cvv = "//input[@name='cvc']" def clickLoginLink(self): self.elementClick(self._login_link, locatorType="link") def enterEmail(self, email): self.sendKeys(email, self._email_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._login_button, locatorType="xpath") def enterCourse(self, course): self.sendKeys(course, self._search_box, locatorType="id") def clickSearch(self): self.elementClick(self._enter_search, locatorType="xpath") def clickCourse(self): self.elementClick(self._choice_course, locatorType="xpath") def clickEnroll(self): self.elementClick(self._enroll_course, locatorType="xpath") def enterNum(self, num): self.switchToFrame(index=0) self.sendKeys(num, self._cc_num, "xpath") def register(self, email="", password="", course="", num=""): self.clickLoginLink() self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() time.sleep(2) self.enterCourse(course) self.clickSearch() self.clickCourse() self.clickEnroll() self.webScroll(direction="down") # self.enterNum(num) time.sleep(2)
class KodeItTestSuite(unittest.TestCase): log = cl.customLogger(logging.DEBUG) def setUp(self): # -----------Edit inputs here: ---------- baseUrl = "https://letskodeit.teachable.com/pages/practice" self.elementIdToFind = "mouseover" self.elementClassToFind = "btn-style" #---------Do not edit below this line --------- self.driver = webdriver.Firefox() self.driver.maximize_window() self.driver.get(baseUrl) self.log.info('Setup Complete.') def testIdFind(self): elementById = self.driver.find_elements_by_id(self.elementIdToFind) if elementById is not None: self.log.info("We found an element by the ID of " + self.elementIdToFind + ".") else: self.log.error("Could not find an element by the ID of " + self.elementIdToFind + ".") def testClassFind(self): elementByClass = self.driver.find_elements_by_class_name(self.elementClassToFind) if elementByClass is not None: self.log.info("We found an element by the Class Name of " + self.elementClassToFind + ".") else: self.log.error("Could not find an element by the Class Name of " + self.elementClassToFind + ".") # def testSearchEnterName(self): # elementSearchByName = self.driver.find_element_by_name(".//*[@id='name'") # if elementSearchByName is not None: # self.log.info("We found an element by the xpath of .//*[@id='name']") # self.search_field = self.driver.find_element_by_xpath(".//*[@id='name']") # self.search_field.send_keys("Selenium WebDriver Interview Questions") # self.search_field.submit() testSearchEnterName = self.driver.find_element_by_xpath(".//*[@id='carselect']") all_options = element.find_elements_by_tag_name("option") for option in all_options: print("Value is: %s" % option.get_attribute("value")) option.click() def tearDown(self): self.addCleanup(self.driver.quit) self.log.info('Teardown Complete')