示例#1
0
class LoginPO(SeleniumWebDriver):
    log = cl.customLogger(logLevel=logging.INFO)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

    #Locator values
    _usernametxtbx = "username"
    _pwdtxtbx = "//input[@placeholder='Password']"
    _keepmeloggedin = "keepLoggedInCheckBoxContainer"
    _loginbtn = "//div[contains(text(),'Login')]"

    def sendusername(self, username):
        self.sendData(username, self._usernametxtbx, locator="id")

    def sendpwd(self, pwd):
        self.sendData(pwd, self._pwdtxtbx, locator="xpath")

    def clickkeepmeloggedin(self):
        self.click(self._keepmeloggedin, locator="id")

    def loginbtn(self):
        self.click(self._loginbtn, locator="xpath")

    def login(self, username, pwd):
        self.sendusername(username)
        self.sendpwd(pwd)
        self.clickkeepmeloggedin()
        self.loginbtn()

    def errormsgvalidation(self):
        return self.getText(self._errorms_txt, "xpath")
示例#2
0
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 CreateuserPO(SeleniumWebDriver):
    log = cl.customLogger(logLevel=logging.INFO)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

    #locators values
    _firstnametxtbx_id = "createUserPanel_firstNameField"
    _middlenametxtbx_id = "createUserPanel_middleNameField"
    _lastnametxtbx_id = "createUserPanel_lastNameField"
    _emailtxtbx_id = "createUserPanel_emailField"
    _usernametxtbx_id = "createUserPanel_usernameField"
    _password_id = "createUserPanel_passwordField"
    _retypepwd_id = "createUserPanel_passwordCopyField"
    _departmentdrpdwn_xpath = "//div[contains(text(),'-- department not assigned --')]"
    _select_hrandfinances_xpath1 = "//div[contains(text(),'-- new department --')]/following-sibling::div[contains(text(),"
    _select_hrandfinances_xpath2 = ")]"
    _clickoncreate_xpath = "//div[contains(text(),'Create User')]"

    def createnewuser(self, firstname, middlename, lastname, emailid, username,
                      pwd, retypepwd, dept):
        self.webdriverwait_elementclickable(self._firstnametxtbx_id, 20, 2,
                                            "id")
        self.sendData(firstname, self._firstnametxtbx_id, "id")
        self.sendData(middlename, self._middlenametxtbx_id, "id")
        self.sendData(lastname, self._lastnametxtbx_id, "id")
        self.sendData(emailid, self._emailtxtbx_id, "id")
        self.sendData(username, self._usernametxtbx_id, "id")
        self.sendData(pwd, self._password_id, "id")
        self.clear(self._retypepwd_id, "id")
        self.sendData(retypepwd, self._retypepwd_id, "id")
        self.click(self._departmentdrpdwn_xpath, "xpath")
        print(self._select_hrandfinances_xpath1 + "'" + dept + "'" +
              self._select_hrandfinances_xpath2)
        self.driver.find_element(
            By.XPATH, self._select_hrandfinances_xpath1 + "'" + dept + "'" +
            self._select_hrandfinances_xpath2).click()
        self.click(self._clickoncreate_xpath, "xpath")
        self.clear(self._retypepwd_id, "id")
        self.sendData(retypepwd, self._retypepwd_id, "id")
        self.click(self._clickoncreate_xpath, "xpath")
示例#4
0
class TestStatus(SeleniumDriver):
    log = cl.customLogger(logging.INFO)

    def __init__(self, driver):
        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 FAIL ")

    def mark(self, result, resultMessage):
        self.setResult(result, resultMessage)

    def markFinal(self, testName, result, resultMessage):
        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
示例#5
0
class HomePO(SeleniumWebDriver):
    log = cl.customLogger(logLevel=logging.INFO)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

    # Locator values
    _logoutlink = "logoutLink"
    _usertab = "//div[text()='USERS']"
    _newuserbtn_xpath = "//div[contains(text(),'New User')]"

    def clicklogoutlnk(self):
        self.webdriverwait_elementclickable(self._logoutlink, 40, 2, "id")
        self.click(self._logoutlink, "id")

    def clickusertab(self):
        self.click(self._usertab, "xpath")

    def clicknewuserbtn(self):
        self.click(self._newuserbtn_xpath, "xpath")
