Exemple #1
0
class Util:

    log = cl.custom_logger()

    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 StatusTest(SeleniumDriver):

    log = custom_logger()

    def __init__(self, driver):
        """
        Inits CheckPoint class
        """
        super(StatusTest, 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, NO RESULT FOUND:: + " +
                    resultMessage)
                self.screenShot(resultMessage)
        except:
            self.resultList.append("FAIL")
            self.log.error("### Exception Occurred !!!")
            self.screenShot(resultMessage)
            print_stack()

    def mark(self, result, resultMessage):
        """
        Mark the result of the verification point in a test case
        """
        self.setResult(result, resultMessage)

    def markFinal(self, testName, result, resultMessage):
        """
        Mark the final result of the verification point in a test case
        This needs to be called at least once in a test case
        This should be final test status of the test case
        """
        self.setResult(result, resultMessage)

        if "FAIL" in self.resultList:
            self.log.error(testName + " ### TEST FAILED")
            self.log.info(self.resultList)
            self.resultList.clear()
            assert True == False
        else:
            self.log.info(testName + " ### TEST SUCCESSFUL")
            self.resultList.clear()
            assert True == True
Exemple #3
0
class Utilities():
    cl = custom_logger(logging.INFO)

    def sleep(self, sec, info=""):
        if info is not None:
            self.cl.info("Wait :: " + str(sec) + " seconds for " + str(info))
        try:
            time.sleep(sec)
        except InterruptedError:
            self.cl.error("Exception occured while Sleep")

    def generate_date_time(self):
        now = datetime.datetime.now()
        return now.strftime('%Y-%m-%d %H-%M-%S-%f')
Exemple #4
0
class MarkTestStatus(SeleniumDriver):
    cl = custom_logger(logging.INFO)

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

        self.resultlist = []

    def setResult(self, result, resultMessage):
        try:
            if result is not None:
                if result is True:
                    self.resultlist.append("Pass")
                    self.cl.info("###Verification Successfull :: + " + resultMessage)
                else:
                    self.resultlist.append("Fail")
                    self.savescreenshots(resultMessage)
                    self.cl.error("###Verification Failed :: + " + resultMessage)

            else:
                self.resultlist.append("Fail")
                self.savescreenshots(resultMessage)
                self.cl.error("###Verification Failed :: + " + resultMessage)


        except Exception as e:
            self.resultlist.append("Fail")
            self.savescreenshots(resultMessage)
            self.cl.error("### Exception Occured !!!" + "Exception :: " + str(e))


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

    def finalMark(self, testcase, result, resultMessage):
        self.setResult(result, resultMessage)

        if "Fail" in self.resultlist:
            self.cl.error(testcase + "### Test Failed")
            self.resultlist.clear()
            assert True == False

        else:
            self.cl.info(testcase + "### Test Passed")
            self.resultlist.clear()
            assert True == True
class Account(SeleniumBase):
    cl = custom_logger(loglevel=logging.INFO)

    def __init__(self, driver):
        super(Account, self).__init__(driver)
        self.driver = driver
        self.mb = MobilePage(self.driver)

    #locators
    _account = (By.XPATH, "//a/span[text()='Account']")
    _register = (By.LINK_TEXT, "Register")
    _firstname = (By.ID, "firstname")
    _lastname = (By.ID, "lastname")
    _email_address = (By.ID, "email_address")
    _password = (By.ID, "password")
    _confirmation = (By.ID, "confirmation")
    _checkbox = (By.ID, "is_subscribed")
    _registeration = (By.XPATH, "//button[@title='Register']")

    _tv = "TV"
    _add_to_wishlist = "//a[@title='LG LCD']//following-sibling::div/child::div/ul/li/a"
    _share_wishlist = "//span[text()='Share Wishlist']"
    _emailaddress_wishlist = "email_address"
    _message_wishlist = "message"
    _message_success_sharelist = "//span[text()='Your Wishlist has been shared.']"

    def click_account(self):
        self.elementClick(self._account)
        self.elementClick(self._register)

    def fill_registration(self, firstName, lastName, emailAddress, password,
                          confirmPassword):
        self.elementSend(self._firstname, firstName)
        self.elementSend(self._lastname, lastName)
        self.elementSend(self._email_address, emailAddress)
        self.elementSend(self._password, password)
        self.elementSend(self._confirmation, confirmPassword)

    def checkbox(self, ):
        self.elementClick(self._checkbox)

    def click_registration_button(self):
        self.elementClick(self._registeration)

    def success_message(self, success):
        _success_message = (By.XPATH, f"//span[text()='{success}']")
        return self.isElementDisplayed(_success_message)
Exemple #6
0
class WebDriverFactory():
    cl = custom_logger(logging.INFO)

    def __init__(self, browser, url):
        self.browser = browser
        self.url = url

    def get_browser_instance(self):
        if self.browser == "FF":
            driver = webdriver.Firefox(
                executable_path="drivers//geckodriver.exe")

        elif self.browser == "Chrome":
            chrome_options = Options()
            #download_dir = "C://Users//A610037//Downloads//download_chrome"
            chrome_options.add_argument('--start-maximized')
            chrome_options.add_experimental_option('prefs',
                                                   {'geolocation': True})
            chrome_options.add_experimental_option('useAutomationExtension',
                                                   False)
            chrome_options.add_experimental_option("excludeSwitches",
                                                   ["enable-automation"])

            driver = webdriver.Chrome(
                options=chrome_options,
                executable_path='drivers//chromedriver.exe')

        elif self.browser == "IE":
            driver = webdriver.Ie(
                executable_path='drivers//IEDriverServer.exe')

        else:
            driver = webdriver.Chrome(
                executable_path='drivers//chromedriver.exe')

        baseUrl = self.url
        driver.delete_all_cookies()
        driver.maximize_window()
        driver.implicitly_wait(10)
        driver.get(baseUrl)
        self.cl.info('Launching the URL :: ' + str(baseUrl) +
                     ' on browser :: ' + str(self.browser))

        return driver
Exemple #7
0
from behave import *

from pages.login.login import Login
from utilities.customlogger import custom_logger
import logging
from base.WebDriverFactory import WebDriverFactory
from base.selenium_driver import SeleniumDriver
import configuration_file.configuration as config
from pages.account_creation.account_creation import Account
import allure_behave.hooks

cl = custom_logger(logging.INFO)


def before_scenario(context, feature):
    cl.info("Automation Started")
    context.wdf = WebDriverFactory(browser=config.browser, url=config.url)
    context.driver = context.wdf.get_browser_instance()

    # All Page Objects initialized here
    context.selenium_driver = SeleniumDriver(context.driver)
    context.login = Login(context.driver)
    context.account = Account(context.driver)


def after_scenario(context, feature):
    context.driver.quit()
    cl.info("Automation Ended")
class MobilePage(SeleniumBase):
    cl = custom_logger(logging.INFO)

    def __init__(self, driver):
        super(MobilePage, self).__init__(driver)
        self.driver = driver
        self.utill = Utilities()

    #locator
    _mobile = (By.LINK_TEXT, "MOBILE")
    _Iphone = "IPHONE"
    _samsung = "SAMSUNG GALAXY"
    _sony = "SONY XPERIA"
    _expected_list1 = ['IPHONE', 'SAMSUNG GALAXY', 'SONY XPERIA']
    _expected_list2 = ['SONY XPERIA', 'SAMSUNG GALAXY', 'IPHONE']
    _tv = (By.LINK_TEXT, "TV")
    _grid_view = "//strong[@title='Grid']"
    _list_view = (By.LINK_TEXT, "List")
    _value = (By.XPATH, "//span[@id='product-price-1']/child::span")
    _add_to_cart = (
        By.XPATH,
        "//a[@title='Xperia']//following-sibling::div//span[text()='Add to Cart']"
    )
    _cart_quantity = (By.XPATH,
                      "//input[@data-cart-item-id='MOB001' and @title='Qty']")
    _update = (By.XPATH, "//button[@title='Update']/span/span")
    _error = (
        By.XPATH,
        "//span[text()='Some of the products cannot be ordered in requested quantity.']"
    )
    _compare_add_product = "//a[text()='Sony Xperia']/parent::h2/parent::div/child::div/child::ul/li/a[text()='Add to Compare']"
    _compare_button = (By.XPATH, "//span[text()='Compare']")
    _compare_screen = (By.XPATH, "//h1[text()='Compare Products']")
    _iphone_new = "//a[text()='IPhone']"
    _close_window = "//span[text()='Close Window']"
    _available_mobile = (By.XPATH, "//div[@class='category-products']/ul/li/a")
    _mobile_text = (By.XPATH, "//li[@class='item last']//child::div/h2/a")
    _sort_by = (By.XPATH, "//select[@title='Sort By']")

    def mobile_tab(self):
        self.elementClick(self._mobile)

    def available_mobiles(self):
        return self.getAttributeList(self._available_mobile,
                                     attributeType='title')

    def sort_by(self, visibleText):
        self.selectByVisibleText(self._sort_by, visibleText)

    def get_mobile_text(self):
        return self.getElementsText(self._mobile_text)

    def verify_sort_functionality(self, result):
        result1 = self.get_mobile_text()
        res = result.strip('][').split(', ')
        return result1 == res

    def add_to_cart(self):
        self.elementClick(self._add_to_cart)

    def enter_cart_quantity_and_update(self):
        self.elementSend(self._cart_quantity, '1000')
        #self.explicitwait(self._update,'xpath',20,0.1)
        self.elementClick(self._update)
        return self.isElementDisplayed(self._error)

    def click_tv_tab(self):
        self.elementClick(self._tv)
        print('clicked on Tv')

    def click_list_view(self):
        self.elementClick(self._list_view)

    def sony_price_grid_view(self):
        return self.getElementText(self._value)

    def sony_price_list_view(self):
        return self.getElementText(self._value)

    def add_product1_for_compare(self, mobile1):
        compare = (
            By.XPATH,
            f"//a[text()='{mobile1}']/parent::h2/parent::div/child::div/child::ul/li/a[text()='Add to Compare']"
        )
        self.elementClick(compare)

    def add_product2_for_compare(self, mobile2):
        compare = (
            By.XPATH,
            f"//a[text()='{mobile2}']/parent::h2/parent::div/child::div/child::ul/li/a[text()='Add to Compare']"
        )
        self.elementClick(compare)

    def click_compare_button(self):
        self.elementClick(self._compare_button)

    def confirm_compare_window(self):
        self.switchWindow(1)
        return self.isElementDisplayed(self._compare_screen)
