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.verifyTextMatch(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 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 MystoreHomePage(BasePage): # global log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver self.util = Util() # locaotr popularproduct = "#homefeatured .left-block .product-image-container" _popularproductAddCart = '#homefeatured .product-container .button-container a' test1 = "//a[text()='Selenium Framework']" _totalproduct = ".ajax_block_products_total" _totlashipping = "span[class='ajax_cart_shipping_cost']" _totalamunt = "span[class='ajax_block_cart_total']" _createEmail = "email_create" _createEmailBtn = "SubmitCreate" _checkout = "a[title='Proceed to checkout']" checkout = "(//a[@title='Proceed to checkout'] )[2]" productheadre = "//h4[text()='Information']" productList = "//h4[text()='Information']/following-sibling::ul/li/a" def getProduct(self): return self.getText(self.productheadre, locatorType="xpath") def getProductList(self): return self.getElementList(self.productList, locatorType="xpath") def test(self): #self.webScroll(self.test1) self.elementClick(self.test1, locatorType="xpath") def verifyProductFooter(self): d = [] e = [ 'Informatio', 'Specials', 'New products', 'Best sellers', 'Our stores', 'Contact us', 'Terms and conditions of use', 'About us', 'Sitemap' ] product = self.getProduct() productlist = self.getProductList() d.append(product) #d = defaultdict(list) #d.keys(product) for plist in productlist: txt = self.getText(element=plist) #d[product].append(txt) d.append(txt) if d == e: self.log.info("List are equal") else: self.log.info("list are not equal") #print(self.getText(element=plist)) self.log.info(d) #self.log.info(d.keys()) assert True return d def selectProduct(self): elements = self.getElementList(self.popularproduct, locatorType="css") for idx, ele in enumerate(elements): if idx == 0: self.getActionDriver().move_to_element(ele).perform() break # def popularProduct(self): # self.getActionDriver().move_to_element(self.driver.find_element_by_id('_popularproduct')).perform() def addToCart(self): self.waitForElement(self._popularproductAddCart, locatorType="css") elements = self.getElementList(self._popularproductAddCart, locatorType="css") for idx, ele in enumerate(elements): if idx == 0: self.elementClick(element=ele) break def verifyTotalCost(self): self.waitForElement(self._totalamunt, locatorType="css") product_amt = self.getText(self._totalproduct, locatorType="css") shiping_amt = self.getText(self._totlashipping, locatorType="css") total_amt = self.getText(self._totalamunt, locatorType="css") amt = float(product_amt.replace("$", "").strip()) + float( shiping_amt.replace("$", "").strip()) # verify ammount self.util.verifyTextMatch(str(amt), total_amt.replace("$", "").strip()) # self.amt = amt self.setamt(amt) def setamt(self, amt): global amt1 amt1 = amt def getAmout(self): return amt1 def clickOnCheckoutLink(self): self.elementClick(self._checkout, locatorType="css") def clickOncheckout(self): self.elementClick(self.checkout, locatorType="xpath") def getEmail(self): self.sendKeys(str("abcb" + str(random.randint(1, 100)) + "@gmail.com"), self._createEmail) def createEmail(self): self.elementClick(self._createEmailBtn)
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 SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver self.util = Util() 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 locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Element not found locator: " + locator + " locatorType: " + locatorType) return element def getTextFromElement(self, element): try: 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 :: ") self.log.info("The text is :: '" + text + "'") text = text.strip() except: self.log.error("Failed to get text on element ") print_stack() text = None return text def getText(self, locator="", locatorType="id", element=None, info=""): try: if locator: 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 isElementDisplayed(self, locator="", locatorType="id", element=None): isDisplayed = False try: if locator: element = self.getElement(locator, locatorType) if element is not None: isDisplayed = element.is_displayed() self.log.info("Element is displayed with locator: " + locator + " locatorType: " + locatorType) else: self.log.info("Element not displayed with locator: " + locator + " locatorType: " + locatorType) return isDisplayed except: self.log("Element not found") return False def elementClear(self, locator, locatorType="id"): element = self.getElement(locator, locatorType) element.clear() def elementClick(self, locator="", locatorType="css", element=None): try: if locator: 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): try: if locator: 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 isElementPresent(self, locator="", locatorType="id", element=None): try: if locator: 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 elementPresentCheck(self, locator, byType): try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element Found locator: " + locator) return True else: return False except: self.log.info("Element not found locator: " + locator) return False def waitUntilElementIsVisible(self, locator, locatorType="id", timeout=15, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, 10, poll_frequency=1, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until( EC.visibility_of_element_located((byType, locator))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") return element def waitUntilElementIsClickable(self, locator, locatorType="id", timeout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log("Waiting for maximum :: " + str(timeout) + " :: seconds 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, locator))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") return element def screenShot(self, resultMessage): 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 waitForElementAndCheckText(self, locator, locatorType, messageToVerify): self.waitUntilElementIsVisible(locator, locatorType=locatorType) message = self.getText(locator, locatorType=locatorType) result = self.util.verifyTextMatch(message, messageToVerify) if result: return "PASS" return "FAIL" def getElementList(self, locator, locatorType="css"): 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 clickEveryWebElementOnList(self, locator, locatorType): elementList = self.getElementList(locator, locatorType) for element in elementList: element.click()
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 LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) # constructor method to pass values def __init__(self, driver): super().__init__(driver) self.driver = driver self.nav = NavigationPage(driver) self.util = Util() # Locators _username_field = 'username' _password_field = 'password' _login_button = "kc-login" _login_error = "//span[@class='kc-feedback-text']" _forgot_password = "******" _user_icon = "//span[@class='d-none d-md-flex']" _logout = "//span[contains(text(),'Logout')]" # Methods to perform actions on elements def enterUserName(self, username): self.sendKeys(username, self._username_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._login_button) def checkLoginError(self, expectedErrorMsg): errorMsg = self.getElementAttributeValue("text", self._login_error, "xpath") result = self.util.verifyTextMatch(actualText=errorMsg, expectedText=expectedErrorMsg) return result # Sorry, we were not able to identify your information in our system. Please try again, or if you recently changed your username or email address, please call 1 888 939 4852 for assistance. def clickForgotPassword(self): self.elementClick(self._forgot_password, 'xpath') def verifyLoginSuccessful(self): userIconElement = self.waitForElement(self._user_icon, 'xpath', 30) result = self.isElementPresent(element=userIconElement) return result def verifyLoginFailure(self): result = self.isElementPresent(self._login_error, 'xpath') return result def clickLogout(self): userDropDown = self.waitForElement(self._user_icon, 'xpath', 10, 1) self.elementClick(element=userDropDown) self.elementClick(self._logout, 'xpath') #Main Method def login(self, username='', password=''): self.enterUserName(username) self.enterPassword(password) self.clickLoginButton() def logout(self): self.nav.navigateToUserSettings() logoutLinkElement = self.waitForElement(self._logout, locatorType='xpath', pollFrequency=1) self.elementClick(element=logoutLinkElement)
class MystoresignPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver self.util = Util() #self.log=MystoreHomePage(driver) # locator _title = ".radio-inline label div" _firstName = "customer_firstname" _lastName = "customer_lastname" _pass = "******" _city = "city" _state = "id_state" _phone = "phone_mobile" _address = "address1" _postal = "postcode" _register = "submitAccount" _processAddress = "button[name='processAddress']" _checkbox = ".checker" _processCarrier = "button[name='processCarrier']" _payment = ".bankwire" _confirmOrder = "//span[text()='I confirm my order']" _totalammountfinal = ".price strong" checkout = "(//a[@title='Proceed to checkout'] )[2]" def clickOnCheckoutLink(self): self.elementClick(self.checkout, locatorType="css") def registerUser(self): self.waitForElement(self._firstName) eleList = self.getElementList(self._title, locatorType="css") for idx, ele in enumerate(eleList): if idx == 0: self.elementClick(element=ele) break self.sendKeys("test", self._firstName) self.sendKeys("User", self._lastName) self.sendKeys("password123", self._pass) self.sendKeys("city", self._city) self.selectByText("Alaska", self._state) self.sendKeys("12454545", self._phone) self.sendKeys("abb121aa", self._address) self.sendKeys("00005", self._postal) self.elementClick(self._register) def clickOnProceed(self): self.elementClick(self.checkout, locatorType="xpath") def clickOnProceedAddress(self): self.waitForElement(self._processAddress, locatorType="css") self.elementClick(self._processAddress, locatorType="css") def clickOnProceedCarrier(self): self.waitForElement(self._processCarrier, locatorType="css") self.elementClick(self._processCarrier, locatorType="css") def clickOnTerms(self): self.elementClick(self._checkbox, locatorType="css") def pay(self): self.waitForElement(self._payment, locatorType="css") self.elementClick(self._payment, locatorType="css") def confirmOrder(self): self.elementClick(self._confirmOrder, locatorType="xpath") def verifyAmt(self, amt11): final = self.getText(self._totalammountfinal, locatorType="css") n = amt11 self.util.verifyTextMatch(final.replace("$", "").strip(), amt11)