示例#6
0
class Util(object):

    log = cl.customLogger(logging.INFO)

    def sleep(self, sec, info=""):
        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'):
    def verifyTextContains(self, actualText, expectedText):
        self.log.info("Actual text : " + actualText)
        self.log.info("Expected text : " + expectedText)
        if expectedText.lower() in actualText.lower():
            self.log.info("### VERIFICATION CORRECT")
            return True
        else:
            self.log.info("### VERIFICATION INCORRECT")
            return False
示例#7
0
class SeleniumDriver():

    log = cl.customLogger(logLevel=logging.DEBUG)

    def __init__(self, driver):
        self.driver = driver

    def screenShot(self, resultMessage):
        fileName = resultMessage + "." + str(round(
            time.time() * 1000)) + ".png"
        screenshotDirectory = "../screenshots/"
        relativeFileName = screenshotDirectory + fileName
        currentDirectory = os.path.dirname(__file__)
        destinationFileName = 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(destinationFileName)
            self.log.info("Screenshot saved at: ", destinationFileName)
        except:
            self.log.error("### Exception Ocurred")
            print_stack()

    def getTitle(self):
        return self.driver.title

    def getByType(self, locatorType):
        locatorType = locatorType.lower()
        if locatorType == "id":
            return By.ID
        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
        elif locatorType == "name":
            return By.NAME
        else:
            self.log.info("Locator type is not 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 +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Element not found with locator: " + locator +
                          " locatorType: " + locatorType)
        return element

    def getElementList(self, locator, locatorType="id"):
        elements = None
        try:
            locatorType = locatorType.lower()
            byType = self.getByType(locatorType)
            elements = self.driver.find_elements(byType, locator)
            self.log.info("Elements found with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Elements not found with locator: " + locator +
                          " locatorType: " + locatorType)
        return elements

    def elementClick(self, locator="", locatorType="id", element=None):
        try:
            if locator:  # Esto verifica si el locator no esta vacio
                element = self.getElement(locator, locatorType)
            element.click()
            self.log.info("Element has been clicked with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Cannot click the element with locator: " + locator +
                          " locatorType: " + locatorType)
            print_stack()

    def sendElementKeys(self, locator, data, locatorType="id"):
        try:
            element = self.getElement(locator, locatorType)
            element.send_keys(data)
            self.log.info("Keys has been send with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Cannot send keys with locator: " + locator +
                          " locatorType: " + locatorType)
            print_stack()

    def getText(self, locator="", locatorType="id", element=None, info=""):
        try:
            if locator:
                element = self.getElement(locator, locatorType)
            text = element.text
            if len(text) == 0:
                text = element.get_attribute("innerText")
            if len(text) != 0:
                text = text.strip()
            self.log.info("Text has been retrieved")
        except:
            self.log.error("Failed to get text on element")
            print_stack()
            text = None
        return text

    def isElementPresent(self, locator, locatorType="id"):
        try:
            element = self.getElement(locator, locatorType)
            if element is not None:
                self.log.info("Element found with locator: " + locator +
                              " locatorType: " + locatorType)
                return True
            else:
                return False
        except:
            self.log.info("Element not found with locator: " + locator +
                          " locatorType: " + locatorType)
            return False

    def ElementsPresent(self, locator, byType):
        try:
            elements = self.driver.find_elements(byType, locator)
            if len(elements) > 0:
                self.log.info("Element found")
                return True
            else:
                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.hw.getByType(locatorType)
            self.log.info("Esperando a :: " + str(timeout) +
                          " :: segundos para que aparezca el elemento")
            wait = WebDriverWait(self.driver,
                                 10,
                                 poll_frequency=1,
                                 ignored_exceptions=[
                                     NoSuchElementException,
                                     ElementNotVisibleException,
                                     ElementNotSelectableException
                                 ])
            element = wait.until(EC.element_to_be_clickable((byType, locator)))
            element.click()
            self.log.info("Element appeared with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Element didn't appear with locator: " + locator +
                          " locatorType: " + locatorType)
            print_stack()
        return element

    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 is not displayed with locator: " +
                              locator + " locatorType: " + locatorType)
            return isDisplayed
        except:
            self.log.info("No aparecio el elemento")
            return False

    def scrollBroswer(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);")

    #Switch To Iframe Method

    def switchToFrame(self, locatorIndex=0):
        try:
            self.driver.switch_to.frame(locatorIndex)
            self.log.info("Frame has been switched")
        except:
            self.log.info("Cannot switch frame")
            print_stack()

    def switchToDefault(self):
        try:
            self.driver.switch_to.default_content()
            self.log.info("Switched to default")
        except:
            self.log.info("Cannot revert to default")
            print_stack()