Exemple #9
0
class Account(SeleniumDriver):
    cl = custom_logger(loglevel=logging.INFO)

    def __init__(self, driver):
        super(Account, self).__init__(driver)
        self.driver = driver
        self.mb = MobilePage(self.driver)

    #locators
    _account = {
        "locatorType": By.XPATH,
        "locatorValue": "//a/span[text()='Account']"
    }
    _register = {"locatorType": By.LINK_TEXT, "locatorValue": "Register"}
    _firstname = {"locatorType": By.ID, "locatorValue": "firstname"}
    _lastname = {"locatorType": By.ID, "locatorValue": "lastname"}
    _email_address = {"locatorType": By.ID, "locatorValue": "email_address"}
    _password = {"locatorType": By.ID, "locatorValue": "password"}
    _confirmation = {"locatorType": By.ID, "locatorValue": "confirmation"}
    _checkbox = {"locatorType": By.ID, "locatorValue": "is_subscribed"}
    _register2 = {
        "locatorType": By.XPATH,
        "locatorValue": "//button[@title='Register']"
    }
    _success_message = {
        "locatorType":
        By.XPATH,
        "locatorValue":
        "//span[text()='Thank you for registering with Main Website Store.']"
    }
    _tv = {"locatorType": By.LINK_TEXT, "locatorValue": "TV"}
    _add_to_wishlist = {
        "locatorType":
        By.XPATH,
        "locatorValue":
        "//a[@title='LG LCD']//following-sibling::div/child::div/ul/li/a"
    }
    _share_wishlist = {
        "locatorType": By.XPATH,
        "locatorValue": "//span[text()='Share Wishlist']"
    }
    _emailaddress_wishlist = {
        "locatorType": By.ID,
        "locatorValue": "email_address"
    }
    _message_wishlist = {"locatorType": By.ID, "locatorValue": "message"}
    _message_success_sharelist = {
        "locatorType": By.XPATH,
        "locatorValue": "//span[text()='Your Wishlist has been shared.']"
    }
    _my_Account = {
        "locatorType": By.XPATH,
        "locatorValue": "//div[@id='header-account']//a[text()='My Account']"
    }

    def click_account(self):
        self.elementClick(self._account)

    def click_registration(self):
        self.elementClick(self._register)

    # def click_tv_tab(self):
    #     self.elementClick(self._tv,'link')
    #
    # def add_to_wishlist(self,emailAddress,message):
    #     self.click_tv_tab()
    #     self.elementClick(self._add_to_wishlist,'xpath')
    #     self.elementClick(self._share_wishlist,'xpath')
    #     self.elementSend(self._emailaddress_wishlist,'id',emailAddress)
    #     self.elementSend(self._message_wishlist, 'id', message)
    #     self.elementClick(self._share_wishlist,'xpath')
    #     return self.isElementDisplayed(self._message_success_sharelist,'xpath')

    def register(self, firstName, lastName, emailAddress, password,
                 confirmPassword):
        self.elementSend(self._firstname, firstName)
        self.elementSend(self._lastname, lastName)
        self.elementSend(self._email_address, emailAddress)
        self.elementSend(self._password, password)
        self.elementSend(self._confirmation, confirmPassword)
        self.elementClick(self._checkbox)

    def click_register_button(self):
        self.elementClick(self._register2)

    def success_message(self):
        return self.isElementDisplayed(self._success_message)
Exemple #10
0
class WebDriverFactory:
    cl = custom_logger(logging.INFO)

    def __init__(self, browser, headless):
        self.browser = browser
        self.headless = headless


    def get_browser_instance(self):
        try:
            if self.browser.lower() == "firefox":
                options = FirefoxOptions()
                if self.headless:
                    options.add_argument("--headless")
                #options.add_argument("--disable-gpu")
                profile = webdriver.FirefoxProfile()
                #options.add_argument("--private")
                # options.add_argument("-width=1920")
                # options.add_argument("-height=1080")
                profile.accept_untrusted_certs = True
                driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(), firefox_profile=profile,
                                           options=options)

            elif self.browser.lower() == "chrome":
                chrome_options = Options()
                if self.headless:
                    chrome_options.add_argument('headless')
                #chrome_options.add_argument('window-size=1920x1080')
                chrome_options.add_argument('ignore-certificate-errors')
                chrome_options.add_argument('--incognito')
                chrome_options.add_argument('--start-maximized')
                # chrome_options.add_experimental_option('prefs', {'geolocation': True})
                chrome_options.add_experimental_option('useAutomationExtension', False)
                chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
                chrome_options.add_argument('--log-level=3')
                # driver = webdriver.Chrome(options=chrome_options, executable_path='drivers//chromedriver.exe')
                driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)

            elif self.browser.lower() == "ie":
                driver = webdriver.Ie(IEDriverManager().install())

            elif self.browser.lower() == "edge":
                options = EdgeOptions()
                if self.headless:
                    options.add_argument('headless')
                options.use_chromium = True
                #options.add_argument('window-size=1920x1080')
                options.add_argument('ignore-certificate-errors')
                options.add_experimental_option('useAutomationExtension', False)
                options.add_argument('--inprivate')
                options.add_argument('--log-level=3')
                options.add_experimental_option("excludeSwitches", ["enable-automation"])
                driver = webdriver.Chrome(EdgeChromiumDriverManager().install(), options=options)

            elif self.browser.lower() == 'browserstack':
                # bs_local = Local()
                # bs_local_args = {"key": key,"localIdentifier": localIdentifier}
                # bs_local.start(**bs_local_args)
                driver = webdriver.Remote(command_executor=bb_url, desired_capabilities=browser_config)

            else:
                raise ValueError

            if self.headless:
                self.cl.info("Starting " + str(self.browser).upper() + " browser in headless mode")
            else:
                self.cl.info("Starting " + str(self.browser).upper() + " browser ")
            driver.maximize_window()
            # if self.baseUrl:
            #     driver.get(self.baseUrl)
            #     self.cl.info("Opening the URL :: " + str(self.baseUrl))

            driver.implicitly_wait(5)
            driver.delete_all_cookies()
            driver.set_page_load_timeout(20)
            return driver


        except ValueError as e:
            self.cl.error("Browser not supported :: " + str(
                self.browser) + ". Supported browser types are Chrome, Firefox, Edge. Exception occurred. :: " + str(
                e.__class__.__name__) + ' ' + str(e))
            raise e

        except Exception as e:
            self.cl.error("Exception occurred. :: " + str(
                e.__class__.__name__) + ' ' + str(e))
            raise e
Exemple #11
0
class Login(BasePage):
    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

    log = cl.custom_logger()

    def enter_username(self, username):
        self.sendKeys(username, *el.user_name)

    def enter_password(self, password):
        self.sendKeys(password, *el.password)

    def click_login_button(self):
        self.elementClick(*el.login_link)

    def verify_mandara_app_load(self):
        result = self.isElementPresent(*el.sigtuple_logo)
        return result

    def verify_login_text(self):
        result = self.verify_text_match_from_element(td.login_btn_text,
                                                     *el.login_link)
        return result

    def verify_username_text(self):
        result = self.verify_text_match_from_element(td.usr_ghost_text,
                                                     *el.user_ghost)
        return result

    def verify_password_text(self):
        result = self.verify_text_match_from_element(td.pwd_ghost_text,
                                                     *el.pwd_ghost)
        return result

    def verify_fgt_pwd_text(self):
        result = self.verify_text_match_from_element(td.fgt_pwd_text,
                                                     *el.forgot_password)
        return result

    def verify_back_to_login_text(self):
        result = self.verify_text_match_from_element(td.back_to_login,
                                                     *el.back_to_login)
        return result

    def verify_reset_text(self):
        result = self.verify_text_match_from_element(td.reset_password_text,
                                                     *el.reset_password)
        return result

    def verify_disabled_login_button(self):
        self.log.info("Verifying if the login button is disabled")
        self.log.debug("Checking the enabled returns: " +
                       str(self.verify_if_button_enabled(*el.login_link)))
        if self.verify_if_button_enabled(*el.login_link):
            return True
        else:
            return False

    def username_input_alert(self):
        self.log.info("Verifying the alert text for the username input field")
        self.util.sleep(2)
        self.elementClick(*el.user_name)
        self.elementClick(*el.login_container)
        self.util.sleep(2)
        return self.verify_text_match_from_element(td.username_input_alert,
                                                   *el.username_input_alert)

    def password_input_alert(self):
        self.log.info("Verifying the alert text for the password input field")
        self.elementClick(*el.user_name)
        self.elementClick(*el.login_container)
        self.util.sleep(2)
        return self.verify_text_match_from_element(td.password_input_alert,
                                                   *el.password_input_alert)

    def login(self, username, password):
        self.clearField(*el.user_name)
        self.clearField(*el.password)
        self.enter_username(username)
        self.enter_password(password)
        self.click_login_button()

    def verify_login_failed(self):
        self.util.sleep(1, "Waiting for the invalid creds message")
        expected_invalid_header = self.getText(*el.error_invalid_login)
        expected_invalid_message = self.getText(*el.error_invalid_login1)
        if self.util.verifyTextMatch(
                td.invalid_creds_header,
                expected_invalid_header) and self.util.verifyTextMatch(
                    td.invalid_creds_message, expected_invalid_message):
            return True
        else:
            return False

    def verify_login_success(self):
        self.util.sleep(2, "user icon")
        result = self.elementPresenceCheck(*el.user_icon)
        return result

    def verify_login_page_title(self, titleToVerify):
        result = self.verifyPageTitle(titleToVerify)
        return result

    def verify_enter_valid_email(self):
        self.util.sleep(2, "Forgot Password")
        self.elementClick(*el.forgot_password)
        self.elementClick(*el.fgtpasswdemail)
        self.moveOffsetToElement(10, 30, *el.fgtpasswdemail)
        self.util.sleep(2, "Message for entering valid email")
        return self.verify_text_match_from_element(
            td.forgot_password_input_alert, *el.forgot_password_alert)

    def forgot_password_invalid(self, email):
        self.sendKeys(email, *el.fgtpasswdemail)
        self.elementClick(*el.reset_password)
        self.util.sleep(1)
        result = self.elementPresenceCheck(*el.invalid_forgot_email)
        self.util.sleep(2)
        return result

    def forgot_password_valid(self, email):
        self.clearField(*el.fgtpasswdemail)
        self.elementClick(*el.fgtpasswdemail)
        self.sendKeys(email, *el.fgtpasswdemail)
        self.elementClick(*el.reset_password)
        self.util.sleep(1, "Confirmation Message for Email sent")
        confirmation_message = self.getText(*el.confirmation_messgforgtpasswd,
                                            "xpath")
        self.log.info("Verifying the successful email send for password reset")
        result = self.util.verifyTextMatch(confirmation_message,
                                           td.success_email_send_message)
        return result

    def presence_back_to_login(self):
        result = self.elementPresenceCheck(*el.back_to_login)
        return result

    def back_to_login(self):
        self.elementClick(*el.back_to_login)
        result = self.elementPresenceCheck(*el.password)
        return result

    def copyright(self):
        result = self.verify_text_match_from_element(td.copy_right_text,
                                                     *el.copyright)
        return result
