class BasePage(PageElements): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getPageTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("EXCEPTION: Actual and Expected Page Title Differ") #print_stack() return False
class BasePage(SeleniumDriver): # this is a constructor def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver # instance of util class self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title .getTtitle() method is coming from Sel_driver class this method is getting the title for you and assertiing if the title matches the titletoverify Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") self.screenShot() print_stack() return False
class Basepage(SeleniumDriver): log = customLogger(logLevel=logging.DEBUG) def __init__(self, driver): """ Base page inherites from the selenium driver which takes care of all the operations related to selenium driver So further we can just inherit this Base page into all our prages so we can have both the functionality :param driver: """ super().__init__(driver) self.driver = driver self.util = Util() # Creation of util object inorder to use utility functions anywhere in classes which is extending this class ex:any pages class def verifyPageTitle(self, textToVerify): """ Verify the title of the webpage :param textToVerify:Title on the page that needs to be verified :return:boolean """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, textToVerify) except: self.log.error("Failed to get the page title") traceback.print_exc() return False
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False
class BasePage(SeleniumDrivers): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def doScreenshot(self, resultMessage): self.screenShot(resultMessage) self.log.info("Screenshot " + resultMessage + "done") def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getPageTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to verify " + titleToVerify + " title") print_stack() return False def getTextFromInputField(self, locator, locatorType="xpath"): """ Get the text from an input field :return: String. Text from an input field """ textOnElement = self.getTextByAttribute(locator, locatorType) return textOnElement def getTextFromMultiSelectField(self, locatorName, locatorType="xpath"): """ Get text from ONLY one element from the multiselect field. :return: String. Text from the element """ textOnElement = self.getText("//span[contains(text(), '" + locatorName + "')]//parent::div//div[@class='multiple-search-select__label']", locatorType) return textOnElement def verifyText(self, actualText, exceptedText, locatorType="xpath"): """ Verify that the element text is exactly the same as the excepted element :param actualText: Text from a web element :param exceptedText: Text what we want to verify on element :return: Boolean. True if texts match, False if not """ textOnElement = self.getText(actualText, locatorType) result = self.util.verifyTextMatch(textOnElement, exceptedText) return result
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False def verifyPageURL(self, expectedURL): currentURL = self.driver.current_url self.log.info("expectedURL ( " + expectedURL + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURL def verifyPageURLlow(self, expectedURL): currentURL1 = self.driver.current_url a1 = currentURL1.split('//')[0] a2 = currentURL1.split('//')[1] b1 = a2.split('/')[0] currentURL = a1+'//'+b1 self.log.info("expectedURL ( " + expectedURL + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURL def verifyLocatorText(self, locator, locatorType, expectedText): result = self.getText(locator, locatorType) self.log.info("expectedText ( " + expectedText + " ) VS LocatorText ( " + result + " )") return result == expectedText def verifyLocatorTextNotNone(self, locator, locatorType): result = self.getText(locator, locatorType) self.log.info("LocatorText = " + str(result) + " locator (" + str(locator) + ") + locatorType (" + locatorType + ")") return result is not None def plusNet(self): plusNetURL = 'http://192.168.1.254/' print("\nPlusNet URL : " + plusNetURL) self.log.info("PlusNet URL : " + plusNetURL) self.driver.get(plusNetURL)
class BaseHome(AppiumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BaseHome, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False def verifyLocatorText(self, locator, locatorType, expectedText): result = self.getText(locator, locatorType) self.log.info("expectedText ( " + expectedText + " ) VS LocatorText ( " + result + " )") return result == expectedText def verifyLocatorTextNotNone(self, locator, locatorType): result = self.getText(locator, locatorType) self.log.info("LocatorText = " + str(result) + " locator (" + str(locator) + ") + locatorType (" + locatorType + ")") return result is not None def verifyLocatorValueText(self, locator, locatorType, expectedText): element = self.getElement(locator, locatorType) result = element.get_attribute('value') self.log.info("expectedText ( " + expectedText + " ) VS LocatorText ( " + result + " )") return result.lower() == expectedText.lower() def verifyPageURL(self, expectedURL): currentURL = self.driver.current_url self.log.info("expectedURL ( " + expectedURL + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURL def verifyPageURLlow(self, expectedURL): currentURL1 = self.driver.current_url a1 = currentURL1.split('//')[0]; a2 = currentURL1.split('//')[1]; b1 = a2.split('/')[0] currentURL = a1+'//'+b1 a1 = expectedURL.split('//')[0]; a2 = expectedURL.split('//')[1]; b1 = a2.split('/')[0] expectedURLlow = a1+'//'+b1 self.log.info("expectedURL ( " + expectedURLlow + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURLlow
class BasePage(SeleniumDriver): def __init__(self, driver): super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.info("Failed to get page title") return False
class BasePage(SeleniumDriver): def __init__(self, driver): super().__init__(driver) self.driver = driver self.util = Util() def VerifyPageTitle(self, titleToVerify): try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error('Failed to get Page title') print_stack() return False
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: WebDriverWait(self.driver, 20).until(lambda x: titleToVerify in self.getTitle()) actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False def verifyAmountOfRowsInTable(self, expected_rows_amount, allowed_offset=3): """ """ try: WebDriverWait(self.driver, 30).until( lambda x: abs((len(self.getElements('//tr', 'xpath')) - 1) - expected_rows_amount) <= allowed_offset) return True except: actualRowsAmount = len(self.getElements( '//tr', 'xpath')) - 1 # minus one for ignoring header self.log.error( "Amount of rows in the table is not as expected. Actual: %s Expected: %s Allowed offset: %s" % (actualRowsAmount, expected_rows_amount, allowed_offset)) print_stack() return None
class BasePage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super(BasePage, self).__init__(driver) self.driver = driver self.ut = Util() def verifyPageTitle(self, expected_title): actual_title = self.getTitle() try: return self.ut.verifyTextContains(actual_title, expected_title) except: self.log.error("Exception Occurred") return False
class BasePage(SeleniumDriver): def __init__(self, driver): super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def pageLocators(self, page): """ read the locators of specific page :param page: page :return: list of all locators in specific page """ locatorsPath = os.path.abspath( "/Users/karthickdhivya/Documents/GitHub/Python-Test-Automation-Framework/locators/locators.json" ) locatorsJsonFile = RJ.readJson(locatorsPath) pageLocators = [ locator for locator in locatorsJsonFile if locator['pageName'] in page ] return pageLocators def locator(self, pageLocators, locatorName): """ get specific locator in specific page :param pageLocators: specific page :param locatorName: locator name :return: locator and locator Type """ for locator in pageLocators: if locatorName == locator['name']: return locator['locator'], locator['locateUsing'] def verifyPageTitle(self, titleToVerify): """ Verify the page Title :param titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verify_page_title(self, title_to_verify): """ Verify the page Title Parameters: title_to_verify: Title on the page that needs to be verified """ try: actualTitle = self.get_title() return self.util.verifyTextContains(actualTitle, title_to_verify) except: self.log.error("Failed to get page title") print_stack() return False def verify_text(self, locator, locator_type, text_to_verify): """ Verify the text Parameters: titleToVerify: Text on the page that needs to be verified """ try: actual_text = self.get_text(locator, locator_type) return self.util.verifyTextMatch(actual_text, text_to_verify) except: self.log.info("Failed to get the text") print_stack() return False def modify_result(self, expected_result, actual_result): return self.util.verifyTestResult(expected_result, actual_result)
class BasePage(SeleniumDriver): def __init__(self, driver): ''' inits BasePage class returns None ''' super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): ''' Verifies the page title Parameters: titleToVerify ''' try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error('Failed to get page title') print_stack()
class BasePage(SeleniumDriver): def __init__(self, driver): super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False _intercomChat_xpath = "//*[@id='intercom-container']/div/iframe" _exitButton_class = "//*[@id='intercom-container']/div/div/div[2]" _next1_xpath = "//*[@id='root']/div/div/main/div/div/div[2]/div/div/div[1]/div/div[2]/button" def removeIntercomChat(self): openIntercomButton = self.getElement(self._intercomChat_xpath, locatorType="xpath") actions = ActionChains(self.driver) actions.move_to_element(openIntercomButton).perform() self.elementClick(self._intercomChat_xpath, locatorType="xpath") time.sleep(1) closeIntercomButton = self.getElement(self._intercomChat_xpath, locatorType="xpath") actions = ActionChains(self.driver) actions.move_to_element(closeIntercomButton).perform() self.elementClick(self._intercomChat_xpath, locatorType="xpath") next1button = self.getElement(self._next1_xpath, locatorType="xpath") actions = ActionChains(self.driver) actions.move_to_element(next1button).perform() self.elementClick(self._next1_xpath, locatorType="xpath")
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False def clearField(self, locator="", locatorType="id"): """ Clear an element field :param locator: :param locatorType: :return: """ element = self.getElement(locator, locatorType) element.clear() self.log.info("Clear field with locator: " + locator + " locatorType: " + locatorType)
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False def verifyPageURL(self, expectedURL): currentURL = self.driver.current_url self.log.info("expectedURL ( " + expectedURL + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURL def verifyPageURLlow(self, expectedURL): currentURL1 = self.driver.current_url a1 = currentURL1.split('//')[0] a2 = currentURL1.split('//')[1] b1 = a2.split('/')[0] currentURL = a1 + '//' + b1 self.log.info("expectedURL ( " + expectedURL + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURL def verifyPageText(self, locator, locatorType, expectedText): result = self.getText(locator, locatorType) self.log.info("expectedText ( " + expectedText + " ) VS pageText ( " + result + " )") return result == expectedText def verifyPageTextNotNone(self, locator, locatorType): result = self.getText(locator, locatorType) return result is not None def verifyUserEmailId(self, avatar_field, avatar_field_type, emailid_field, emailid_field_type): self.elementClick(avatar_field, avatar_field_type) return self.getText(emailid_field, emailid_field_type) def loginGmailUser(self, gmailemail, gmailpswd): from pages.home.login_page import LoginPage userURL = "https://accounts.google.com/signin" + '?Email=' + gmailemail self.log.info("GMAIL URL : " + userURL) self.driver.get(userURL) self.loginpage = LoginPage(self.driver) self.loginpage.login(gmailpswd) def verifyGmailUserStillLogin(self, avatar_email, avatar_email_type): return self.isElementPresent(avatar_email, avatar_email_type)
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver self.util = Util() def screenShot(self, resultMessage): """ Takes screenshot of the current open web page """ fileName = resultMessage + "." + str(round(time.time() * 1000)) + ".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 when taking screenshot") print_stack() def getTitle(self): return self.driver.title def browserBack(self): self.driver.back() def browserForward(self): self.driver.forward() def browserRefresh(self): self.driver.refresh() def browserCurrentUrl(self): time.sleep(2) currentUrl = self.driver.current_url() return currentUrl def verifyUrl(self, UrlToVerify): """ Verify the page URL Parameters: URL: URL on the page that needs to be verified """ try: actualUrl = self.driver.current_url self.log.info("Actual URL" + str(actualUrl)) self.log.info("Expected URL" + str(UrlToVerify)) return self.util.verifyTextContains(actualUrl, UrlToVerify) except: self.log.error("Failed to get page URL") print_stack() return False 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("Cannot 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 send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def clearField(self, locator="", locatorType="id"): """ Clear an element field """ element = self.getElement(locator, locatorType) element.clear() self.log.info("Clear field with locator: " + locator + " locatorType: " + locatorType) 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 element = self.getElement(locator, locatorType) text = element.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: print("Element not found") return False def isElementDisplayed(self, locator="", locatorType="id", element=None): """ NEW METHOD Check if element is displayed 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 displayed" ) else: self.log.info("Element not displayed") 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 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", timeout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=pollFrequency, ignored_exceptions=[NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException]) element = wait.until(EC.element_to_be_clickable((byType, locator))) 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 AutomationInterface(SeleniumDriver): log = cl.customLogger(logging.DEBUG) element = None elementType = None Action = None Data = None waitAfterCmd = None timeOut = None driver = None stat = None util = None reports = {} def __init__(self, driver): try: super(SeleniumDriver).__init__(driver) except: SeleniumDriver.__init__(self, driver) self.driver = driver def run_All_testCase(self, testCaseJson, baseURL): wdf = WebDriverFactory(self.driver) if baseURL == '': self.log.error("Base URL not Inserted") self.driver = wdf.getWebDriverInstance(baseURL=baseURL) self.stat = Status(self.driver) self.util = Util() for test in testCaseJson: self.element = test['FindElement'] self.Action = test['ActionCommand'] self.elementType = test['FindElementType'] self.Data = test['ActionParameters'] self.waitAfterCmd = int(float(test['WaitAfterCommand'])) self.timeOut = int(float(test['Wait-Timeout'])) if self.Action == "login": email = self.Data.strip().split(",")[0] password = self.Data.strip().split(",")[1] email_locator = self.element.strip().split(",")[0] password_locator = self.element.strip().split(",")[1] self.sendKeys(email, email_locator, self.elementType) time.sleep(self.waitAfterCmd) self.sendKeys(password, password_locator, self.elementType) self.waitForElement(self.element, self.elementType, self.timeOut) elif self.Action == "isElementPresent": result = self.isElementPresent(self.element, self.elementType) self.stat.markFinal("Test" + self.element, result, "") self.reports.update({test['ActionNo']: result}) elif self.Action == "elementClick": self.elementClick(self.element, self.elementType) time.sleep(self.waitAfterCmd) elif self.Action == "verifyTextContains": exceptedText = self.getText(self.element, self.elementType) result = self.util.verifyTextContains(self.Data, exceptedText) self.stat.markFinal("Test" + self.element, result, "Text Contains") self.reports.update({test['ActionNo']: result}) elif self.Action == "sendKeys": self.sendKeys(self.Data, self.element, self.elementType) time.sleep(self.waitAfterCmd) elif self.Action == "waitForElement": self.waitForElement(self.element, self.elementType, self.timeOut) elif self.Action == "isElementPresent": result = self.isElementPresent(self.element, self.elementType) self.stat.markFinal("Test" + self.element, result, "") self.reports.update({test['ActionNo']: result}) elif self.Action == "clearField": self.clearField(self.element, self.elementType) time.sleep(self.waitAfterCmd) elif self.Action == "getTitle": result = self.getTitle() print(result) elif self.Action == "isElementDisplayed": self.isElementDisplayed(self.element, self.elementType) time.sleep(self.waitAfterCmd) elif self.Action == "scrollIntoView": self.scrollIntoView(self.element, self.elementType) time.sleep(self.waitAfterCmd) elif self.Action == "mouseHover": self.mouseHover(self.element, self.elementType) self.waitForElement(self.element, self.elementType, self.timeOut) elif self.Action == "mouseClick": self.mouseClick(self.element, self.elementType) time.sleep(self.waitAfterCmd) elif self.Action == "webScroll": self.webScroll(self.Data) time.sleep(self.waitAfterCmd) self.driver.quit() def collectReportsData(self): return self.reports
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() self.stat = Status(driver) self.nav = Navigation(driver) def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("### Failed to get page title !!!") print_stack() return False def DBGetElement(self, tablename, name): # Connect to the database connection = pymysql.connect(host='localhost', user='******', password='******', db='testing', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) self.log.info("Connection Established with DB") try: sql = "SELECT Locator, LocatorType FROM " + tablename + " WHERE Name = '" + name + "'" with connection.cursor() as cursor: # Read a single record cursor.execute(sql) result = cursor.fetchall() self.log.info("Query Successfully Ran") new_row = [] for record in result: new_row.append(record['Locator']) new_row.append(record['LocatorType']) self.log.info("Data Retrieved with: " + tablename + " and Name: " + name) return new_row except: self.log.error("Can't run Query") finally: connection.close() def DBText(self, tablename, name): """ New Method tablename: name: :return: Name column from the database """ # Connect to the database connection = pymysql.connect(host='localhost', user='******', password='******', db='testing', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) self.log.info("Connection Established with DB") try: sql = "SELECT Name FROM " + tablename + " WHERE Name = '" + name + "'" with connection.cursor() as cursor: # Read a single record cursor.execute(sql) result = cursor.fetchall() self.log.info("Query Successfully Ran") new_row = [] for record in result: new_row.append(record['Name']) self.log.info("Data Retrieved with: " + tablename + " and Name: " + name) return new_row except: self.log.error("Can't run Query") finally: connection.close()
class BasePage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() self.bh = bh # === verify_title === def verify_page_title(self, title_to_verify: str) -> bool: try: actual_title = self.get_title() return self.util.verifyTextContains(actual_title, title_to_verify) except: self.log.error("Failed to get page title") print_stack() return False # === css_builder === def css_builder(self, element: BeautifulSoup) -> str: css_build = "" for at in element.attrs: value = element[at] css_build = css_build + "[" + at + "=" if isinstance(value, str): css_build = css_build + '"' + value else: l = len(value) i = 1 for v in value: if i == 1: css_build = css_build + '"' + v + "" else: css_build = css_build + '"' + v + "" i = i + 1 css_build = css_build + '"]' return css_build # === click_on_button === def click_on_button(self, label: str): self.util.sleep(2) bs = self.bh(self.driver.page_source) button = bs.find_clickable_element(label) if len(button) > 0: css = self.css_builder(button[1]) self.log.info(button[0] + css) self.element_click(button[0] + css, "css") else: self.screen_shot(result_message="button_not_found") # === click_on_button_given_parent === def click_on_button_given_parent(self, label: str, parent: BeautifulSoup): self.util.sleep(2) bs = self.bh(self.driver.page_source) button = bs.find_clickable_element_sibling(text=label, parent=parent) if len(button) > 0: css = self.css_builder(button[1]) self.log.info(button[0] + css) self.element_click(button[0] + css, "css") else: self.screen_shot(result_message="button_not_found") # === click_on_button_partial_text === def click_on_button_partial_text(self, label: str): self.util.sleep(2) bs = self.bh(self.driver.page_source) button = bs.find_clickable_element_partial_text(partialtext=label) if len(button) > 0: css = self.css_builder(button[1]) self.log.info(button[0] + css) self.element_click(button[0] + css, "css") else: self.screen_shot(result_message="button_not_found") # === click_on_delete_button_with_alert === def click_on_delete_button_with_alert(self): self.click_on_button(label="Delete") self.util.sleep(3) alert_obj = self.driver.switch_to.alert alert_obj.accept() # === scroll_to_bottom === def scroll_to_bottom(self): last_height = self.driver.execute_script( "return document.body.scrollHeight") while True: # Scroll down to bottom self.driver.execute_script( "window.scrollTo(0, document.body.scrollHeight);") # Wait to load page self.util.sleep(0.5) # Calculate new scroll height and compare with last scroll height new_height = self.driver.execute_script( "return document.body.scrollHeight") if new_height == last_height: break last_height = new_height # === click_on_link === def click_on_link(self, displayText: str): self.driver.find_element_by_link_text(displayText).click() # === concate_string === def concate_string(self, createString: list) -> str: returnString: str = "" for string in createString: returnString = returnString + string + " " return returnString.rstrip() # === tableRow === def getRowReturnList(self) -> list: self.wait_for_element("tbody", "css", timeout=30) bs = self.bh(self.driver.page_source) return bs.get_table_rows() # === compare_alert_text === def compare_alert_text(self, text: str) -> bool: return self.util.verifyTextMatch(actualText=self.alert_text(), expectedText=text)
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Returns: None """ super(BasePage, self).__init__(driver) self.driver = driver self.util = Util() def verifyPageTitle(self, titleToVerify): """ Verify the page Title Parameters: titleToVerify: Title on the page that needs to be verified """ try: actualTitle = self.getTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False def verifyPageURL(self, expectedURL): currentURL = self.driver.current_url.rstrip('/') self.log.info("expectedURL ( " + expectedURL.rstrip('/') + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURL.rstrip('/') def verifyPageURLlow(self, expectedURL): currentURL1 = self.driver.current_url a1 = currentURL1.split('//')[0] a2 = currentURL1.split('//')[1] b1 = a2.split('/')[0] currentURL = a1 + '//' + b1 a1 = expectedURL.split('//')[0] a2 = expectedURL.split('//')[1] b1 = a2.split('/')[0] expectedURLlow = a1 + '//' + b1 self.log.info("expectedURL ( " + expectedURLlow + " ) VS currentURL ( " + currentURL + " )") return currentURL == expectedURLlow def verifyWordExistInURL(self, word=' '): currentURL1 = self.driver.current_url countN = currentURL1.lower().split(word.lower()) return len(countN) > 1 def verifyLocatorText(self, locator, locatorType, expectedText): result = self.getText(locator, locatorType) self.log.info("expectedText ( " + str(expectedText) + " ) VS LocatorText ( " + str(result) + " )") return str(result) == str(expectedText) def verifyLocatorTextNotNone(self, locator, locatorType): result = self.getText(locator, locatorType) self.log.info("LocatorText = " + str(result) + " locator (" + str(locator) + ") + locatorType (" + locatorType + ")") return result is not None def verifyLocatorValueText(self, locator, locatorType, expectedText): element = self.getElement(locator, locatorType) result = element.get_attribute('value') self.log.info("expectedText ( " + str(expectedText) + " ) VS LocatorText ( " + str(result) + " )") return str(result.lower()) == str(expectedText.lower()) def verifyActualGreaterEqualExpected(self, Actual, Expected): self.log.info("Actual ( " + str(Actual) + " ) >= Expected ( " + str(Expected) + " )") return Actual >= Expected def verifyActualEqualExpected(self, Actual, Expected): self.log.info("Actual ( " + str(Actual) + " ) == Expected ( " + str(Expected) + " )") return Actual == Expected def verifyTextEqual(self, Text, Expected): self.log.info("Text ( " + str(Text) + " ) == Expected ( " + str(Expected) + " )") return Text == Expected def verifyEmailFormat(self, email): list1 = [x for x in email.split('@') if x] list2 = [x for x in email.split('.') if x] self.log.info("Email ( " + email + ' ) in correct email format') if len(list1) == 2 and len(list2) >= 2: return True else: return False def verifyPhoneNumber(self, phonenumber): phonenumber1 = phonenumber.replace('-', '').replace(' ', '') result = False if len(phonenumber1) > 11: return result elif len(phonenumber1) < 6: return result else: for i in range(len(phonenumber1)): # print('i = ' + str(i) + ' / s = ' + str(phonenumber[i]) + ' / ' + str(phonenumber[i].isdigit())) if phonenumber1[i].isdigit() == True: result = True else: result = False return result return result def verifyDateIsFuture(self, futureepoch): from time import time, strftime, localtime currentepoch = int(time()) currentdate = strftime('%Y-%m-%d %H:%M:%S') futuredate = strftime('%Y-%m-%d %H:%M:%S', localtime(futureepoch)) self.log.info("FutureDate ( " + str(int(futureepoch)) + " / " + str(futuredate) + " ) > CurrentDate ( " + str(int(currentepoch)) + " / " + str(currentdate) + " )") return int(futureepoch) > int(currentepoch) def verifyDateIsHistory(self, historyepoch): from time import time, strftime, localtime currentepoch = int(time()) currentdate = strftime('%Y-%m-%d %H:%M:%S') historydate = strftime('%Y-%m-%d %H:%M:%S', localtime(historyepoch)) self.log.info("HistoryDate ( " + str(int(historyepoch)) + " / " + str(historydate) + " ) < CurrentDate ( " + str(int(currentepoch)) + " / " + str(currentdate) + " )") return int(historyepoch) < int(currentepoch)
class Helpers: log = cl.customLogger(logging.DEBUG) def __init__(self, section): self.bs = BeautifulSoup(section, "html5lib") self.util = Util() # ===get_all_anchors=== def get_anchor_elements(self) -> list: urls: list = [] for a in self.bs.find_all('a'): urls.append(dict(text=a.get_text(), link=a['href'])) return urls # ===get_text_all=== def get_text_all(self, tag: str = "", attributes: dict = {}) -> str: elements = self.bs.find_all(tag, attributes) result = "" for element in elements: result = result + element.get_text() + " " return result # ===get_text=== def get_text(self, tag: str = "", attributes: dict = {}) -> str: element = self.bs.find(tag, attributes) return element.get_text() # ===get_text_element_sibling=== def get_text_element_sibling( self, tag: str = "", attributes: dict = {}, sib_tag: str = "", sib_attributes: dict = {}, ) -> str: parent = self.bs.find(tag, attributes) elements = parent.find_all(sib_tag, sib_attributes) result = "" for element in elements: result = result + element.get_text() + " " return result # ===count_sibling=== def count_sibling( self, tag: str = "", attributes: dict = {}, sib_tag: str = "", sib_attributes: dict = {}, sib_text: str = None, ) -> int: self.util.sleep(2) parent = self.bs.find(tag, attributes) if sib_text: elements = parent.find_all(sib_tag, text=sib_text) else: elements = parent.find_all(sib_tag, sib_attributes) return len(elements) # === get_table_rows === def get_table_rows(self) -> list: table = self.bs.find("table") tbody = table.find("tbody") return tbody.findAll("tr") # === search_row_for_element === def search_row_for_element( self, rows: list, tag: str, attributes: dict ) -> BeautifulSoup: for row in rows: candidate = row.find(tag, attributes) if candidate: return row # === get_all_sibling_divs === def get_all_sibling_divs( self, parent: BeautifulSoup, tag: str, attributes: dict ) -> list: return parent.find(tag, attributes).findAll("div") # ===get_attribute_button=== @staticmethod def get_attribute_button(parent: BeautifulSoup, att: str) -> str: button = parent.find("button") return button[att] # ===find_clickable_element=== def find_clickable_element(self, text: str = "") -> list: button = self.bs.find_all("button") input = self.bs.find_all("input") if len(button) > 0: self.log.info("button length: " + str(len(button))) for but in button: if self.util.verifyTextMatch(actualText=re.sub(r"\s+", "", but.get_text()), expectedText=re.sub(r"\s+", "", text)): return ["button", but] if len(input) > 0: self.log.info("input length: " + str(len(input))) for but in input: if but.has_attr('value'): if self.util.verifyTextMatch(actualText=but["value"], expectedText=text): return ["input", but] return None # ===find_clickable_element_sibling=== def find_clickable_element_sibling(self, text: str, parent: BeautifulSoup) -> list: button = parent.find_all("button") input = parent.find_all("input") if len(button) > 0: for but in button: if self.util.verifyTextMatch(actualText=re.sub(r"\s+", "", but.get_text()), expectedText=re.sub(r"\s+", "", text)): return ["button", but] if len(input) > 0: for but in input: if but.has_attr('value'): if self.util.verifyTextMatch(actualText=but["value"], expectedText=text): return ["input", but] return None # ===find_clickable_element_partial_text=== def find_clickable_element_partial_text(self, partialtext: str = "") -> list: button = self.bs.find_all("button") input = self.bs.find_all("input") if len(button) > 0: for but in button: if self.util.verifyTextContains(actualText=but.get_text(), expectedText=partialtext): return ["button", but] if len(input) > 0: for but in input: if but.has_attr('value'): if self.util.verifyTextContains(actualText=but["value"], expectedText=partialtext): return ["input", but] return None
class BasePage(SeleniumDriver): def __init__(self, driver): """ Inits BasePage class Required Parameters: driver: WebDriver Object Optional Parameters: None Returns: None """ super(BasePage, self).__init__(driver) self._validate_page(driver) self.driver = driver self.util = Util() self.bkend = BEConnection() def verifyFlashMessage(self, textToVerify, timeout=6): """ Validate the flash message after completing an action Required Parameters: textToVerify: Text on the flash message that needs to be verified Optional Parameters: None Returns: Boolean """ try: flashMessageElement = self.waitForElement( locator=".nmbl-flash-message-content", locatorType="css", info="flash message", timeout=timeout) if flashMessageElement is not None: elementText = self.getText(flashMessageElement, "Getting text on flash message") # elementText = self.getText(self.getElementByClassName("flash-message"), # "Getting text on flash message") result = self.util.verifyTextContains(elementText, textToVerify) # flashMessageClose = self.getElementByClassName("flash-message-close") flashMessageClose = self.getElementByCss( ".nmbl-flash-message-close") self.clickElement(flashMessageClose, "Flash message 'X' close button", 1) return result else: # If element does not show up before timeout, return False return False except: self.log.error("Failed to get text on flash message") print_stack() return False def verifyModalMessage(self, textToVerify, textLocator, buttonToClickLocator, buttonInfo=""): """ Validate the message on the modal and click Ok/Close button to close the modal Required Parameters: textToVerify: Text on the modal that needs to be verified textLocator: Locator of the message buttonToClickLocator: Locator of the button to click on modal Optional Parameters: None Returns: Boolean """ try: result = False elementPresent = self.isElementPresent(textLocator) if elementPresent: elementText = self.getText(self.getElement(textLocator), "Getting text on modal") result = self.util.verifyTextContains(elementText, textToVerify) if not result: self.util.screenShot("FAIL-Modal-Message-Verification") self.clickElement(self.getElement(buttonToClickLocator), buttonInfo) return result except: self.log.error("Failed to get text on modal") print_stack() return False def verifyModalConfirmation(self, buttonLocator, info, locatorType="id"): """ Verify the confirmation modal is present and click the 'Confirmation' button 'Confirmation' button can be OK/Close/Delete Required Parameters: buttonLocator: Locator of the button on confirmation modal info: Information about the button, usually text on the button Optional Parameters: locatorType: Type of the locator(id(default), xpath, css, className, linkText) Returns: Boolean """ try: elementPresent = self.isElementPresent(buttonLocator, locatorType) if elementPresent: return self.clickElement(self.getElement(buttonLocator), info) return False except: self.log.error("Failed to find button on confirmation modal") print_stack() return False def verifyFieldErrorMessage(self, locator, textToVerify, locatorType="id"): """ Validate the flash message after completing an action Required Parameters: locator: Locator of the error message textToVerify: Text on the flash message that needs to be verified Optional Parameters: locatorType: Type of the locator, default is 'id' Returns: Boolean """ try: elementPresent = self.isElementPresent(locator, locatorType) if elementPresent: elementText = self.getText( self.getElement(locator), "Getting text on field error message") result = self.util.verifyTextContains(elementText, textToVerify) return result return False except: self.log.error("Failed to get text on field error message") print_stack() return False def verifyPageTitle(self, titleToVerify): """ Verify the page Title Required Parameters: titleToVerify: Title on the page that needs to be verified Optional Parameters: None Returns: Boolean """ try: actualTitle = self.getBrowserTitle() return self.util.verifyTextContains(actualTitle, titleToVerify) except: self.log.error("Failed to get page title") print_stack() return False @abstractmethod def _validate_page(self, driver): pass """ Regions define functionality available through all page objects """