示例#8
0
class SeleniumDriver():

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        #super().__init__(browser)
        self.driver = driver

    # 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 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"):
        """
        Get list of elements
        """
        locatorType = locatorType.lower()
        byType = self.getByType(locatorType)
        elements = self.driver.find_elements(byType, locator)
        if len(elements) > 0:
            self.log.info("Element list FOUND with locator: " + locator +
                          " and locatorType: " + locatorType)
        else:
            self.log.info("Element list NOT FOUND with locator: " + locator +
                          " and locatorType: " + locatorType)
        return elements

    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
        """
        global text
        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):
        try:
            elementList = self.driver.find_elements(byType, locator)
            if len(elementList) > 0:
                self.log.info("Element Found")
                return True
            else:
                self.log.info("Element not found")
                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, 10, poll_frequency=1,
                                 ignored_exceptions=[NoSuchElementException,
                                                     ElementNotVisibleException,
                                                     ElementNotSelectableException])
            element = wait.until(EC.element_to_be_clickable((byType,
                                                             "stopFilter_stops-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, -1500);")

        if direction == "down":
            # Scroll Down
            self.driver.execute_script("window.scrollBy(0, 1300);")

    def switchToFrame(self, id="", name="", index=None):
        """
        Switch to iframe using element locator inside iframe

        Parameters:
            1. Required:
                None
            2. Optional:
                1. id    - id of the iframe
                2. name  - name of the iframe
                3. index - index of the iframe
        Returns:
            None
        Exception:
            None
            :param index:
            :param name:
            :param id:
        """
        if id:
            self.driver.switch_to.frame(id)
        elif name:
            self.driver.switch_to.frame(name)
        else:
            self.driver.switch_to.frame(index)

    def switchToDefaultContent(self):
        """
        Switch to default content

        Parameters:
            None
        Returns:
            None
        Exception:
            None
        """
        self.driver.switch_to.default_content()

    def getElementAttributeValue(self, attribute, element=None, locator="", locatorType="id"):
        """
        Get value of the attribute of element

        Parameters:
            1. Required:
                1. attribute - attribute whose value to find

            2. Optional:
                1. element   - Element whose attribute need to find
                2. locator   - Locator of the element
                3. locatorType - Locator Type to find the element

        Returns:
            Value of the attribute
        Exception:
            None
        """
        if locator:
            element = self.getElement(locator=locator, locatorType=locatorType)
        value = element.get_attribute(attribute)
        return value

    def isEnabled(self, locator, locatorType="id", info=""):
        """
        Check if element is enabled

        Parameters:
            1. Required:
                1. locator - Locator of the element to check
            2. Optional:
                1. locatorType - Type of the locator(id(default), xpath, css, className, linkText)
                2. info - Information about the element, label/name of the element
        Returns:
            boolean
        Exception:
            None
        """
        element = self.getElement(locator, locatorType=locatorType)
        enabled = False
        try:
            attributeValue = self.getElementAttributeValue(element=element, attribute="disabled")
            if attributeValue is not None:
                enabled = element.is_enabled()
            else:
                value = self.getElementAttributeValue(element=element, attribute="class")
                self.log.info("Attribute value From Application Web UI --> :: " + value)
                enabled = not ("disabled" in value)
            if enabled:
                self.log.info("Element :: '" + info + "' is enabled")
            else:
                self.log.info("Element :: '" + info + "' is not enabled")
        except:
            self.log.error("Element :: '" + info + "' state could not be found")
        return enabled
class SeleniumWebDriver:

    log = cl.customLogger(logLevel=logging.INFO)

    def __init__(self, driver):
        self.driver = driver

    #Returns by type
    def getByType(self, locator):
        if locator == "name":
            return By.NAME
        elif locator == "id":
            return By.ID
        elif locator == "class":
            return By.CLASS_NAME
        elif locator == "linktext":
            return By.LINK_TEXT
        elif locator == "partiallinktext":
            return By.PARTIAL_LINK_TEXT
        elif locator == "css":
            return By.CSS_SELECTOR
        elif locator == "xpath":
            return By.XPATH
        else:
            self.log.error("Provided locator is wrong " + locator +
                           " Please provide valid one")
            return False

    def getWebelement(self, locatorvalue, locator="id"):
        element = None
        try:
            bytype = self.getByType(locator)
            element = self.driver.find_element(bytype, locatorvalue)
            self.log.info("Identified webelement with locator " + locator +
                          "and locator value " + locatorvalue)
        except Exception as e:
            self.log.error("Unable to identify the webelement with locator "
                           "" + locator + "and locator value " + locatorvalue +
                           e)
        return element

    def getWebelements(self, locatorvalue, locator="id"):
        listelement = None
        try:
            bytype = self.getByType(locator)
            listelement = self.driver.find_elements(bytype, locatorvalue)
            self.log.info("Identified webelements with locator " + locator +
                          "and locator value " + locatorvalue)
        except Exception as e:
            self.log.error("Unable to identify the webelements with locator "
                           "" + locator + "and locator value " + locatorvalue +
                           e)
        return listelement

    def isElementPresent(self, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        if element is not None:
            self.log.info("Element found")
            return True
        else:
            self.log.error("Element is not present")
            return False

    def enterUrl(self, url):
        self.driver.get(url)

    def browserNavigations(self, action="back"):
        if action == "back":
            self.log.info("Clicked on back button")
            self.driver.back()
        elif action == "forward":
            self.log.info("Clicked on forward button")
            self.driver.forward()
        elif action == "refresh":
            self.log.info("Refreshed the page")
            self.driver.refresh()
        else:
            self.log.error("Please provide the valid browser action")
            return False

    def setBrowserSize(self, width=500, height=500):
        self.driver.set_window_size(width, height)

    def setBrowserPosition(self, width=500, height=500):
        self.driver.set_window_position(width, height)

    def setBrowserMaxOrMin(self, action="max"):
        if action == "max":
            self.log.info("Maximized the window")
            self.driver.maximize_window()
        elif action == "min":
            self.log.info("Minimized the window")
            self.driver.minimize_window()
        else:
            self.log.error("Please provide the valid action")
            return False

    # Current title of the page
    def getTitle(self):
        title = self.driver.title
        return title

    # Current url of the page
    def getURL(self):
        url = self.driver.current_url
        return url

    def sendData(self, data, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        if element is not None:
            element.send_keys(data)
            self.log.info("Entered text or data " + data + " into element " +
                          locatorvalue)
        else:
            self.log.error("Unable to send the data")
            return False

    def click(self, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        if element is not None:
            element.click()
            self.log.info("Clicked on web element " + locatorvalue)
        else:
            self.log.error("Unable to click on web element " + locatorvalue)
            return False

    def clear(self, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        if element is not None:
            element.clear()
            self.log.info("Cleared the text from web element " + locatorvalue)
        else:
            self.log.error("Unable to clear the text from web element " +
                           locatorvalue)
            return False

    def getText(self, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        text = None
        if element is not None:
            text = element.text
            self.log.info("Got text " + text + " from web element " +
                          locatorvalue)
        else:
            self.log.error("Unable to get the text from web element " +
                           locatorvalue)
        return text

    def selectOptionFromDrpDwn(self, option, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        if element is not None:
            s1 = Select(element)
            s1.select_by_visible_text(option)
            s1.select_by_value()
            s1.select_by_index(0)
            self.log.info("Selected " + option + " from drp dwn " +
                          locatorvalue)
        else:
            self.log.error("Unable to select option from web element " +
                           locatorvalue)

    def deselectalloptions(self, locatorvalue, locator="id"):
        element = self.getWebelement(locatorvalue, locator)
        if element is not None:
            s1 = Select(element)
            s1.deselect_all()
            self.log.info("De Selected all options from drp dwn " +
                          locatorvalue)
        else:
            self.log.error("Unable to de select option from web element " +
                           locatorvalue)

    def handleframe(self, id=""):
        try:
            self.driver.switch_to.frame(id)
            self.log.info("Swithched to frame " + id)
        except Exception as e:
            self.log.error("Error in handling frame " + e)

    def switchparentframe(self):
        self.driver.switch_to.parent_frame()

    def handlejspopup(self, action="accept"):
        if action == "accept":
            self.driver.switch_to.alert.accept()
            self.log.info("Clicked on OK button in JS popup")
        elif action == "dismiss":
            self.driver.switch_to.alert.dismiss()
            self.log.info("Clicked on CANCEL button in JS popup")
        else:
            self.log.error("Please provide valid action")
            return False

    def getcurrentwindowid(self):
        currentwindow = self.driver.current_window_handle
        return currentwindow
        self.driver.window_handles

    def getwindowhandles(self):
        windowhandles = self.driver.window_handles
        return windowhandles

    def switchtowindow(self, windowid):
        self.driver.switch_to.window(windowid)

    def webdriverwait_elementclickable(self,
                                       locatorvalue,
                                       waittime=20,
                                       poll_freq=2,
                                       locator="id"):
        try:
            wait = WebDriverWait(self.driver,
                                 waittime,
                                 poll_freq,
                                 ignored_exceptions=[
                                     NoSuchElementException,
                                     ElementNotInteractableException,
                                     ElementNotVisibleException
                                 ])
            bytype = self.getByType(locator)
            wait.until(EC.element_to_be_clickable((bytype, locatorvalue)))
            self.log.info("Waited for element " + str(waittime))
        except Exception as e:
            self.log.error("Unable to wait for element " + str(e))

    def webdriverwait_titlecontains(self, title, waittime=20, poll_freq=2):
        try:
            wait = WebDriverWait(self.driver,
                                 waittime,
                                 poll_freq,
                                 ignored_exceptions=[
                                     NoSuchElementException,
                                     ElementNotInteractableException,
                                     ElementNotVisibleException
                                 ])
            wait.until(EC.title_contains(title))
            self.log.info("Waited for title " + str(waittime))
        except Exception as e:
            self.log.error("Unable to wait for title " + str(e))

    def webdriverwait_urlcontains(self, url, waittime=20, poll_freq=2):
        try:
            wait = WebDriverWait(self.driver,
                                 waittime,
                                 poll_freq,
                                 ignored_exceptions=[
                                     NoSuchElementException,
                                     ElementNotInteractableException,
                                     ElementNotVisibleException
                                 ])
            wait.until(EC.title_contains(url))
            self.log.info("Waited for url " + str(waittime))
        except Exception as e:
            self.log.error("Unable to wait for url " + str(e))

    def mouseover(self, locatorvalue, locator="id"):
        try:
            element = self.getWebelement(locatorvalue, locator)
            action = ActionChains(self.driver)
            action.move_to_element(element).perform()
        except Exception as e:
            self.log.error("Unable to mouse over on element " + locatorvalue)

    def mouseover_click(self, locatorvalue, locator="id"):
        try:
            element = self.getWebelement(locatorvalue, locator)
            action = ActionChains(self.driver)
            action.move_to_element(element).click().perform()
            self.log.info("Mouse over on element " + locatorvalue)
        except Exception as e:
            self.log.error("Unable to mouse over on element " + locatorvalue)

    def scrollpage(self, x="0", y="500"):
        self.driver.execute_script("window.scrollBy(" + x + "," + y + ");")
示例#10
0
class LoginPage(SeleniumDriver):
    log = cl.customLogger(logging.DEBUG)

    def__init__()
    self.driver = driver

    def getTitle(self):
        return self.driver.title

    # Locators
    _amazon = 'a-section a-spacing-medium a-text-center'  #class  'a-icon a-icon-logo'
    _login_link = 'nav-link-accountList'  # id          #class  nav-line-1      nav-action-inner
    _mail_id = 'ap_email'
    _continue = 'continue'
    _password = '******'
    _submit = 'signInSubmit'
    _cart = 'nav-cart'
    _buy = 'sc-buy-box-ptc-button'  # name 'proceedToRetailCheckout'  #class 'a-button-input'  #id 'sc-buy-box-ptc-button'

    def clickAmazon(self):
        self.elementClick(locator=self._amazon)

    def clickLoginLink(self):
        self.elementClick(locator=self._login_link)

    def enterMailId(self, mail):
        self.sendKeys(mail, locator=self._mail_id)

    def clickContinue(self):
        self.elementClick(locator=self._continue)

    def enterPassword(self, password):
        self.sendKeys(password, locator=self._password)

    def clickSubmit(self):
        self.elementClick(locator=self._submit)

    def clickCart(self):
        self.elementClick(locator=self._cart)

    def clickBuy(self):
        self.elementClick(locator=self._buy)

    def login(self, mail="", password=""):
        self.elementClick()
        self.enterMailId(mail)
        self.clickContinue()
        self.enterPassword(password)
        self.clickSubmit()
        time.sleep(2)
        self.clickCart()
        self.clickBuy()

    def VerifyTitle(self):
        return self.VerifyPageTitle("Google")

    # auth-error-message-box
    def verifyLoginFailed(self):
        result = self.isElementPresent("auth-error-message-box",
                                       locatorType="id")
        return result

    def VerifyPageTitle(self, param):
        pass
示例#11
0
class PaymentPage(SeleniumDriver):
    log = cl.customLogger(logging.DEBUG)

    def__init__()
    self.driver = driver

    def getTitle(self):
        return self.driver.title

    # LOCATORS
    _login_link = 'nav-link-accountList'  # id          #class  nav-line-1      nav-action-inner
    _mail_id = 'ap_email'
    _continue = 'continue'
    _password = '******'
    _submit = 'signInSubmit'
    _search = 'twotabsearchtextbox'  #"//input[@id='twotabsearchtextbox']"         #'twotabsearchtextbox'   id
    _search_icon = 'nav-search-submit-text'  #id   #'nav-input'  # class
    _atta = 's-image'  # class
    _add_to_cart = 'add-to-cart-button'  # id
    _proceed_to_buy = 'hlb-ptc-btn-native'  # id
    _buy = 'sc-buy-box-ptc-button'  # class
    _delivery = 'a-declarative a-button-text'  # class
    _continue_payment = 'a-button-text'  # class
    _radio_check = 'pp-HiR0bm-91'  # id
    _cvv = 'pp-HiR0bm-98'  # id
    _final_continue = 'pp-HiR0bm-172-announce'  # id
    _place_order = 'placeYourOrder'  # id

    def clickLoginLink(self):
        self.elementClick(locator=self._login_link)

    def enterMailId(self, mail):
        self.sendKeys(mail, locator=self._mail_id)

    def clickContinue(self):
        self.elementClick(locator=self._continue)

    def enterPassword(self, password):
        self.sendKeys(password, locator=self._password)

    def clickSubmit(self):
        self.elementClick(locator=self._submit)

    def enterKeyword(self, grocery):
        self.sendKeys(grocery, locatorType=self._search)
        self.elementClick(locatorType=self._search_icon)

    def clickItem(self):
        self.elementClick(locatorType=self._atta)  #.format("")

    def clickAddToCart(self):
        self.elementClick(locator=self._add_to_cart)

    def clickProceedToBuy(self):
        self.elementClick(locator=self._proceed_to_buy)

    def clickBuy(self):
        self.elementClick(locator=self._buy)

    def clickDelivery(self):
        self.elementClick(locator=self._delivery)

    def clickContinuePayment(self):
        self.elementClick(locator=self._continue_payment)

    def clickRadioButton(self):
        self.elementClick(locator=self._radio_check)

    def enterCVV(self, cvv):
        self.sendKeys(cvv, locator=self._cvv)

    def clickFinalContinue(self):
        self.elementClick(locator=self._final_continue)

    def clickPlaceOrder(self):
        self.elementClick(locator=self._place_order)

    def login(self, mail="", password="", grocery="", cvv=""):
        self.elementClick()
        self.enterMailId(mail)
        self.clickContinue()
        self.enterPassword(password)
        self.clickSubmit()
        time.sleep(2)
        self.enterKeyword(grocery)
        self.enterCVV(cvv)