Exemple #12
0
class MobilePage(BasePage):
    cl = custom_logger(logging.INFO)

    def __init__(self,driver):
        super(MobilePage, self).__init__(driver)
        self.driver = driver
        self.utill = Utilities()


    #locator
    _mobile = "MOBILE"
    _sort = "//select[@title='Sort By']"
    _Iphone = "IPHONE"
    _samsung = "SAMSUNG GALAXY"
    _sony = "SONY XPERIA"
    _expected_list1 = ['IPHONE', 'SAMSUNG GALAXY', 'SONY XPERIA']
    _expected_list2 = ['SONY XPERIA', 'SAMSUNG GALAXY', 'IPHONE']
    _tv = "TV"
    _grid_view = "//strong[@title='Grid']"
    _list_view = "List"
    _value = "//span[@id='product-price-1']/child::span"
    _add_to_cart = "//a[@title='Xperia']//following-sibling::div//span[text()='Add to Cart']"
    _cart_quantity = "//input[@data-cart-item-id='MOB001' and @title='Qty']"
    _update = "//button[@title='Update']/span/span"
    _error = "//span[text()='Some of the products cannot be ordered in requested quantity.']"
    _compare_xperia = "//a[@title='Xperia']//following-sibling::div/child::div/child::div/child::ul/li/a[text()='Add to Compare']"
    _compare_apple = "//a[@title='IPhone']//following-sibling::div/child::div/child::div/child::ul/li/a[text()='Add to Compare']"
    _compare_button = "//span[text()='Compare']"
    _iphone_new = "//a[text()='IPhone']"
    _close_window = "//span[text()='Close Window']"


    def mobile_tab(self):
        self.elementClick(self._mobile,"link")


    def sort_by_name(self):
        self.get_element_dropdown_value(locator=self._sort,locatorType="xpath",selectType='text',value="Name")

    def sort_by_price(self):
        self.get_element_dropdown_value(locator=self._sort,locatorType='xpath',selectType='text',value='Price')



    def sort_result_name(self):
        sort_result_list = [self.getText(self._Iphone,"link"),self.getText(self._samsung,"link"),self.getText(self._sony,"link")]
        print(sort_result_list)
        return self.utill.listcompare(expectedList=self._expected_list1,actualList=sort_result_list)

    def sort_result_price(self):
        sort_result_list = [self.getText(self._sony,"link"),self.getText(self._samsung,"link"),self.getText(self._Iphone,"link")]
        print(sort_result_list)
        return self.utill.listcompare(expectedList=self._expected_list2,actualList=sort_result_list)

    def add_to_cart(self):
        self.elementClick(self._add_to_cart,'xpath')

    def enter_cart_quantity_and_update(self):
        self.elementSend(self._cart_quantity,'xpath','1000')
        self.explicitwait(self._update,'xpath',20,0.1)
        self.elementClick(self._update,'xpath')
        return self.isElementDisplayed(self._error,'xpath')


    def click_tv_tab(self):
        self.elementClick(self._tv,'link')
        print('clicked on Tv')


    def click_list_view(self):
        self.elementClick(self._list_view,'link')


    def sony_price_grid_view(self):
        value1 = self.getText(self._value,'xpath')
        return value1

    def sony_price_list_view(self):
        value2 = self.getText(self._value,'xpath')
        return value2




    def mobile_sort_by_name(self):
        self.mobile_tab()
        self.sort_by_name()
        return self.sort_result_name()

    def mobile_sort_by_price(self):
        self.mobile_tab()
        self.sort_by_price()
        return self.sort_result_price()

    def verify_price_different_view(self):
        self.click_list_view()
        value1 = self.sony_price_list_view()
        value2 = self.sony_price_grid_view()
        return self.utill.verify_value(value1,value2)

    def verify_max_cart_error(self):
        self.add_to_cart()
        return self.enter_cart_quantity_and_update()

    def click_compare_(self):
        self.elementClick(self._compare_xperia,'xpath')
        self.elementClick(self._compare_apple,'xpath')
        self.elementClick(self._compare_button,'xpath')
        self.switching_to_window()
        result1 = self.isElementDisplayed(self._iphone_new,'xpath')
        self.elementClick(self._close_window,'xpath')
        return result1
Exemple #13
0
class SeleniumDriver():
    cl = custom_logger(logging.INFO)

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

        self.actions = ActionChains(self.driver)

    def ByType(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 == "link":
            return By.LINK_TEXT
        elif locatorType == "partial link":
            return By.PARTIAL_LINK_TEXT
        elif locatorType == "name":
            return By.NAME
        elif locatorType == "tag":
            return By.TAG_NAME
        elif locatorType == "class":
            return By.CLASS_NAME

        else:
            self.cl.info("Invalid Locatortype " + str(locatorType))

    def findElement(self, locator):
        element = None
        try:
            element = self.driver.find_element(locator["locatorType"],
                                               locator["locatorValue"])
            self.driver.execute_script("arguments[0].scrollIntoView(true);",
                                       element)
            self.driver.execute_script(
                "arguments[0].style.border='3px solid red'", element)
            self.cl.info("Element :: " + str(element) +
                         "found for locator :: " +
                         str(locator["locatorValue"]))

        except Exception as e:
            self.cl.info("Element could not be found for :: " +
                         str(locator["locatorValue"]))
            print_stack()
        return element

    def findElements(self, locator):
        element = []
        try:
            element = self.driver.find_elements(locator["type"],
                                                locator["value"])
            self.cl.info("Element :: " + str(element) +
                         "found for locator :: " + str(locator))

        except Exception as e:
            self.cl.info("Element could not be found for :: " + str(locator))
            print_stack()
        return element

    def get_element_dropdown_value(self, locator, selectType, value):
        try:
            element = self.findElement(locator)

            sel = Select(element)
            if selectType == "Value":
                sel.select_by_value(value)
                self.cl.info("Selected element with Name " + str(value) +
                             " from the drop down using Value")

            elif selectType == "text":
                sel.select_by_visible_text(value)
                self.cl.info("Selected element with value " + str(value) +
                             " from the drop down using Visible Text")

            elif selectType == "index":
                sel.select_by_index(value)
                self.cl.info("Selected element with index " + str(value) +
                             " from the drop down using Index position")

        except Exception as e:
            self.cl.info(
                "Unable to select element from the dropdown. Exception occurred :: "
                + str(e))
            print_stack()

    def elementClick(self, locator):
        try:
            element = self.findElement(locator)
            element.click()
            self.cl.info("Clicked on Element : " + str(element))

        except Exception as e:
            self.cl.info("Unable to click the element: " + locator +
                         ". Exception occured :: " + str(e))
            print_stack()

    def elementSend(self, locator, message):
        try:
            element = self.findElement(locator)
            element.clear()
            element.send_keys(message)
            self.cl.info("Text : " + str(message) + " entered on locator: " +
                         str(locator["locatorValue"]))
        except Exception as e:
            self.cl.info("Unable to send the message on locator: " +
                         str(locator["locatorValue"]) + "Exception :: " +
                         str(e))
            print_stack()

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

    def getText(self, locator):
        element_text = None
        try:
            element = self.findElement(locator)
            element_text = element.text
            self.cl.info("Text of the element : " + locator + " is " +
                         element_text)
            return element_text
        except Exception as e:
            self.cl.info("Unable to find the text for element : " +
                         str(locator["locatorValue"]) +
                         ". Following Exception occured :: " + str(e))
            print_stack()
        return element_text

    def getTextElementList(self, locator):
        elementText = []
        elementText2 = []
        try:
            element = self.findElements(locator)
            for item in element:
                itemtext = item.text
                elementText.append(itemtext)

            elementText2 = list(filter(None, elementText))
            self.cl.info(elementText2)
            return elementText2

        except Exception as e:
            self.cl.info(
                "Unable to return text for elements. Following Exception occurred :: "
                + str(e))
            print_stack()
        return elementText2

    def getAttribute(self, locator, attributeType):
        elementAttribute = None
        try:
            element = self.findElement(locator)
            elementAttribute = element.get_attribute(attributeType)
            self.cl.info("Value of Attribute :: " + attributeType + " is " +
                         str(elementAttribute))
            return elementAttribute
        except Exception as e:
            self.cl.info(
                "Unable to find the value of attribute for element : " +
                str(locator["locatorValue"]) +
                ". Following exception occurred :: " + str(e))
            print_stack()
        return elementAttribute

    def getAttributelist(self, locator, attributeType):
        element_attribute = []

        try:
            element = self.findElements(locator)
            for item in element:
                elementAttribute = item.get_attribute(attributeType)
                element_attribute.append(elementAttribute)
                self.cl.info("Value of Attribute :: " + attributeType +
                             " is " + elementAttribute)
            return element_attribute

        except Exception as e:
            self.cl.info(
                "Unable to find the value of attribute for element : " +
                str(locator["locatorValue"]) + " exception :: " + str(e))
            print_stack()
        return element_attribute

    def get_value_of_css_property(self, locator, attributeType):
        cssAttributeProperty = None
        try:
            element = self.findElement(locator)
            cssAttributeProperty = element.value_of_css_property(
                property_name=attributeType)
            self.cl.info("Value of CSS Attribute :: " + attributeType +
                         " is " + cssAttributeProperty)
            if attributeType == 'Color':
                formatted_name = Color.from_string(cssAttributeProperty).hex
                self.cl.info("Value of CSS Attribute :: " + attributeType +
                             " in HEX format is " + cssAttributeProperty)
                return formatted_name
            else:
                return cssAttributeProperty

        except Exception as e:
            self.cl.info(
                "Unable to find the value of attribute for element : " +
                str(locator["locatorValue"]) +
                ". Following Exception occurred :: " + str(e))
            print_stack()
        return cssAttributeProperty

    def explicitwait(self, locator, time, poll):
        try:

            wait = WebDriverWait(self.driver,
                                 timeout=time,
                                 poll_frequency=poll,
                                 ignored_exceptions=[
                                     ElementNotInteractableException,
                                     ElementNotVisibleException,
                                     NoSuchElementException, TimeoutException,
                                     StaleElementReferenceException,
                                     ElementClickInterceptedException
                                 ])
            self.cl.info("Waiting to click on element : " +
                         str(locator["locatorValue"]) + "for time " +
                         str(time) + "sec")
            element = wait.until(EC.element_to_be_clickable((locator)))
            self.cl.info("Element is Available for action")

        except:
            self.cl.info("Unable to find the element")
            print_stack()

    def explicit_wait_for_iframe(self, locator, index, time, poll):
        try:

            wait = WebDriverWait(self.driver,
                                 timeout=time,
                                 poll_frequency=poll,
                                 ignored_exceptions=[
                                     NoSuchFrameException,
                                     NoSuchElementException, TimeoutException
                                 ])
            self.cl.info("Waiting to find : " + str(locator["locatorValue"]) +
                         "with index position:: " + str(index) + "for time " +
                         str(time) + "sec")
            element = wait.until(
                EC.frame_to_be_available_and_switch_to_it(
                    (self.driver.find_elements_by_tag_name(locator)[index])))
            self.cl.info("iFrame is Available for switching")

        except TimeoutException:
            self.cl.info("Unable to find the element")

    def isElementPresent(self, locator):
        try:
            element = self.findElements(locator)
            self.cl.info(element)
            if len(element) > 0:
                self.cl.info("Element with locator " +
                             str(locator["locatorValue"]) + "is present")
                return True
            else:
                self.cl.info("Element with locator " +
                             str(locator["locatorValue"]) + "is not present")
                return False

        except Exception as e:
            self.cl.info("exception occured :: " + str(e))
            print_stack()
            return False

    def elementclear(self, locator):
        element = None
        try:
            element = self.findElement(locator)
            element.clear()
            self.cl.info("Cleared Element : " + str(element))

        except Exception as e:
            self.cl.info("Unable to find element. Exception :: " + str(e))
            print_stack()

    def savescreenshots(self, resultMessage):
        filename = resultMessage + str(round(time.time() * 10000)) + ".png"
        screenshotDirectory = "..//screenshots//"
        relativeFilename = screenshotDirectory + filename

        currentDirectory = os.path.dirname(__file__)
        destinationPath = os.path.join(currentDirectory, relativeFilename)

        destinationFolder = os.path.join(currentDirectory, screenshotDirectory)

        try:
            if not os.path.exists(destinationFolder):
                os.makedirs(destinationFolder)
            self.driver.save_screenshot(destinationPath)
            self.cl.info("### Screenshot saved at path: " + destinationPath)
        except:
            self.cl.warning("### Exception Occurred")
            print_stack()

    def isElementDisplayed(self, locator):
        try:
            element = self.findElement(locator)
            isDisplayed = element.is_displayed()

            if isDisplayed is True:
                self.cl.info("Element is displayed with locator :: " +
                             str(locator["locatorValue"]))
                return True
            else:
                self.cl.info("Element is not displayed with locator :: " +
                             str(locator["locatorValue"]))
                return False

        except Exception as e:
            self.cl.warning(
                "Exception occurred while executing isElementDisplayed :: exception occurred :: "
                + str(e))
            print_stack()
            return False

    def scrollingVertical(self, direction):
        direction = direction.lower()
        try:
            if direction == "up":
                self.driver.execute_script("window.scrollBy(0,-1000);")
                self.cl.info("Scrolling the screen up")

            if direction == "down":
                self.driver.execute_script("window.scrollBy(0,700);")
                self.cl.info("Scrolling the screen down")

        except:
            self.cl.warning(
                "Exception occurred when trying to scroll the screen")
            print_stack()

    def scrollingHorizontal(self, direction):
        direction = direction.lower()
        try:
            if direction == "left":
                self.driver.execute_script("window.scrollBy(-600,0);")
                self.cl.info("Scrolling the screen up")

            if direction == "right":
                self.driver.execute_script("window.scrollBy(1100,0);")
                self.cl.info("Scrolling the screen down")

        except:
            self.cl.warning(
                "Exception occured when trying to scroll the screen")
            print_stack()

    def switchFrame(self, value):
        try:
            self.driver.switch_to.frame(value)
            self.cl.info("Switched to Iframe :: " + str(value))

        except Exception as e:
            self.cl.error("Error while switching to Iframe" +
                          ". Following Exception occurred :: " + str(e))
            print_stack()

    def switchParentFrame(self):
        try:
            self.driver.switch_to.parent_frame()
        except Exception as e:
            self.cl.info(
                "Unable to  to Parent Frame. Following Exception occurred :: "
                + str(e))
            print_stack()

    def switch_default_content(self):
        try:
            self.driver.switch_to.default_content()
            self.cl.info("Switched to default content")

        except Exception as e:
            self.cl.error(
                "Error while switching to Default Content. Exception occurred :: "
                + str(e))
            print_stack()

    def elementSendSpecial(self, locator, message):
        try:
            element = self.findElement(locator)
            for items in message:
                element.send_keys(items)
            self.cl.info("Text : " + message + " entered on locator: " +
                         str(locator["locatorValue"]))
        except Exception as e:
            self.cl.info("Unable to send the message on locator: " +
                         str(locator["locatorValue"]) +
                         ". Following Exception occurred :: " + str(e))
            print_stack()

    def slider(self, locator, xcord, ycord):
        try:
            element = self.findElement(locator)
            self.actions.drag_and_drop_by_offset(source=element,
                                                 xoffset=xcord,
                                                 yoffset=ycord).perform()
        except Exception as e:
            self.cl.info(
                "Exception occurred during sliding. Following Exception occurred :: "
                + str(e))
            print_stack()

    def double_clickk(self, locator):
        try:
            element = self.findElement(locator)
            self.actions.double_click(element).perform()
            self.cl.info("Double Clicked on :: " + str(element))
        except Exception as e:
            self.cl.info(
                "Exception occurred during Double Click. Following Exception occurred :: "
                + str(e))
            print_stack()

    def browserRefresh(self):
        self.driver.refresh()

    def current_handle_window(self):
        current_window = None
        try:
            current_window = self.driver.current_window_handle
            self.cl.info("The current window handle is :: " +
                         str(current_window))
            #return current_window

        except Exception as e:
            self.cl.info(
                'Unable to get the current window. Exception Occurred :: ' +
                str(e))
        return current_window

    def all_window_handles(self):
        all_window_available = None
        try:
            all_window_available = self.driver.window_handles
            self.cl.info("All available Window's are :: " + str(all_handles))

        except Exception as e:
            self.cl.info(
                'Unable to get all the windows. Exception Occured :: ' +
                str(e))
        return all_window_available

    def switching_to_window(self):
        try:
            current_window = self.current_handle_window()
            all_window_available = self.all_window_handles()

            for items in all_window_available:
                if items != current_window:
                    self.driver.switch_to.window(items)
                    self.cl.info("Switched to window :: " + str(items))

        except Exception as e:
            self.cl.info(
                "Unable to switch to new window. Following Exception occurred :: "
                + str(e))

    def switch_to_parent_window(self):
        try:
            all_window_available = self.all_window_handles()

            for items in all_window_available:
                if items == all_windows[0]:
                    self.driver.switch_to.window(items)
                    self.cl.info("Switched to window :: " + str(items))

        except Exception as e:
            self.cl.info(
                "Unable to  to new window. Following Exception occurred :: " +
                str(e))

    def browserback(self):
        self.driver.back()

    def browserForward(self):
        self.driver.forward()

    def action(self):
        try:
            self.actions.key_down(Keys.DOWN).key_down(Keys.ENTER).perform()
            # self.actions.send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform()

        except Exception as e:
            self.cl.info(
                "Unable to press ENTER key. Following Exception occurred :: " +
                str(e))

    def enter(self):
        try:
            self.actions.key_down(Keys.ENTER).key_up(Keys.ENTER).perform()
            self.cl.info("Pressed ENTER")
        except Exception as e:
            self.cl.info(
                "Unable to press ENTER key. Following Exception occurred :: " +
                str(e))

    def close_new_window(self):
        try:
            self.actions.key_down(Keys.CONTROL).send_keys('W').perform()
            self.cl.info("Pressing CTRL + W to close the new window")
        except Exception as e:
            self.cl.info(
                "Unable to perform Action :: CTRL + W. Following Exception occurred :: "
                + str(e))
            print_stack()

    def js_element_click(self, locator):
        element - None
        try:
            element = self.findElement(locator)
            self.driver.execute_script("arguments[0].click();", element)

        except Exception as e:
            self.cl.info("Unable to click on element :: " + str(element) +
                         ". Following Exception occurred :: " + str(e))

    def js_select_list(self, locator, message):
        try:
            element = self.findElement(locator)
            self.driver.execute_script(
                "arguments[0].removeAttribute('readonly','readonly');",
                element)
            element.send_keys(message)
            self.cl.info("Sending message :: " + str(message) + "locator :: " +
                         str(locator["locatorValue"]))

        except Exception as e:
            self.cl.info("Exception Occurred. Following Exception :: " +
                         str(e))
            print_stack()

    def stop_page_load(self):
        try:
            self.driver.execute_script("return window.stop")
            self.cl.info("Page load stop")
        except Exception as e:
            self.cl.info(
                "Unable to stop the page load. Following Exception occurred :: "
                + str(e))

    # def js_double_click(self,locator,locatorType):
    #     try:
    #         element = self.findElement(locator,locatorType)
    #         self.driver.execute_script("var evt = document.createEvent('MouseEvents');"+
    #         "evt.initMouseEvent('dblclick',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);"+
    #         "arguments[0].dispatchEvent(evt);", element);

    #         self.cl.info("Double clicked element :: " + str(element))

    #     except:
    #         raise Exception
    #         self.cl.info("Unable to Double click element :: " + str(element))

    def right_clickk(self, locator):
        element = None
        try:
            element = self.findElement(locator)
            self.actions.context_click(element).key_down(Keys.DOWN).key_down(
                Keys.ENTER).perform()

        except Exception as e:
            self.cl.info("Unable to right click on element " + str(element) +
                         ". Following Exception Occurred :: " + str(e))

    def driver_get(self, url):
        self.driver.get(url)
class SeleniumBase():
    enableScreenshot = False
    cl = custom_logger(logging.INFO)

    def __init__(self, driver):
        self.driver = driver
        self.actions = ActionChains(self.driver)
        self.util = Utilities()

    @classmethod
    def EnableScreenshotForTest(cls, screenshot):
        cls.enableScreenshot = screenshot

    """
    Below method is deprecated
    """

    # def ByType(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 == "link":
    #         return By.LINK_TEXT
    #     elif locatorType == "partial link":
    #         return By.PARTIAL_LINK_TEXT
    #     elif locatorType == "name":
    #         return By.NAME
    #     elif locatorType == "tag":
    #         return By.TAG_NAME
    #     elif locatorType == "class":
    #         return By.CLASS_NAME
    #
    #     else:
    #         self.cl.info("Invalid Locatortype " + str(locatorType))

    def visit(self, url):
        try:
            self.driver.get(url)
            element = self.driver.find_elements(By.TAG_NAME, 'title')
            self.cl.info("The element list is :: " + str(element))
            if len(element) == 0:
                i = 0
                while i < 5:
                    if len(element) == 0:
                        i += 1
                        time.sleep(2)
                        self.cl.info(
                            "Website is not loaded. Reloading the website for :: "
                            + str(i) + 'st time')
                        self.driver.get(url)
                        element = self.driver.find_elements(
                            By.TAG_NAME, 'title')

                    else:
                        self.cl.info("The element list is :: " + str(element))
                        break
            else:
                self.cl.info("Website is loaded.")
        except Exception as e:
            self.cl.error("Unable to open URL from :: " + str(url) + '. ' +
                          "Exception Occurred :: " + str(e.__class__.__name__))

    # def visit(self, url):
    #     try:
    #         i = 0
    #         while i < 5:
    #             self.driver.get(url)
    #             element = self.driver.find_elements(By.TAG_NAME, 'title')
    #             self.cl.info("The element list is :: " + str(element))
    #             if len(element) < 1:
    #                 i += 1
    #                 time.sleep(2)
    #                 self.cl.info("Website is not loaded. Reloading the website for :: " + str(i) + 'st time')
    #                 self.driver.get(url)
    #
    #             else:
    #                 self.cl.info("Website is loaded.")
    #                 break
    #     except Exception as e:
    #         self.cl.error("Unable to open URL from :: " + str(url) + '. ' + "Exception Occurred :: " + str(
    #             e.__class__.__name__))

    def findElement(self, locator, timeout=5, poll_frequency=0):
        element = None

        try:
            wait = WebDriverWait(self.driver,
                                 timeout=timeout,
                                 poll_frequency=poll_frequency)
            self.cl.info("Waiting for " + str(timeout) +
                         " seconds to find the element for locator :: " +
                         str(locator))
            element = wait.until(ec.presence_of_element_located(locator))
            self.cl.info("Element :: " + str(element.id) +
                         " found for locator :: " + str(locator) +
                         ". Session_id :: " + str(element.parent.session_id))

            # element = self.driver.find_element(*locator)
            self.driver.execute_script("arguments[0].scrollIntoView(true);",
                                       element)
            self.driver.execute_script(
                "arguments[0].style.border='3px solid red'", element)
            # if self.enableScreenshot:
            #     self.saveScreenshots()

        except Exception as e:
            self.cl.error("No Element found for locator :: " + str(locator) +
                          '. ' + "Exception Occurred :: " +
                          str(e.__class__.__name__))
            # print_stack()()
        return element

    def findElements(self, locator):
        element = []
        try:
            element = self.driver.find_elements(*locator)
            if len(element) > 0:
                self.cl.info("Elements list returned::  " + str(element) +
                             " for locator :: " + str(locator))

            else:
                self.cl.info("Elements not found for locator :: " +
                             str(locator) + ". Empty List returned " +
                             str(element))

        except Exception as e:
            self.cl.error("Element could not be found for :: " + str(locator) +
                          '. ' + str(e.__class__.__name__) + ' ' + str(e))
            # print_stack()()
        return element

    def selectByIndex(self, locator, value, element=None):
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                sel = Select(element)
                sel.select_by_index(value)
                self.cl.info("Selected element with index " + str(value) +
                             " from the drop down using Index position")
                # if self.enableScreenshot:
                #     self.saveScreenshots()

            else:
                self.cl.error(
                    "Unable to select element by Index. No element was found for locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error(
                "Unable to select element by Index. Exception occurred :: " +
                '. ' + str(e.__class__.__name__) + str(e))
            # print_stack()()

    def selectByVisibleText(self, locator, value, element=None):
        try:
            if locator:
                element = self.findElement(locator)
                # self.saveScreenshots()
            if element:
                sel = Select(element)
                sel.select_by_visible_text(value)
                self.cl.info("Selected element with value " + str(value) +
                             " from the drop down using Visible Text")
                # if self.enableScreenshot:
                #     self.saveScreenshots()
            else:
                self.cl.error(
                    "Unable to select element by Visible Text. No element was found for locator :: "
                    + str(locator))
        except Exception as e:
            self.cl.error(
                "Unable to select element by Visible Text. Exception occurred :: "
                + '. ' + str(e.__class__.__name__) + str(e))
            # print_stack()()

    def selectByValue(self, locator, value, element=None):
        try:
            if locator:
                element = self.findElement(locator)
                # self.saveScreenshots()
            if element:
                sel = Select(element)
                sel.select_by_value(value)
                self.cl.info("Selected element with Name " + str(value) +
                             " from the drop down using Value")
                # if self.enableScreenshot:
                #     self.saveScreenshots()

            else:
                self.cl.error(
                    "Unable to select element by Visible Text. No element was found for locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error(
                "Unable to select element from the dropdown. Exception occurred :: "
                + '. ' + str(e.__class__.__name__) + str(e))
            # print_stack()()

    def visibilityOfElementLocated(self,
                                   locator,
                                   timeout=10,
                                   poll_frequency=0.2):
        element = None
        try:
            wait = WebDriverWait(self.driver,
                                 timeout=timeout,
                                 poll_frequency=poll_frequency)
            self.cl.info("Waiting for " + str(timeout) +
                         " seconds for checking the element visibility :: " +
                         str(locator))
            element = wait.until(ec.visibility_of_element_located(locator))

            self.cl.info("Element :: " + str(element.id) +
                         " is visible on page for locator :: " + str(locator) +
                         ". Session_id :: " + str(element.parent.session_id))
            self.driver.execute_script("arguments[0].scrollIntoView(true);",
                                       element)
            self.driver.execute_script(
                "arguments[0].style.border='3px solid red'", element)
            if self.enableScreenshot:
                self.saveScreenshots()

        except Exception as e:
            self.cl.error("Unable to find element with locator :: " +
                          str(locator) + '. Exception occurred ' +
                          str(e.__class__.__name__) + str(e))
        return element

    def elementClick(self, locator, element=None):
        try:
            if locator:
                element = self.findElement(locator)

            if element:
                if self.enableScreenshot:
                    self.saveScreenshots()
                element.click()
                self.cl.info("Clicked on Element : " + str(element.id))
            else:
                self.cl.error(
                    "Unable to click on locator. No element was found for locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error("Unable to click the element: " + str(locator) +
                          ". Exception occurred :: " + '. ' +
                          str(e.__class__.__name__) + str(e))
            # print_stack()()

    def elementSend(self, locator, message, element=None):
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                # if self.enableScreenshot:
                #     self.saveScreenshots()
                element.send_keys(message)
                self.cl.info("Text :: " + str(message) +
                             " entered on element :: " + str(element.id))
                # if self.enableScreenshot:
                #     self.saveScreenshots()
            else:
                self.cl.error(
                    "Unable to send the message on the element. No Element found for the locator ::  "
                    + str(locator))

        except Exception as e:
            self.cl.error("Unable to send the message on locator: " +
                          str(locator) + "Exception :: " + '. ' +
                          str(e.__class__.__name__) + str(e))
            # print_stack()()

    def verifyExactTitle(self, expectedTitle, timeout=10, poll_frequency=0.2):
        try:
            wait = WebDriverWait(self.driver,
                                 timeout=timeout,
                                 poll_frequency=poll_frequency)
            result = wait.until(ec.title_is(expectedTitle))
            if result:
                self.cl.info("The actual title of the webpage is :: " +
                             str(self.driver.title))
                self.cl.info("The expected title is :: " + str(expectedTitle))
                self.cl.info("Title Match")
            else:
                self.cl.info("Title doesnt match")

        except Exception as e:
            self.cl.error(
                "Unable to fetch the current page title. Exception occurred :: "
                + '. ' + str(e.__class__.__name__) + str(e))
            result = False
            # print_stack()()
        return result

    def verifyTitleContains(self, title, timeout=15, poll_frequency=0.2):
        try:
            wait = WebDriverWait(self.driver,
                                 timeout=timeout,
                                 poll_frequency=poll_frequency)
            result = wait.until(ec.title_contains(title))
            if result:
                self.cl.info("'" + title + "'" +
                             " is part of the page title :: " +
                             str(self.driver.title))
            else:
                self.cl.info("Title of the page doesnt contain text :: " +
                             title)

        except Exception as e:
            self.cl.error(
                "Unable to fetch the current page title. Exception occurred :: "
                + '. ' + str(e.__class__.__name__) + str(e))
            result = False
            # print_stack()()
        return result

    def getElementText(self, locator, element=None):
        element_text = None
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                element_text = element.text
                self.cl.info("Text of the element : " + str(locator) + " is " +
                             element_text)
            else:
                self.cl.error(
                    "Unable to find the text for element. No Element found for locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error("Unable to find the text for element : " +
                          str(locator) + ". Following Exception occurred :: " +
                          '. ' + str(e.__class__.__name__) + str(e))
            # print_stack()()

        return element_text

    def getElementsText(self, locator, elements=None):
        elementText = []
        try:
            if locator:
                elements = self.findElements(locator)
            if len(elements) > 0:
                for item in elements:
                    itemText = item.text
                    elementText.append(itemText)
                self.cl.info("The TEXT for Elements are :: " +
                             str(elementText))

            else:
                self.cl.error(
                    "Unable to find text for the element list. No elements found for the locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error(
                "Unable to return text for elements. Following Exception occurred :: "
                + '. ' + str(e.__class__.__name__) + str(e))
            # print_stack()()
        return elementText

    def getAttribute(self, locator, attributeType, element=None):
        elementAttribute = None
        try:
            if locator:
                element = self.findElement(locator)

            if element:
                elementAttribute = element.get_attribute(attributeType)
                self.cl.info("Value of Attribute :: " + attributeType +
                             " is " + str(elementAttribute))
            else:
                self.cl.error("Unable to get the value of attribute " +
                              attributeType +
                              ". No element was found for locator :: " +
                              str(locator))
        except Exception as e:
            self.cl.error(
                "Unable to find the value of attribute for element : " +
                str(locator) + ". Following exception occurred :: " + '. ' +
                str(e.__class__.__name__) + str(e))
            # print_stack()()
        return elementAttribute

    def getAttributeList(self, locator, attributeType, elements=None):
        element_attribute = []

        try:
            if locator:
                elements = self.findElements(locator)
            if len(elements) > 0:
                for item in elements:
                    elementAttribute = item.get_attribute(attributeType)
                    element_attribute.append(elementAttribute)
                    self.cl.info("Value of attribute")
            self.cl.info("Attribute list is :: " + str(element_attribute))

        except Exception as e:
            self.cl.error(
                "Unable to find the value of attribute for element : " +
                str(locator) + " exception :: " + str(e))
            #print_stack()()
        return element_attribute

    def getValueOfCssProperty(self, locator, attributeType, element=None):
        cssAttributeProperty = None
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                cssAttributeProperty = element.value_of_css_property(
                    property_name=attributeType)
                self.cl.info("Value of CSS Attribute :: " + attributeType +
                             " is " + cssAttributeProperty)
            # if attributeType == 'Color': formatted_name = Color.from_string(cssAttributeProperty).hex self.cl.info(
            # "Value of CSS Attribute :: " + attributeType + " in HEX format is " + cssAttributeProperty) return
            # formatted_name
            else:
                self.cl.error(
                    "Unable to find the value of css property for element. No element was found for the "
                    "locator :: " + str(locator))
        except Exception as e:
            self.cl.error(
                "Unable to find the value of attribute for element : " +
                str(locator) + ". Following Exception occurred :: " + '. ' +
                str(e.__class__.__name__) + str(e))
            # print_stack()()
        return cssAttributeProperty

    def waitToClickElement(self, locator, time=5, poll=0.2):
        element = None
        try:

            wait = WebDriverWait(self.driver,
                                 timeout=time,
                                 poll_frequency=poll,
                                 ignored_exceptions=[
                                     ElementNotInteractableException,
                                     ElementNotVisibleException,
                                     NoSuchElementException, TimeoutException,
                                     StaleElementReferenceException,
                                     ElementClickInterceptedException
                                 ])
            self.cl.info("Waiting to click on element : " + str(locator) +
                         "for time " + str(time) + "sec")
            element = wait.until(ec.element_to_be_clickable(locator))
            self.cl.info("Element is Available for action")

        except Exception as e:
            self.cl.error("Unable to find the element " +
                          str(e.__class__.__name__) + str(e))
            # print_stack()()
        return element

    def waitForIframe(self, locator, index=None, time=10, poll=0.5):
        try:

            wait = WebDriverWait(self.driver,
                                 timeout=time,
                                 poll_frequency=poll,
                                 ignored_exceptions=[
                                     NoSuchFrameException,
                                     NoSuchElementException, TimeoutException
                                 ])
            self.cl.info("Waiting to find iframe with : " + str(locator) +
                         "with index position:: " + str(index) + "for time " +
                         str(time) + "sec")
            wait.until(ec.frame_to_be_available_and_switch_to_it(locator))
            self.cl.info("iFrame is Available for switching")

        except Exception as e:
            self.cl.error(
                "Unable to find the iframe. Following Exception occurred " +
                '. ' + str(e.__class__.__name__) + str(e))

    def elementClear(self, locator, element=None):
        try:
            if locator:
                element = self.findElement(locator)
                if self.enableScreenshot:
                    self.saveScreenshots()

            if element:
                element.clear()
                self.cl.info("Cleared Element : " + str(element))
                if self.enableScreenshot:
                    self.saveScreenshots()
            else:
                self.cl.error(
                    "Unable to clear the element. No element found for locator :: "
                    + str(locator))
        except Exception as e:
            self.cl.error("Unable to clear element. Exception :: " + '. ' +
                          str(e.__class__.__name__) + str(e))
            # print_stack()()

    def full_screenshot_with_scroll(self, driver, save_path):
        from io import StringIO
        from io import BytesIO
        from PIL import Image

        # initiate value

        save_path = save_path
        img_li = []  # to store image fragment
        offset = 0  # where to start

        # js to get height
        height = self.driver.execute_script(
            "return Math.max("
            "document.documentElement.clientHeight, window.innerHeight);")

        # js to get the maximum scroll height
        # Ref--> https://stackoverflow.com/questions/17688595/finding-the-maximum-scroll-position-of-a-page
        max_window_height = self.driver.execute_script(
            "return Math.max("
            "document.body.scrollHeight, "
            "document.body.offsetHeight, "
            "document.documentElement.clientHeight, "
            "document.documentElement.scrollHeight, "
            "document.documentElement.offsetHeight);")

        # looping from top to bottom, append to img list
        # Ref--> https://gist.github.com/fabtho/13e4a2e7cfbfde671b8fa81bbe9359fb
        while offset < max_window_height:
            # Scroll to height
            driver.execute_script(f"window.scrollTo(0, {offset});")
            img = Image.open(BytesIO((self.driver.get_screenshot_as_png())))
            img_li.append(img)
            offset += height

        # In case it is not a perfect fit, the last image contains extra at the top.
        # Crop the screenshot at the top of last image.
        extra_height = offset - max_window_height
        if extra_height > 0 and len(img_li) > 1:
            pixel_ratio = driver.execute_script(
                "return window.devicePixelRatio;")
            extra_height *= pixel_ratio
            last_image = img_li[-1]
            width, height = last_image.size
            box = (0, extra_height, width, height)
            img_li[-1] = last_image.crop(box)

        # Stitch image into one
        # Set up the full screen frame
        img_frame_height = sum([img_frag.size[1] for img_frag in img_li])
        img_frame = Image.new("RGB", (img_li[0].size[0], img_frame_height))
        offset = 0
        for img_frag in img_li:
            img_frame.paste(img_frag, (0, offset))
            offset += img_frag.size[1]
        img_frame.save(save_path)

    def saveScreenshots(self):
        test_name = os.environ.get('PYTEST_CURRENT_TEST').split(' ')[
            0]  # fetch the current TestName
        new_name = test_name.split("::")
        filename = new_name[-1] + "_" + self.util.generate_date_time() + ".png"
        screenshotDirectory = "..//logs//screenshots//" + str(
            datetime.date.today()) + "//"
        relativeFilename = screenshotDirectory + filename

        currentDirectory = os.path.dirname(__file__)
        destinationPath = os.path.join(currentDirectory, relativeFilename)

        destinationFolder = os.path.join(currentDirectory, screenshotDirectory)

        try:
            if not os.path.exists(destinationFolder):
                os.makedirs(destinationFolder)
            #self.driver.save_screenshot(destinationPath)
            self.full_screenshot_with_scroll(self.driver, destinationPath)
            self.cl.info("### Screenshot saved at path: " + destinationPath)
        except Exception as e:
            self.cl.error("### Exception Occurred " +
                          str(e.__class__.__name__) + str(e))
            # print_stack()()

    def getInnerText(self, locator, element=None):
        innerText = None
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                innerText = element.get_attribute("innerText")
                self.cl.info("InnerText of element is " + str(innerText))
            else:
                self.cl.error(
                    "Unable to get innerText of element. No element was found for locator :: "
                    + str(locator))
        except Exception as e:
            self.cl.error(
                "Unable to find the value of attribute for element : " +
                str(locator) + ". Following exception occurred :: " + '. ' +
                str(e.__class__.__name__) + str(e))
            # print_stack()()
        return innerText

    def isElementDisplayed(self, locator, element=None):
        try:
            if locator:
                element = self.findElement(locator)
                if self.enableScreenshot:
                    self.saveScreenshots()

            if element:
                result = element.is_displayed()
                if result:
                    self.cl.info("Element is displayed for locator :: " +
                                 str(locator))

                else:
                    self.cl.info("Element is not displayed for locator :: " +
                                 str(locator))
            else:
                self.cl.error(
                    "Element is not displayed. Unable to find element with locator :: "
                    + str(locator))
                result = False

        except Exception as e:
            self.cl.error("Element is not displayed with locator :: " +
                          str(locator) + " Exception occurred :: " + str(e))
            # print_stack()()
            result = False
        return result

    def scrollingVertical(self, direction):
        direction = direction.lower()
        try:
            if direction == "up":
                self.driver.execute_script("window.scrollBy(0,-1000);")
                self.cl.info("Scrolling the screen up")

            if direction == "down":
                self.driver.execute_script("window.scrollBy(0,700);")
                self.cl.info("Scrolling the screen down")

        except Exception as e:
            self.cl.error(
                "Exception occurred when trying to scroll the screen :: " +
                str(e.__class__.__name__) + str(e))
            # print_stack()()

    def scrollingHorizontal(self, direction):
        direction = direction.lower()
        try:
            if direction == "left":
                self.driver.execute_script("window.scrollBy(-600,0);")
                if self.enableScreenshot:
                    self.saveScreenshots()
                self.cl.info("Scrolling the screen up")

            if direction == "right":
                self.driver.execute_script("window.scrollBy(1100,0);")
                if self.enableScreenshot:
                    self.saveScreenshots()
                self.cl.info("Scrolling the screen down")

        except Exception as e:
            self.cl.error(
                "Exception occurred when trying to scroll the screen :: " +
                str(e.__class__.__name__) + str(e))
            # print_stack()()

    def switchFrame(self, value):
        try:
            self.driver.switch_to.frame(value)
            self.cl.info("Switched to Iframe :: " + str(value))

        except Exception as e:
            self.cl.error("Error while switching to Iframe" +
                          ". Following Exception occurred :: " +
                          str(e.__class__.__name__) + str(e))
            # print_stack()()

    def switchParentIframe(self):
        try:
            self.driver.switch_to.parent_frame()
            self.cl.info("Switch to Parent iFrame")
        except Exception as e:
            self.cl.error(
                "Unable to switch  to Parent Frame. Following Exception occurred :: "
                + str(e.__class__.__name__) + str(e))
            # print_stack()()

    def exitIframe(self):
        try:
            self.driver.switch_to.default_content()
            self.cl.info("Switched to default content. Iframe closed")

        except Exception as e:
            self.cl.error(
                "Error while switching to Default Content. Exception occurred :: "
                + str(e.__class__.__name__) + str(e))
            # print_stack()()

    # def elementSendSpecial(self, locator, message,element=None):
    #     try:
    #         element = self.findElement(locator)
    #         if element:
    #             for items in message:
    #                 element.send_keys(items)
    #         self.cl.info("Text : " + message + " entered on locator: " + str(locator))
    #
    #
    #     except Exception as e:
    #         self.cl.info(
    #             "Unable to send the message on locator: " + str(
    #                 locator["locatorValue"]) + ". Following Exception occurred :: " + str(e))
    #         #print_stack()()

    def slider(self, locator, XCORD, YCORD, element=None):
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                self.saveScreenshots()
                self.actions.drag_and_drop_by_offset(source=element,
                                                     xoffset=XCORD,
                                                     yoffset=YCORD).perform()
                self.saveScreenshots()
            else:
                self.cl.error(
                    "Unable to perform slider operation on element. No element was found for locator "
                    + str(locator))
        except Exception as e:
            self.cl.error(
                "Exception occurred during sliding. Following Exception occurred :: "
                + '. ' + str(e.__class__.__name__) + str(e))
            # print_stack()()

    def doubleClick(self, locator, element=None):
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                self.saveScreenshots()
                self.actions.double_click(element).perform()
                self.cl.info("Double Clicked on :: " + str(element))
            else:
                self.cl.error(
                    "Unable to perform double click on element. No element was found for locator :: "
                    + str(locator))
        except Exception as e:
            self.cl.error(
                "Exception occurred during Double Click. Following Exception occurred :: "
                + str(e.__class__.__name__) + str(e))
            # print_stack()()

    def browserRefresh(self):
        try:
            self.driver.refresh()
            self.cl.info("Refreshing the current window")
        except Exception as e:
            self.cl.error(
                "Unable to refresh the browser. Exception occurred :: " +
                str(e.__class__.__name__) + str(e))

    def currentBrowserWindow(self):
        current_window = None
        try:
            current_window = self.driver.current_window_handle
            self.cl.info("The current window is :: " + str(current_window))

        except Exception as e:
            self.cl.error(
                'Unable to get the current window. Exception Occurred :: ' +
                str(e.__class__.__name__) + str(e))

        return current_window

    def allBrowserWindow(self):
        all_window = None
        try:
            all_window = self.driver.window_handles
            self.cl.info("All available Window's are :: " + str(all_window))

        except Exception as e:
            self.cl.info(
                'Unable to get all the windows. Exception Occurred :: ' +
                str(e.__class__.__name__) + str(e))
        return all_window

    #
    def switchWindow(self, windowNumber: int):
        try:
            allWindow = self.allBrowserWindow()
            self.driver.switch_to.window(allWindow[windowNumber])
            self.cl.info("Switched to new window :: " +
                         str(allWindow[windowNumber]))
        except Exception as e:
            self.cl.info(
                "Unable to switch to new window. Following Exception occurred :: "
                + str(e.__class__.__name__) + " " + str(e))

    def browserBack(self):
        self.driver.back()

    def browserForward(self):
        self.driver.forward()

    def jsClick(self, locator, element=None):
        try:
            if locator:
                element = self.findElement(locator)
            if element:
                self.driver.execute_script("arguments[0].click();", element)
            else:
                self.cl.error(
                    "Unable to click on element. No element was found for locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error("Unable to click on element :: " + str(element) +
                          ". Following Exception occurred :: " +
                          str(e.__class__.__name__) + str(e))

    def js_select_list(self, locator, message):
        try:
            element = self.findElement(locator)
            self.driver.execute_script(
                "arguments[0].removeAttribute('readonly','readonly');",
                element)
            element.send_keys(message)
            self.cl.info("Sending message :: " + str(message) + "locator :: " +
                         str(locator["locatorValue"]))

        except Exception as e:
            self.cl.error("Exception Occurred. Following Exception :: " +
                          str(e))
            # print_stack()()

    def stopPageLoading(self):
        try:
            self.driver.execute_script("return window.stop")
            self.cl.info("Page load stop")
        except Exception as e:
            self.cl.error(
                "Unable to stop the page load. Following Exception occurred :: "
                + str(e.__class__.__name__) + str(e))

    # def js_double_click(self,locator,locatorType):
    #     try:
    #         element = self.findElement(locator,locatorType)
    #         self.driver.execute_script("var evt = document.createEvent('MouseEvents');"+
    #         "evt.initMouseEvent('dblclick',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);"+
    #         "arguments[0].dispatchEvent(evt);", element);

    #         self.cl.info("Double clicked element :: " + str(element))

    #     except:
    #         raise Exception
    #         self.cl.info("Unable to Double click element :: " + str(element))

    def rightClick(self, locator, element=None):

        try:
            if locator:
                element = self.findElement(locator)
            if element:
                self.actions.context_click(element).key_down(
                    Keys.DOWN).key_down(Keys.ENTER).perform()
                self.saveScreenshots()

            else:
                self.cl.error(
                    "Unable to perform right click on element. No element was found for locator :: "
                    + str(locator))

        except Exception as e:
            self.cl.error("Unable to right click on element " + str(element) +
                          ". Following Exception Occurred :: " +
                          str(e.__class__.__name__) + " " + str(e))

    def getCurrentUrl(self):
        currentUrl = None
        try:
            currentUrl = self.driver.current_url
            print("Current Page URL is :: " + str(currentUrl))

        except Exception as e:
            self.cl.error(
                "Unable to fetch the current URL. Following Exception Occurred :: "
                + str(e.__class__.__name__) + " " + str(e))

        return currentUrl

    def assertTitle(self, expectedTitle):
        actualTile = self.getTitle()
        assert_that(actualTile).is_equal_to(expectedTitle)

    def assertTitleContains(self, titleSubString):
        result = None
        try:
            result = WebDriverWait(self.driver, 15, 0.2).until(
                ec.title_contains(titleSubString))
            self.cl.info("The title of page is :: " + str(self.getTitle()))
            self.cl.info("Title of the Page contains text :: " +
                         str(titleSubString))

        except Exception as e:
            self.cl.error("Title of the Page does not contains text :: " +
                          str(titleSubString) +
                          ". Following Exception occurred :: " +
                          str(e.__class__.__name__) + " " + str(e))
        finally:
            assert_that(result).is_true()

    def assertElementDisplayed(self, locator, element=None):
        assert_that(self.isElementDisplayed(locator, element)).is_true()

    def assertText(self, locator, expectedText, element=None):
        text = self.getElementText(locator, element)
        assert_that(text).is_equal_to(expectedText)

    def assertTextContains(self, textSubString, locator, element=None):
        text = self.getElementText(locator, element)
        assert_that(text).contains_ignoring_case(textSubString)
Exemple #15
0
class WebDriverFactory:
    cl = custom_logger(logging.INFO)

    def __init__(self, browser, headless, url, mobile, device):
        self.browser = browser
        self.headless = headless
        self.baseUrl = url
        self.mobile = mobile
        self.device = device

    def get_browser_instance(self):
        try:
            if self.browser.lower() == "firefox":
                options = FirefoxOptions()
                if self.headless:
                    options.add_argument("--headless")
                    options.add_argument("-width=1920")
                    options.add_argument("-height=1080")
                # options.add_argument("--disable-gpu")
                profile = webdriver.FirefoxProfile()
                # options.add_argument("--private")
                profile.accept_untrusted_certs = True
                service = Service(executable_path=GeckoDriverManager(
                    cache_valid_range=10).install())
                driver = webdriver.Firefox(service=service,
                                           firefox_profile=profile,
                                           options=options)

            elif self.browser.lower() == "chrome":
                options = ChromeOptions()
                if self.headless:
                    options.add_argument('headless')
                    options.add_argument('window-size=1920x1080')
                if self.mobile:
                    mobile_emulation = {"deviceName": self.device}
                    options.add_experimental_option("mobileEmulation",
                                                    mobile_emulation)
                options.add_argument('ignore-certificate-errors')
                options.add_argument('--incognito')
                # options.add_argument('--start-maximized')
                options.add_experimental_option('useAutomationExtension',
                                                False)
                options.add_experimental_option("excludeSwitches",
                                                ["enable-automation"])
                # options.add_experimental_option("excludeSwitches", ["enable-logging"])
                options.add_argument('--log-level=3')
                service = Service(
                    ChromeDriverManager(cache_valid_range=10).install())
                driver = webdriver.Chrome(service=service, options=options)

            elif self.browser.lower() == "ie":
                driver = webdriver.Ie(IEDriverManager().install())

            elif self.browser.lower() == "edge":
                options = EdgeOptions()
                if self.headless:
                    options.add_argument('headless')
                    options.add_argument('window-size=1920x1080')
                options.use_chromium = True
                options.add_argument('ignore-certificate-errors')
                options.add_experimental_option('useAutomationExtension',
                                                False)
                options.add_argument('--inprivate')
                options.add_argument('--log-level=3')
                options.add_experimental_option("excludeSwitches",
                                                ["enable-automation"])
                service = Service(
                    EdgeChromiumDriverManager(cache_valid_range=10,
                                              log_level=1).install())
                driver = webdriver.Chrome(service=service, options=options)

            elif self.browser.lower() == 'browserstack':
                bs_local = Local()
                bs_local_args = {
                    "key": key,
                    "localIdentifier": localIdentifier
                }
                bs_local.start(**bs_local_args)
                driver = webdriver.Remote(command_executor=bb_url,
                                          desired_capabilities=browser_config)

            # elif self.browser.lower() =="docker":
            #     options = FirefoxOptions()
            #     options.add_argument("--headless")
            #     options.add_argument("-width=1920")
            #     options.add_argument("-height=1080")
            #     profile = webdriver.FirefoxProfile()
            #     # options.add_argument("--private")
            #     profile.accept_untrusted_certs = True
            #     driver = webdriver.Remote(command_executor="http://localhost:4444", options=options, browser_profile=profile)

            else:
                raise ValueError

            if self.headless:
                self.cl.info("Starting " + str(self.browser).upper() +
                             " browser in headless mode")
            else:
                self.cl.info("Starting " + str(self.browser).upper() +
                             " browser ")
                if self.browser.lower(
                ) == "browserstack" and 'browserName' in browser_config.keys():
                    pass
                else:
                    driver.maximize_window()

            driver.delete_all_cookies()
            # driver.set_page_load_timeout(30)

            if self.baseUrl:
                driver.get(self.baseUrl)
                self.cl.info("Opening the URL :: " + str(self.baseUrl))

            # driver.implicitly_wait(10)
            return driver

        except ValueError as val:
            self.cl.error(
                "Browser not supported :: " + str(self.browser) +
                ". Supported browser types are Chrome, Firefox, Edge. Exception occurred. :: "
                + str(val.__class__.__name__) + ' ' + str(val))
            raise val

        except Exception as e:
            self.cl.error("Exception occurred. :: " +
                          str(e.__class__.__name__) + ' ' + str(e))
            raise e
class SeleniumDriver:

    log = cl.custom_logger()

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

    def verifyPageTitle(self, titleToVerify):
        """
        Verify the page Title

        Parameters:
            titleToVerify: Title on the page that needs to be verified
        """
        try:
            actualTitle = self.getTitle()
            self.log.debug(
                f"The actual title received : {actualTitle} is compared to expected {titleToVerify}"
            )
            return self.util.verifyTextMatch(actualTitle, titleToVerify)
        except:
            self.log.error("Failed to get page title")
            print_stack()
            return False

    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")

    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()
            locatorType = self.getByType(locatorType)
            element = self.driver.find_element(locatorType, 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="xpath", 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)

    def sendKeys(self, data, locator="", locatorType="xpath", 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)

    def clearField(self, locator="", locatorType="xpath"):
        """
        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)
            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, locatorType="xpath"):
        """
        Check if element is present
        """
        try:
            elementList = self.driver.find_elements(locatorType, locator)
            lenelem = len(elementList)
            if lenelem > 0:
                self.log.info("Element present with locator: " + locator +
                              " locatorType: " + str(locatorType) +
                              " Length of element list: " + str(lenelem))
                return True
            else:
                self.log.info("Element not present with locator: " + locator +
                              " locatorType: " + str(locatorType))
                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")
        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);")

    def moveOffsetToElement(self, x, y, locator="", locatorType="xpath"):
        ac = ActionChains(self.driver)
        el = self.getElement(locator, locatorType)
        self.log.info("Moving to element: " + " with offset: " + str(x) + "," +
                      str(y))
        ac.move_to_element_with_offset(el, x, y)
        ac.click()
        ac.perform()

    def verify_text_match_from_element(self,
                                       expected_text,
                                       locator="",
                                       locatorType="xpath"):
        """
        Verifies the alert text of input field is matching as expected
        :param alert_text: the text which appears as the alert message
        :return: boolean based on the criteria if the text matches or not
        """
        self.log.info(
            f"Finding the alert text for the input field with locator {locator} and locatorType {locatorType}"
        )
        obtained_alert_text = self.getText(locator, locatorType)
        if obtained_alert_text == expected_text:
            return True
        else:
            return False

    def verify_if_button_enabled(self, locator="", locatorType="xpath"):
        """
        Verified if the element given is enabled.
        Returns true if its enabled
        """
        self.log.info(
            f"Verifying if the element with locator {locator} and locatorType {locatorType} is enabled"
        )
        element = self.getElement(locator, locatorType)
        attrib = element.get_attribute("class")
        self.log.info("The attrib received from the element: " + attrib)
        if "disable-button" in attrib:
            return True
        else:
            return False
Exemple #17
0
class TestLogin(BaseClass):
    log = cl.custom_logger()

    @pytest.fixture(autouse=True)
    # loading all the objects in the test class
    def objectsetup(self, setup):
        self.log.info("Setting up the objects")
        self.lp = Login(self.driver)
        self.ts = StatusTest(self.driver)

    # Checks if the Mandara page has loaded by verifying the availability of the logo.
    def test_mandara_app_load(self):
        self.log.info("Verifying if the Mandara App loaded")
        result = self.lp.verify_mandara_app_load()
        self.ts.markFinal("Mandara app load verification", result, "Verification of Mandara load with logo appearance")

    # Verifies the title of the loaded Mandara Page
    def test_title(self):
        self.log.info("Checking the title of the Mandara login Page")
        result1 = self.lp.verify_login_page_title(td.page_title)
        self.ts.markFinal("Page title", result1, "Verification of the Page Title")

    # Verifies the copyright info with the current year
    def test_copyright(self):
        self.log.info("Checking the copyright presence and year correctness")
        result = self.lp.copyright()
        self.ts.markFinal("Copyright Info", result, "Verification of the presence and year correctness for copyright")

    # Verifies the text in the username field, password field, and the text in the buttons of login page
    def test_text(self):
        self.log.info("Verification of the text available in the buttons")
        result1 = self.lp.verify_username_text()
        result2 = self.lp.verify_password_text()
        result3 = self.lp.verify_fgt_pwd_text()
        result4 = self.lp.verify_login_text()
        self.ts.mark(result1, "Verifying the text in the username field")
        self.ts.mark(result2, "Verifying the text in the password field")
        self.ts.mark(result3, "Verifying the text in the forgot_password button")
        self.ts.markFinal("Verifying the text in the Login page", result4, "Verification of all text in login button")

    # Verifies the input alert for username and password when clicked and no data is entered
    def test_login_input_field_alert(self):
        self.log.info("Checking the alert messages for the username and password")
        result1 = self.lp.username_input_alert()
        result2 = self.lp.password_input_alert()
        self.ts.mark(result1, "Verifying the username input alert when no text is given")
        self.ts.markFinal(
            "Login page alert message check", result2, "Verifying the username input alert when no text is given"
        )

    # Verifies the login button being disabled when no value is entered in both username and password fields
    def test_login_button_disabled(self):
        self.log.info("Verifying if the login button is disabled when no value is entered to both login fields")
        result = self.lp.verify_disabled_login_button()
        self.ts.markFinal("Login button disable check", result, "Verifying disabled login button on start")

    # Verifies the invalid log with wrong username
    def test_invalid_login_user(self):
        self.log.info("Verifying Invalid login with wrong username")
        self.lp.login(td.wrongusername, td.password)
        result2 = self.lp.verify_login_failed()
        self.ts.markFinal("Invalid Login", result2, "Verification of Invalid Login with wrong username")

    # Verifies the invalid log with wrong password
    def test_invalid_login_pass(self):
        self.log.info("Verifying Invalid login with wrong password")
        self.lp.login(td.username, td.wrongpassword)
        result2 = self.lp.verify_login_failed()
        self.ts.markFinal("Invalid Login", result2, "Verification of Invalid Login with wrong password")

    # Verifies the forgot password feature
    def test_forgotpassword(self):
        result3 = self.lp.verify_enter_valid_email()
        result4 = self.lp.forgot_password_invalid(td.wrongemail)
        result5 = self.lp.forgot_password_valid(td.email)
        self.ts.mark(result3, "Checking valid Email message")
        self.ts.mark(result4, "Sending wrong Email and verifying the error thrown")
        self.ts.markFinal("Valid Email check", result5, "Verification of forgot password feature")

    # Verifies the text for the buttons in the forgot password page.
    def reset_pwd_page_text(self):
        result1 = self.lp.verify_back_to_login_text()
        result2 = self.lp.verify_reset_text()
        self.ts.mark(result1, "Verification of back_to_login_text")
        self.ts.markFinal("Verification of text in reset password field", result2,
                          "Verification of reset password text ")

    # Verifies the presence and functionality of the "back to login" feature
    def test_back_to_login(self):
        result1 = self.lp.presence_back_to_login()
        result2 = self.lp.back_to_login()
        self.ts.mark(result1, "Verifying the presence of back to login button")
        self.ts.markFinal("Back to login", result2, "Verification of back to login button")

    # Verifies the valid login
    def test_valid_login(self):
        self.lp.login(td.username, td.password)
        result3 = self.lp.verify_login_success()
        self.ts.markFinal("Valid Login", result3, "Verification of Valid Login")
Exemple #18
0
class Utilities():
    cl = custom_logger(logging.INFO)

    def sleep(self, sec, info=""):
        if info is not None:
            self.cl.info("Wait :: " + str(sec) + " seconds for " + str(info))
        try:
            time.sleep(sec)
        except InterruptedError:
            self.cl.error("Exception occured while Sleep")

    def verify_text_contains(self, actualText, expectedText):
        self.cl.info("Actual text from application URL is :: " +
                     str(actualText))
        self.cl.info("Expected text from application URL is :: " +
                     str(expectedText))

        if actualText.lower() in expectedText.lower():
            self.cl.info("### Verfication Passed !!!")
            return True
        else:
            self.cl.info("### Verfication Failed !!!")
            return False

    def verify_text(self, actualText, expectedText):
        self.cl.info("Actual text from application URL is :: " +
                     str(actualText))
        self.cl.info("Expected text from application URL is :: " +
                     str(expectedText))

        if actualText.lower() == expectedText.lower():
            self.cl.info("### Verfication Passed")
            return True
        else:
            self.cl.log.info("### Verfication Failed")
            return False

    def getAlphaNumeric(self, length, type):

        alpha_num = ""

        if type == "lower":
            value = string.ascii_lowercase

        elif type == "upper":
            value = string.ascii_uppercase

        elif type == "digits":
            value = string.digits

        elif type == "mix":
            value = string.ascii_letters + string.digits

        elif type == "letters":
            value = string.ascii_letters

        for i in range(0, length):
            return alpha_num.join(random.choice(value))

    def listcompare(self, expectedList, actualList):
        try:
            self.cl.info("Expected List is :: " + str(expectedList))
            self.cl.info("Actual List is :: " + str(actualList))

            if len(expectedList) == len(actualList):
                i = 0
                for i in range(0, len(actualList)):
                    if expectedList[i] == actualList[i]:
                        i = i + 1
                        if i == len(actualList):
                            return True
                            self.log.info("Both List Matched")

                    else:
                        return False
                        self.log.info("List Does not match")
                        break
            else:
                print("List Length does not match")
                return False

        except:
            print("List Length does not match")
            return False

    def verify_value(self, actualValue, expectedValue):
        self.cl.info("Actual value from application  is :: " +
                     str(actualValue))
        self.cl.info("Expected value from application  is :: " +
                     str(expectedValue))

        if str(actualValue) == str(expectedValue):
            self.cl.info("### Verfication Passed")
            return True
        else:
            self.cl.info("### Verfication Failed")
            return False