class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver self.home = HomePage(driver) self.WebDriver = WebDriverFactory(driver) # Locators txtUserId = "userid" txtPassword = "******" btnSign_In = "//button[@type='submit']" def loginToApplication(self, userId="", password=""): self.clearFields() self.enterUserId(userId) self.enterPassword(password) self.clickLogin() def enterUserId(self, userId): self.sendKeys(userId, self.txtUserId) def enterPassword(self, password): self.sendKeys(password, self.txtPassword) def clickLogin(self): self.elementClick(locator=self.btnSign_In, locatorType="xpath") def clearFields(self): txtUserId = self.getElement(locator=self.txtUserId) txtUserId.clear() txtPassword = self.getElement(locator=self.txtPassword) txtPassword.clear()
class ChromeLogin(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver emailfield = "//*[@type='email']" passfield = "//*[@name='password']" passedLogin = "******" def login(self): print("You need to sign into chrome for captcha to work") self.driver.get('https://accounts.google.com/signin/v2') while True: if 'Manage your info' in self.driver.page_source: break elif 'Control, protect' in self.driver.page_source: break else: continue time.sleep(1) def redirectToStore(self, domain): shopifyWebsite = "https://" + domain + ".com/sitemap_products_1.xml" self.driver.get(shopifyWebsite) return domain
class FTPTransferImpl(): log = cl.customLogger(logging.INFO) PORT = 21 SFTPPORT = 22 def sendFileToSFTPServer(self, serverIp, userName, password, localPath, destinationPath): try: cnopts = pysftp.CnOpts() cnopts.hostkeys = None with pysftp.Connection(host=serverIp, username=userName, password=password, cnopts=cnopts, log=True) as sftp: print("Connection succesfully established ... ") sftp.put(localPath, destinationPath) sftp.close() except Exception: print(Exception) def sendFileToFTPServer(self, serverIp, userName, password, localPath, destinationPath): try: session = ftplib.FTP(serverIp, FTPTransferImpl.PORT, userName, password) file = open('kitten.jpg', 'rb') # ftp.login(user=userName, passwd=password) # connect = ftp.Connection(serverIp, userName, password) localFile = localPath # + "\\" + localFileName # remotepath = destinationPath # connect.put(localFile,remotepath) # connect.close() except Exception: print(Exception)
class Util(object): log = cl.customLogger(logging.INFO) def sleep(self, sec, info=""): """ Put the program to wait for the specified amount of time """ if info is not None: self.log.info("Wait :: '" + str(sec) + "' seconds for " + info) try: time.sleep(sec) except InterruptedError: traceback.print_stack() def getAlphaNumeric(self, length, type='letters'): """ Get random string of characters Parameters: length: Length of string, number of characters string should have type: Type of characters string should have. Default is letters Provide lower/upper/digits for different types """ alpha_num = '' if type == 'lower': case = string.ascii_lowercase elif type == 'upper': case = string.ascii_uppercase
class NavigationPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _my_courses = "All Courses" _all_courses = "My Courses" _practice = "Practice" _user_icon = "//div[@id='navbar']//span[text()='Test']" def navigateToAllCourses(self): self.elementClick(self._all_courses, locatorType="link") def navigateToMyCourses(self): self.elementClick(self._my_courses, locatorType="link") def navigateToPractice(self): self.elementClick(self._practice, locatorType="link") def navigateToUserSettings(self): self.elementClick(self._user_icon, locatorType="xpath")
class HierarchyBalanceReportTest(unittest.TestCase): log = cl.customLogger(logging.INFO) @pytest.fixture(autouse=True) def classSetup(self, oneTimeSetUp): self.login = LoginPage(self.driver) self.rootCustomer = RootCustomer(self.driver) self.home = HomePage(self.driver) self.account = Accounts(self.driver) self.company = Company(self.driver) self.hierarchyBal = HierarchyBalance(self.driver) self.status = TestStatus(self.driver) @pytest.mark.smoke def test_HierarchyBalances(self): result = False self.login.loginToApplication(ApplicationConfig.get('UserId'), ApplicationConfig.get('Password')) # self.home.verifyWelcomeMessage( ApplicationConfig.get( 'UserId' ) ) # self.status.mark(result, "Incorrect match") self.home.navigateToRootCustomers() self.rootCustomer.clickOnAddRootCustomerButton() companyList = inputCustomerTest.df_Singlecustomer self.company.createCustomerHierarchy(companyList) self.company.activateCustomer(companyList.loc[0]['Subentity']) self.home.navigateToAccounts() self.account.clickOnAddRootAccountButton() accountList = inputCustomerTest.df_accounts_HB data = self.account.createAccountHierarchy(accountList) self.account.activateAccount(accountList.loc[0]['Name of the account']) self.home.navigateToReports() self.hierarchyBal.verifyDefaultHierarchyBalances() self.home.userLogout() print('TTTTTTTT')
class GlobalSearchTest(unittest.TestCase): log = cl.customLogger(logging.INFO) @pytest.fixture(autouse=True) def classSetup(self, oneTimeSetUp): self.login = LoginPage(self.driver) self.rootCustomer = RootCustomer(self.driver) self.home = HomePage(self.driver) self.account = Accounts(self.driver) self.company = Company(self.driver) self.globalSearch = GlobalSearch(self.driver) self.status = TestStatus(self.driver) @pytest.mark.smoke def test_searchCustomerAndClick(self): result = False self.login.loginToApplication(ApplicationConfig.get('UserId'), ApplicationConfig.get('Password')) # self.home.verifyWelcomeMessage( ApplicationConfig.get( 'UserId' ) ) # self.status.mark(result, "Incorrect match") self.home.navigateToRootCustomers() companyList = inputCustomerTest.df_Singlecustomer customerName = companyList['Subentity'][0] customerName = '01PKTESTCUST' self.globalSearch.searchAccountOrCustomerAndClick(self.home.labelsOnUI['GlobalSearchType_Company'], customerName) self.home.verifyRootCustomerLabelOnCompanyPage(customerName) self.overview.verifyCustomerDetails(companyList)
class BankUserTest(unittest.TestCase): log = cl.customLogger(logging.INFO) @pytest.fixture(autouse=True) def classSetup(self, oneTimeSetUp): self.login = LoginPage(self.driver) self.rootCustomer = RootCustomer(self.driver) self.home = HomePage(self.driver) self.ct = Customer(self.driver) self.account = Accounts(self.driver) self.company = Company(self.driver) self.bankUser = Users(self.driver) self.status = TestStatus(self.driver) @pytest.mark.smoke def test_CreateBankUsers_And_ViewUsers(self): self.login.loginToApplication( ApplicationConfig.get('BANKADMIN_USERID'), ApplicationConfig.get('BANKADMIN_PASSWORD')) # self.home.verifyWelcomeMessage( ApplicationConfig.get( 'UserId' ) ) self.home.navigateToAdmin() userList = inputCustomerTest.df_BankUsers self.UsersABO = self.bankUser.createUsers(userList.loc[0]) # print(self.UsersABO) self.bankUser.searchUser(self.UsersABO) result = self.bankUser.verifyAdminUserDetails(self.UsersABO) self.status.mark(result, "Incorrect Match") self.home.userLogout() self.login.loginToApplication(self.UsersABO.get('User ID'), self.UsersABO.get('Password')) result = self.home.verifyWelcomeMessage( self.UsersABO.get('First name')) self.status.mark(result, "Incorrect Match") self.home.userLogout() self.status.markFinal("test_CreateBankAdminUser_And_ViewUser", result, "Verification is Successful") @pytest.mark.smoke def test_CreateCustUsers_And_ViewUsers(self): self.login.loginToApplication( ApplicationConfig.get('BANKADMIN_USERID'), ApplicationConfig.get('BANKADMIN_PASSWORD')) #self.home.verifyWelcomeMessage( ApplicationConfig.get( 'UserId' ) ) self.home.navigateToAdmin() userList = inputCustomerTest.df_CustUsers self.UsersABO = self.bankUser.createUsers(userList.loc[0]) # print(self.UsersABO) self.bankUser.searchUser(self.UsersABO) result = self.bankUser.verifyAdminUserDetails(self.UsersABO) self.status.mark(result, "Incorrect Match") self.home.userLogout() self.login.loginToApplication(self.UsersABO.get('User ID'), self.UsersABO.get('Password')) result = self.home.verifyWelcomeMessage( self.UsersABO.get('First name')) self.status.mark(result, "Incorrect Match") self.home.userLogout() self.status.markFinal("test_CreateBankAdminUser_And_ViewUser", result, "Verification is Successful")
class Company( Customer ): log = cl.customLogger( logging.DEBUG ) def __init__(self, driver): super().__init__( driver ) self.driver = driver # Locators lnkCustomerName = "//span[contains(text(),'{0}')]" addChildCustomer = "//span[text()='{0}']/following-sibling::" \ "div[@class='level-item-actions ng-star-inserted']//app-icon[@iconclass='icon-sm']" btnSendForActivation = "//button[@class='btn btn-primary']" chkboxChooseBranchForApproval = "//label/div/strong[text()='{0}']" btnSend = "//button[@class='btn btn-lg btn-success']" lnkUsers = "//span[text()[normalize-space() = '{0}']]" def clickOnParentCustomerToAddChild(self, parent): try: self.elementClick( self.lnkCustomerName.format( parent ), locatorType="xpath" ) self.elementClick( self.addChildCustomer.format( parent ), locatorType="xpath" ) except Exception as e: self.log.error( "Error occurred while filling address details. :: " ) def createCustomerHierarchy(self, company): try: for i in range(len(company)): self.clickOnParentCustomerToAddChild(company.loc[i]['Parent']) tempCompany = company.loc[i] self.enter_customer_information(tempCompany) self.clickOnAddCustomerButton() self.verifyMessageOnProgressBar(self.labelsOnUI['msg_CustomerCreationSuccessfull']) except Exception as e: self.log.error("Error occurred while filling address details. :: ") def activateCustomer(self, companyName): try: self.waitForElement(self.btnSendForActivation, locatorType="xpath", timeout=4) self.elementClick( self.btnSendForActivation, locatorType="xpath" ) self.waitForElement( self.chkboxChooseBranchForApproval ) self.elementClick( self.chkboxChooseBranchForApproval.format( companyName ), locatorType="xpath" ) self.elementClick( self.btnSend, locatorType="xpath" ) self.verifyMessageOnProgressBar(self.labelsOnUI['msg_CustomerActivateMessage']) inputCustomerTest.set_status_of_customer(inputCustomerTest.df_Singlecustomer, self.labelsOnUI['CustomerStatusValueToVarify']) except Exception as e: self.log.error( "Error occurred while filling address details. :: " ) def navigateToUser(self): try: self.elementClick(self.lnkUsers.format('users'), locatorType="xpath") self.log.info("Successfully navigated to USERS:: ") except: self.log.info("Error while navigating to USERS:: ")
class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators login_link = "Login" username_field = "user_email" password_field = "user_password" loginButton_link = "commit" # def getLoginField(self): # return self.driver.find_element(By.LINK_TEXT, self.login_link) # # def getUserNameField(self): # return self.driver.find_element(By.ID, self.username_field) # # def getPasswordField(self): # return self.driver.find_element(By.ID, self.password_field) # # def getLoginButtonLink(self): # return self.driver.find_element(By.NAME, self.loginButton_link) def clickLoginLink(self): self.elementClick(self.login_link, locatorType="link") def enteremail(self, email): self.sendKeys(email, self.username_field) def enterpassword(self, password): self.sendKeys(password, self.password_field) def clickLoginButton(self): self.elementClick(self.loginButton_link, locatorType="name") def login(self, email=" ", password="******"): self.clickLoginLink() self.driver.implicitly_wait(5) self.enteremail(email) self.enterpassword(password) self.clickLoginButton() def verifyLoginSuccessful(self): result = self.isElementPresent("gravatar", locatorType="class") return result def verifyLoginFailed(self): result = self.isElementPresent( "//div[contains(text(),'Invalid email or password')]", locatorType="xpath") return result def verifyLoginTitle(self): return self.verifyPageTitle("Google")
class TestStatus(SeleniumDriver): log = cl.customLogger(logging.INFO) def __init__(self, driver): """ Inits CheckPoint class """ super(TestStatus, self).__init__(driver) self.resultList = [] def setResult(self, result, resultMessage): try: if result is not None: if result: self.resultList.append("PASS") self.log.info("### VERIFICATION SUCCESSFUL :: + " + resultMessage) else: self.resultList.append("FAIL") self.log.error("### VERIFICATION FAILED :: + " + resultMessage) self.screenShot(resultMessage) else: self.resultList.append("FAIL") self.log.error("### VERIFICATION FAILED :: + " + resultMessage) self.screenShot(resultMessage) except: self.resultList.append("FAIL") self.log.error("### Exception Occurred !!!") self.screenShot(resultMessage) print_stack() def mark(self, result, resultMessage): """ Mark the result of the verification point in a test case """ self.setResult(result, resultMessage) def markFinal(self, testName, result, resultMessage): """ Mark the final result of the verification point in a test case This needs to be called at least once in a test case This should be final test status of the test case """ self.setResult(result, resultMessage) if "FAIL" in self.resultList: self.log.error(testName + " ### TEST FAILED") self.resultList.clear() assert True == False else: self.log.info(testName + " ### TEST SUCCESSFUL") self.resultList.clear() assert True == True
class NavigationPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _user_settings_icon = "abc" def navigateToUserSettings(self): self.elementClick(locator=self._user_settings_icon, locatorType="css")
class LoginClass(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # locators identifiers _login_link = "Login" _email_field = "user_email" _password_field = "user_password" _login_button = "commit" # methods for performing actions on elements def clickLoginLink(self): self.elementClick(self._login_link, locatorType="link") def enterEmail(self, email): self.sendKeys(email, self._email_field, locatorType="id") def enterPassword(self, password): self.sendKeys(password, self._password_field, locatorType="id") def clickLoginButton(self): self.elementClick(self._login_button, locatorType="name") # Functionnality which wraps all the actions needed to be performed on the page class def Login(self, email="", password=""): self.clickLoginLink() time.sleep(3) self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccess(self): result = self.isElementPresent( ".//div[@id='navbar']//span[text()='User Settings']", locatorType="xpath") return result def verifyLoginFail(self): result = self.isElementPresent( "//div[contains(text(),'Invalid email or password')]", locatorType="xpath") return result def verifyLoginTitle(self): return self.verifyPageTitle("Google")
class TrackStatus(SeleniumDriver): log = cl.customLogger(logging.INFO) def __init__(self, driver): """ Inits CheckPoint class """ super(TrackStatus, 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.capturescreen(resultMessage) else: self.resultList.append("FAIL") self.log.error("*** VERIFICATION FAILED: " + resultMessage) self.capturescreen(resultMessage) except: self.resultList.append("FAIL") self.log.error("*** Exception Occurred!!!") self.capturescreen(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): self.setResult(result, resultMessage) if "FAIL" in self.resultList: self.log.error(testName + " ***** TEST FAILED" + " *****") self.resultList.clear() assert True == False else: self.log.info(testName + " ##### TEST SUCCESSFUL" + " #####") self.resultList.clear() assert True == True
class Welcome(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver progressBar = "//div[@class='simple-notification success ng-trigger ng-trigger-enterLeave']" ctlWelcomeMessage = "//div[contains(text(),'{0}')]" lnkCustomerAndAccount = "//span[contains(.,'Customer & Account')]" def verifyWelcomeMessage(self, msg): self.waitForElement(self.progressBar, 10) result = self.isElementDisplayed(self.ctlWelcomeMessage.format())
class LoginPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _login_link = "Login" _email_field = "user_email" _password_field = "user_password" _login_button = "commit" def clickLoginLink(self): self.elementClick(self._login_link, locatorType="link") def enterEmail(self, email): self.sendKeys(email, self._email_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._login_button, locatorType="name") def login(self, email="", password=""): self.clickLoginLink() time.sleep(3) self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccessful(self): result = self.isElementPresent( "//div[@id='navbar']//span[text()='Test']", locatorType="xpath") return result def verifyLoginFailed(self): result = self.isElementPresent( "//div[contains(text(),'Invalid email or password')]", locatorType="xpath") return result def verifyTitle(self): if "google" in self.getTitle(): return True else: return False
class TestStatus(SeleniumDriver): log = cl.customLogger(logging.INFO) def __init__(self, driver): super(TestStatus, self).__init__(driver) self.resultlist = [] def setResult(self, result, resultMessage): try: if result is not None: #we dont have to right if result is true if result: self.resultlist.append("Pass") self.log.info("Verification Successful" + resultMessage) else: self.resultlist.append("Fail") self.log.info("Verification Unsuccessful" + resultMessage) self.screenShot(resultMessage) else: self.resultlist.append("Fail") self.log.error("Result has no value" + resultMessage) self.screenShot(resultMessage) except: self.resultlist.append("Fail") self.log.error("###### Exception occurred" + resultMessage) self.screenShot(resultMessage) def mark(self, result, resultMessage): # it will mark the result of all the verfication/assertion # points in the code self.setResult(result, resultMessage) def markFinal(self, testName, result, resultMessage): self.setResult(result, resultMessage) if "Fail" in self.resultlist: self.log.error(testName + " Test Failed") self.resultlist.clear() assert True == False else: self.log.info(testName + " Test pass") self.resultlist.clear() assert True == True
class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locaters _user_email = "customer_email" _user_password = "******" _login_button = "//button[contains(text(),'Login')]" # xpath _signed_in = "view_address" _signed_in_false = "alert alert-error" _shop_button_hover = "//div[@class='collapse navbar-collapse']//span[contains(text(),'Shop')]" _shop_button_link = "NEW" def enterEmail(self, email): self.sendKeys(email, self._user_email) def enterPassword(self, password): self.sendKeys(password, self._user_password) def clickLoginButton(self): self.elementClick(self._login_button, locatorType="xpath") def login(self, email="", password=""): print("Logging in") self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccess(self): result = self.isElementPresent("view_address") return result def verifyLoginFailed(self): result = self.isElementPresent("//div[@class='alert alert-error']", locatorType="xpath") return result def redirectToShop(self): self.driver.get("https://undefeated.com/sitemap_products_1.xml") def loginAndRedirect(self, email="", password=""): self.login(email, password) self.redirectToShop()
class NavigationPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators Workex_logo="//a[@title='Explore Jobs on Workex' and contains(text(),'Search Jobs')]" Search_jobs="//a[@title='Explore Jobs on Workex' and contains(text(),'Search Jobs')]" def navigateToHomePage(self): self.clickElement(self.Workex_logo, locatorType="xpath") def navigateToSearchPage(self): self.clickElement(self.Search_jobs, locatorType="xpath")
class CheckoutItemPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver ################ ### Locators ### ################ _search_box = "search_query_top" # {0} is a placeholder and the actual value that will be used is passed in by .format() _search_box_button = "submit_search" _item_name = "//a[@title='{0}'][normalize-space()='{0}']" _dropdown_list = "group_1" _size = "0" _choose_color = "//a[@name='{0}']" _add_to_cart_button = "//span[contains(text(),'Add to cart')]" _proceed_to_checkout_button = "//span[normalize-space()='Proceed to checkout']" _proceed_to_checkout_summary = "div#center_column a[title='Proceed to checkout'] > span" _process_address_button = "processAddress" _checkbox = "cgv" _process_carrier_button = "processCarrier" _pay_button = "cheque" _confirm_button = "p#cart_navigation span" _validation_success = "//button[@name='submit_search']" ############################ ### Element Interactions ### ############################ def enterSearchKeyword(self, name): self.sendKeys(name, locator=self._search_box) self.elementClick(locator=self._search_box_button, locatorType="name") def selectItem(self, ItemName): try: if self.getElement(locator=self._item_name.format(ItemName),locatorType="xpath"): self.elementClick(locator=self._item_name.format(ItemName), locatorType="xpath") self.webScroll() return True except: self.log.info("Item not found with locator " + self._item_name.format(ItemName) + " and locatorType xpath") return False def clickOnAddtoCart(self,_size="", _color=""): dropdownlist = Select(self.getElement(locator = self._dropdown_list)) dropdownlist.select_by_visible_text(format(_size)) self.elementClick(locator = self._choose_color.format(_color), locatorType = "xpath") self.elementClick(locator = self._add_to_cart_button, locatorType = "xpath") return True def clickProceedtoCheckout(self): self.elementClick(locator = self._proceed_to_checkout_button,locatorType = "xpath") return True def clickProceedtoCheckout_Sumary(self): self.elementClick(locator=self._proceed_to_checkout_summary,locatorType="css") return True def clickProceedtoCheckout_Address(self): self.elementClick(locator=self._process_address_button,locatorType="name") return True def clickProceedtoCheckout_Shipping(self): self.elementClick(locator=self._checkbox) self.elementClick(locator=self._process_carrier_button,locatorType="name") return True def clickPayByCheck(self): self.elementClick(locator=self._pay_button,locatorType="class") return True def clickConfirm(self): self.elementClick(locator=self._confirm_button,locatorType="css") return True def verifyCompleteCheckout(self): self.webScroll() self.isElementPresent(locator=self._validation_success, locatorType="xpath") return True
class Transactions(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver progressBar = "//div[@class='simple-notification success has-icon ng-trigger ng-trigger-enterLeave'] | //div[@class='simple-notification success ng-trigger ng-trigger-enterLeave']" lnkTransactions = "//a/span[text()='{0}']" rows_Trn = "//table//tr" cell_TrnAmt = "//table//tr[{0}]/td[8]" cell_TrnDate = "//table//tr[{0}]/td[1]" cell_AcctName = "//table//tr[{0}]/td[2]" cell_Category = "//table//tr[{0}]/td[3]" cell_TransactionType = "//table//tr[{0}]/td[4]" cell_ValueDate = "//table//tr[{0}]/td[7]" lnkView = "//table//tr['{0}']/td[9]//a[text()[normalize-space()='{0}']] | //table//tr[1]/td[8]//a[text()[normalize-space()='View']]" lnkMove = "//table//tr['{0}']/td[9]//a[text()[normalize-space()='{0}']]" lnkViewRow = "//table//tr['{0}']/td[8]//a[text()[normalize-space()='View']]" lnkExport = "//button/span" cell_CategoryPain = "//table//tr['{0}']/td[2]" cell_ValueDatePain = "//table//tr['{0}'/td[6]" cell_TrnAmtPain = "//table//tr['{0}']/td[7]" txtTargetAccount = "//label[ text()[normalize-space()='{0}']]/../descendant::input" ddlTargetAccount = "//span[text()[normalize-space()='{0}']]" txtDynamicLocator = "//*[text()[normalize-space()='{0}']]" lblMovedToFromAccount = "//*[text()[normalize-space()='{0}']]/following-sibling::td" lblExceptionTranAmountOnWidget = "//*[@class='text-right text-danger ng-star-inserted']/strong" reportDataTable = "//table[contains(@class, 'table-clickable-rows')]" reportOption = "//div[text()='%{0}']" linksOnTransactionRecord = "//table//tr//td[9]//a[text()[normalize-space()='{0}']]" # Icons iconFilter = "//a[@class='btn btn-circle btn-circle-sm ml-2 mr-2 btn-outline-primary']" # TextBoxes txtValueFromDate = "//input[@id='valueFromDate']" txtValueToDate = "//input[@id='valueToDate']" # Buttons btnApplyFilter = "//button[@class='btn btn-sm btn-primary']//span[contains(text(),'%s')]" def navigateToTransactions(self): try: self.waitForElement(self.lnkTransactions) self.elementClick(self.lnkTransactions.format( self.labelsOnUI['lnkTransactions']), locatorType="xpath") self.log.info("Successfully navigated to " + self.labelsOnUI['lnkTransactions']) except: self.log.info("Error while navigating to" + self.labelsOnUI['lnkTransactions']) def verifyTransationsOnUI(self, input, transactionAccount): result = False cntCreditTrn = 0 cntDebitTrn = 0 exceptionRow = 0 trnRowsFromTestData = 0 value = "" amount = 0.00 try: trnRowsOnUI = self.getElementList(self.rows_Trn).size() trnRowsFromTestData = input.get('ntry_Credit') + input.get( 'ntry_Debit') + 1 if (trnRowsOnUI - 1) != trnRowsFromTestData: self.log.info("Credit/Debit Transaction not posted::") else: today = str(date.today()) for i in trnRowsOnUI: value = self.getText(self.cell_TrnDate.format(i)) if today == value: amount = amount + float( self.getText(self.cell_TrnAmt.format(i)[3:])) except: self.log.info("Error while navigating to" + self.labelsOnUI['lnkTransactions'])
class Customer(RootCustomer): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators companyTitle = "//h4[contains(.,'{0}')]" accountTitle = "//h4[contains(.,'{0}')]" lblMandatory = "//label[@class='required'][contains(text(),'{0}')]" lbl_tblheader = "//th[contains(text(),'{0})]" # radiobuttons rdoSubEntity = "//input[@id='subEntityRadio']" rdoClient = "//input[@id='clientRadio']" rdoLblSubEntity = "//label[@for='subEntityRadio']" rdoLblClient = "//label[@for='clientRadio']" rdoCustomerCategory = "//input[@type='radio']/ancestor::label[contains(.,'{0}')]" rdoCorporate = "//input[@id='corporateRadio']" rdoIndividual = "//input[@id='individualRadio']" rdoLblCorporate = "//label[@for='corporateRadio']" rdoLblIndividual = "//label[@for='individualRadio']" # textbox txtBankId = "//select[@id='bankId']" txtName = "//input[@formcontrolname='firstName']" txtlastName = "//input[@formcontrolname='lastName']" txtPreferredName = "//input[@formcontrolname='companyName']" txtCustomerId = "//input[@id='customerIdentity']" txtAddressLine1 = "//input[@id='addressLine1']" txtAddressLine2 = "//input[@id='addressLine2']" txtAddressLine3 = "//input[@id='addressLine3']" txtAddressLine4 = "//input[@id='addressLine4']" txtPostalCode = "//input[@id='postalCode']" txtParentCustomer = "//span[@class='ng-arrow-zone']" txtParentCustomerAllValue = "//div[contains(@class,'ng-select-dropdown-outer bottom')]//div/span" txtParentCustomerVlue = "//div[contains(@class,'ng-select-dropdown-outer bottom')]//div/span[contains(text(),'{0}')]" txtReferenceNo = "//input[@id='customerReference']" txtContactValue = "//input[@id='contactPhoneNumber']" txtContactDescription = "//input[@id='contactDescription']" txtOptionalReference = "(//select[@formcontrolname='customerRefType']/ancestor::td/following-sibling::td/input[@id='customerReference'])[%d]" txtOptionalReferenceNumber = "//select[@formcontrolname='customerRefType']/ancestor::td/following-sibling::td/input[@id='customerReference']" txtManRefNumber = "(//th[text()[normalize-space()='%s']]/following::label[@class='required ng-star-inserted']/ancestor::td/following-sibling::td/input[@id='customerReference'])[%d]" txtcustomerReference = "//input[@id='customerReference']" # dropdown ddlSectorClassification = "//select[@id='institutionalSectorCode']" ddlMarketSegment = "//select[@id='marketSegmentCode']" ddlCountry = "//select[@id='country']" ddlContactType = "//select[@id='contactType']" ddlRefType = "//select[@formcontrolname='customerRefType']" ddlOpRefType = "(//select[@formcontrolname='customerRefType'])[%d]" ddlOptionalRefType = "//select[@formcontrolname='customerRefType']" # ddlManRefType = "//select[@formcontrolname='customerRefType'][(@disabled)]" ddlManRefType = "//tr[@class='ng-untouched ng-pristine ng-invalid ng-star-inserted']" # Button btnClose = "//button[@class='close']" btnAddCustomer = "//app-icon[@iconname='plus']/ancestor::button[@class='btn btn-lg btn-success'][contains(.,'{0}')]" # btnCancel = "//a[@class='btn btn-lg btn-secondary']" btnCancel = "//button[@class='btn btn-lg btn-secondary']" btnSave = "//button[contains(.,'{0}')]" btnAddRef = "//span[contains(.,'{0}')]" btnSaveChanges = "//button[@class='btn btn-lg btn-success']" # Checkbox chkClientsAllowed = "//input[@id='subCustomerAllowedCheckbox']" chkClientsAllowedLabel = "//label[@for='subCustomerAllowedCheckbox']" # msg msg = "//div[contains(text(),'{0}')]" label = "//label[text()='{0}']" lblValue = "//label[contains(text(),'%s')]/following-sibling::p" deleteIcon = "//fieldset[@formarrayname='customerReferences']/table[@class='table table-sm']" \ "//tr[%s]//td[@class='actions ng-star-inserted']/a" deleteIconForOptRef = "//select[@formcontrolname='customerRefType']" \ "/following::td[@class='actions ng-star-inserted']/a" deleteIconAsPerOptRef = "(//select[@formcontrolname='customerRefType']" \ "/following::td[@class='actions ng-star-inserted'])[%d]/a" numberOfDeleteIcons = "//table[@class='table table-sm']" \ "//tbody//tr[@class='ng-untouched ng-pristine ng-valid ng-star-inserted']//td//a" # lblDatils = "//div[@class='data-list data-list-row data-list-row-align-right mt-2']//dl//dt[contains(.,'%s')]/..") lblRootCustomerName = "//a[@title='%s']" # other rootCustomerIsSelected = "//li[@class='level-0 has-children selected ng-star-inserted']" lnkCustomerName = "//span[contains(text(),'{0}')]" addChildCustomer = "//span[text()='{0}']/following-sibling::" \ "div[@class='level-item-actions ng-star-inserted']//app-icon[@iconclass='icon-sm']" btnSendForActivation = "//button[@class='btn btn-primary']" chkboxChooseBranchForApproval = "//label/div/strong[text()='{0}']" btnSend = "//button[@class='btn btn-lg btn-success']" def clickOnParentCustomerToAddChild(self, parent): try: self.elementClick(self.lnkCustomerName.format(parent), locatorType="xpath") self.elementClick(self.addChildCustomer.format(parent), locatorType="xpath") except Exception as e: self.log.error( "Error occurred while click on AddChild button. :: ") def enter_customer_information(self, rootCustomer): try: self.select_customer_category( rootCustomer[self.labelsOnUI['lbl_CustCategory_SubEntity']]) self.select_customer_type( rootCustomer[self.labelsOnUI['Lbl_CustomerType']]) self.setName(rootCustomer[self.labelsOnUI['Lbl_Name']], rootCustomer[self.labelsOnUI['Lbl_PreferredName']]) self.set_customer_id( rootCustomer[self.labelsOnUI['Lbl_CustomerID']]) self.select_sector_classification( rootCustomer[self.labelsOnUI['Lbl_SectorClassification']]) self.select_Market_Segment( rootCustomer[self.labelsOnUI['Lbl_MarketSegment']]) # if str( root['Customer category'] ) == str( self.labelsOnUI['lbl_CustCategory_SubEntity'] ): # self.decide_Whether_Clients_Allowed( root['Clients allowed'] ) self.fill_address_details(rootCustomer) self.fill_contact_details(rootCustomer) self.fill_customer_references(rootCustomer['Reference type'], rootCustomer['Reference number']) except Exception as e: self.log.error( "Error occurred while filling customer information. ::") def fill_address_details(self, address): try: self.sendKeys(address[self.labelsOnUI['lbl_Line1']], self.txtAddressLine1, locatorType="xpath") self.sendKeys(address[self.labelsOnUI['lbl_Line2']], self.txtAddressLine2, locatorType="xpath") self.sendKeys(address[self.labelsOnUI['lbl_Line3']], self.txtAddressLine3, locatorType="xpath") self.sendKeys(address[self.labelsOnUI['lbl_Line4']], self.txtAddressLine4, locatorType="xpath") # self.sendKeys(address[self.labelsOnUI['lbl_PostalCode']], self.txtPostalCode, locatorType="xpath") self.selectvaluefromDropdown( address[self.labelsOnUI['lbl_Country']], self.ddlCountry, locatorType="xpath") except Exception as e: self.log.error("Error occurred while filling address details. :: ") def fill_contact_details(self, contactDetails): try: self.selectvaluefromDropdown(contactDetails['Type'], self.ddlContactType, locatorType="xpath") self.sendKeys(contactDetails['Value'], self.txtContactValue, locatorType="xpath") self.sendKeys(contactDetails['Description'], self.txtContactDescription, locatorType="xpath") except Exception as e: self.log.error("Error occurred while filling contact details. :: ") def fill_customer_references(self, customerReferences, ReferencesNumber): try: self.add_Mandatory_References(customerReferences, ReferencesNumber) # self.add_Optional_References( customerReferences ) except Exception as e: self.log.error( "Problem occurred while adding customer references. :: ") def add_Mandatory_References(self, customerReferences, ReferencesNumber): try: self.selectvaluefromDropdown(customerReferences, self.ddlOptionalRefType, locatorType="xpath") self.sendKeys(ReferencesNumber, self.txtcustomerReference, locatorType="xpath") except Exception as e: self.log.error( "Problem occurred while adding Mandatory references. :: ") def add_Optional_References(self, customerReferences): try: References = customerReferences['Reference type'] # for key in References: # self.elementClick( self.btnAddRef.format( self.labelsOnUI['btn_AddAnotherReference'] ), # locatorType="xpath" ) # self.selectvaluefromDropdown( key, self.ddlOptionalRefType, locatorType="xpath" ) # references_number = References.get( key ) + Util.get_unique_number( 8 ) # self.sendKeys( references_number, self.txtOptionalReferenceNumber, locatorType="xpath" ) self.elementClick(self.btnAddRef.format( self.labelsOnUI['btn_AddAnotherReference']), locatorType="xpath") self.selectvaluefromDropdown(References, self.ddlOptionalRefType, locatorType="xpath") # references_number = customerReferences['Reference number'] + Util.get_unique_number( 8 ) # self.sendKeys( references_number, self.txtOptionalReferenceNumber, locatorType="xpath" ) except Exception as e: self.log.error( "Problem occurred while adding Optional references. :: ") def select_customer_category(self, customerCategory): try: new = self.labelsOnUI['lbl_CustCategory_SubEntity'] if str(customerCategory) == str( self.labelsOnUI['lbl_CustCategory_SubEntity']): self.elementClick(self.rdoSubEntity, locatorType="xpath") else: self.elementClick(self.rdoClient, locatorType="xpath") except Exception as e: self.log.error( "Error occurred while selecting the customer category :: " + customerCategory) def select_customer_type(self, custType): try: if custType == self.labelsOnUI['lbl_CustCategory_SubEntity']: self.elementClick(self.rdoCorporate, locatorType="xpath") else: self.elementClick(self.rdoIndividual, locatorType="xpath") except: self.log.error( "Error occurred while selecting the customer category :: " + custType) def setName(self, Name, PreferredName): try: self.sendKeys(Name, self.txtName, locatorType="xpath") self.sendKeys(PreferredName, self.txtPreferredName, locatorType="xpath") except Exception as e: self.log.error("Error occurred while seting the Name :: " + Name) def set_customer_id(self, customerId): try: self.strCustomerId = customerId # + Util.get_unique_number( 10 ) self.sendKeys(self.strCustomerId, self.txtCustomerId, locatorType="xpath") except Exception as e: self.log.error("Error occurred while seting the CustomerId :: " + self.strCustomerId) def select_sector_classification(self, sector_classification): try: self.selectvaluefromDropdown(sector_classification, self.ddlSectorClassification, locatorType="xpath") except Exception as e: self.log.error( "Error occurred while seting the Sector Classification :: " + sector_classification) def select_Market_Segment(self, market_segment): try: self.selectvaluefromDropdown(market_segment, self.ddlMarketSegment, locatorType="xpath") except Exception as e: self.log.error( "Error occurred while seting the Market Segment :: " + market_segment) def decide_Whether_Clients_Allowed(self, subCustomerAllowed): try: if subCustomerAllowed == 'True': self.log.info("Making client allowed checkbox enabled :: ") else: self.elementClick(self.chkClientsAllowedLabel, locatorType="xpath") self.log.info("Making client allowed checkbox disabled :: ") except Exception as e: self.log.error( "Error occurred while setting the Market Segment :: ") def clickOnAddCustomerButton(self): try: self.elementClick(self.btnAddCustomer.format( self.labelsOnUI['btn_Add_Customer']), locatorType="xpath") except Exception as e: self.log.error("Error occurred while filling address details. :: ") def activateCustomer(self, companyName): try: self.waitForElement(self.btnSendForActivation) self.elementClick(self.btnSendForActivation, locatorType="xpath") self.waitForElement(self.chkboxChooseBranchForApproval) self.elementClick( self.chkboxChooseBranchForApproval.format(companyName), locatorType="xpath") self.elementClick(self.btnSend, locatorType="xpath") except Exception as e: self.log.error("Error occurred while filling address details. :: ") def fillEditCustomerInformation(self, customerdetails): try: self.setName(customerdetails[self.labelsOnUI['Lbl_Name']], customerdetails[self.labelsOnUI['Lbl_PreferredName']]) self.fill_address_details(customerdetails) self.fill_contact_details(customerdetails) self.fill_customer_references(customerdetails['Reference type'], customerdetails['Reference number']) except Exception as e: self.log.error("Error occurred while filling address details. :: ") def clickOnSaveChangesButton(self): try: self.elementClick(self.btnSave.format( self.labelsOnUI['btn_Save_Changes']), locatorType="xpath") self.isElementDisplayed( self.progressBarlocator.format( self.labelsOnUI['MessageTemplateAddedSuccessfully'])) self.waitForElementInVisible(self.progressBarlocator.format( self.labelsOnUI['msg_CustomerUpdateMessage']), locatorType="xpath") except Exception as e: self.log.error("Error occurred while filling address details. :: ") def disabledClientsallowed(self): try: self.wait_for_page_load(2) self.elementClick(self.chkClientsAllowedLabel, locatorType="xpath") # self.isElementDisplayed(self.lnkMsg.format(self.labelsOnUI['MessageTemplateAddedSuccessfully'])) except Exception as e: self.log.error("Error occurred while filling address details. :: ") def verifyElementIsEnabledOrDisabled(self): try: self.elementClick(self.btnSave.format( self.labelsOnUI['btn_Save_Changes']), locatorType="xpath") self.isElementDisplayed( self.lnkMsg.format( self.labelsOnUI['MessageTemplateAddedSuccessfully'])) except Exception as e: self.log.error("Error occurred while filling address details. :: ")
class SearchItemPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver ################ ### Locators ### ################ _itemlist = "/html[1]/body[1]/div[1]/div[2]/div[1]/div[3]/div[2]/ul[1]/li[1]/div[1]/div[2]/h5[1]/a[1]" #_itemSelect = "/html[1]/body[1]/div[1]/div[2]/div[1]/div[3]/div[1]/div[1]/div[1]/div[3]/h1[1]" _search_box = "search_query_top" _search_button = "submit_search" _search_result = "//li[contains(@class,'ajax_block_product')]" #_search_result = "h5[itemprop='name'] a[class$='product-name']" ############################ ### Element Interactions ### ############################ # click category Women def clickCategory(self, category): try: if category == "Women": _category = "//a[@class='sf-with-ul'][normalize-space()='Women']" elif category == "Dresses": _category = "//div[@id='block_top_menu']/ul/li[2]/a[@title='Dresses']" elif category == "T-shirts": _category = "//div[@id='block_top_menu']/ul/li[3]/a[@title='T-shirts']" self.elementClick(locator=_category, locatorType="xpath") self.webScroll("down", 800) return True except: self.log.info("Category is not defined.") return False # Select an item and get its name def selectItem(self, itemSearch): try: products = self.driver.find_elements_by_xpath( "//li[contains(@class,'ajax_block_product')]") for product in products: elementproduct = product.find_element_by_xpath( "div/div/h5/a").text if elementproduct == itemSearch: return elementproduct, True except: self.log.error("Failed to find an item") return False # Enter this item into page search box and begin search def searchItem(self, itemName): if itemName is not None: self.sendKeys(itemName, locator=self._search_box) self.elementClick(locator=self._search_button, locatorType="name") self.webScroll() return True else: self.log.error("Failed to find an item") return False # Verify search result def getSearchResult(self, SelectItem): #SearchResult = self.getText(locator=self._search_result,locatorType="css") products = self.driver.find_elements_by_xpath( "//li[contains(@class,'ajax_block_product')]") #print(products) for product in products: # if item.getElement(locator="div/div/h5/a",locatorType="xpath").text == SelectItem: try: productElement = product.find_element_by_xpath("div/div/h5/a") productReturn = productElement.text if productReturn == SelectItem: time.sleep(1) productElement.click() self.webScroll() return True except: self.log.error("Return item does not match") return False
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def getByType(self, locatorType): locatorType = locatorType.lower() if locatorType == "id": return By.ID elif locatorType == "name": return By.NAME elif locatorType == "xpath": return By.XPATH elif locatorType == "css": return By.CSS_SELECTOR elif locatorType == "class": return By.CLASS_NAME elif locatorType == "link": return By.LINK_TEXT else: self.log.info("Locator type " + locatorType + " not correct/supported") return False def getElement(self, locator, locatorType="id"): element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info("Element found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def getCookies(self): cookies = self.driver.get_cookies() return cookies def getParentWindowHandle(self): parent_handle = self.driver.current_window_handle self.log.info(parent_handle) return parent_handle def getAllWindowHandle(self, locator, locatorType): parent_handle = self.getParentWindowHandle() self.elementClick(locator, locatorType) handles = self.driver.window_handles for handle in handles: self.log.info("inside for loop") if handle not in parent_handle: self.log.info(handle) child_window = handle time.sleep(2) self.driver.switch_to.window(child_window) self.log.info("switched window") return def pressEnter(self, locator, locatorType='id'): try: element = self.getElement(locator, locatorType) element.send_keys(Keys.ENTER) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def sendKeys(self, data, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def isElementPresent(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) if element is not None: self.log.info("Element Found") return True else: self.log.info("Element not found") return False except: print("Element not found") return False def elementPresenceCheck(self, locator, byType): try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element Found") return True else: self.log.info("Element not found") return False except: self.log.info("Element not found") return False def waitForElement(self, locator, locatorType="id", timeout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, 10, poll_frequency=1, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until( EC.element_to_be_clickable((byType, "stopFilter_stops-0"))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") print_stack() return element def wescroll(self): self.driver.execute_script("window.scrollTo(0, 200);")
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def wait_until_angular(self, TIMEOUT) -> None: java_script_to_load_angular = "var injector = window.angular.element('body').injector(); " \ "var $http = injector.get('$http');" \ "return ($http.pendingRequests.length === 0);" end_time = datetime.utcnow() + timedelta(seconds=TIMEOUT) print("wait for Angular Elements....") while datetime.utcnow() < end_time: try: if self.driver.execute_script(java_script_to_load_angular): return except WebDriverException: continue sleep(1) raise TimeoutError("waiting for angular elements for too long") 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() byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info("Element found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def getElementList(self, locator, locatorType="id"): """ NEW METHOD Get list of elements """ element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_elements(byType, locator) self.log.info("Element list found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element list not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator="", locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty #self.waitForElement(locator) element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def selectvaluefromDropdown(self, optionText, locator="", locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: element = Select(self.getElement(locator, locatorType)) element.select_by_visible_text(optionText) self.log.info("Select value from element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info( "Cannot select value from the element with locator: " + locator + " locatorType: " + locatorType) def sendKeys(self, data, locator="", locatorType="id", element=None): """ Send keys to an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.clear() element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def sendKeysAndEnter(self, data, locator="", locatorType="id", element=None): """ Send keys to an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.clear() element.send_keys(data) element.send_keys(Keys.ENTER) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def clearField(self, locator="", locatorType="id"): """ Clear an element field """ element = self.getElement(locator, locatorType) element.clear() self.log.info("Clear field with locator: " + locator + " locatorType: " + locatorType) def getText(self, locator="", locatorType="id", element=None, info=""): """ NEW METHOD Get 'Text' on an element Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) text = element.text if len(text) == 0: text = element.get_attribute("innerText") if len(text) != 0: self.log.info("Getting text on element :: " + info) self.log.info("The text is :: '" + text + "'") text = text.strip() except: self.log.error("Failed to get text on element " + info) 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: self.log.info("Element not found") return False def elementPresenceCheck(self, locator, byType): """ Check if element is present """ try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element present with locator: " + locator + " locatorType: " + str(byType)) return True else: self.log.info("Element not present with locator: " + locator + " locatorType: " + str(byType)) return False except: self.log.info("Element not found") return False def waitForElement(self, locator, locatorType="id", timeout=2, 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 waitForElementInVisible(self, locator, locatorType="id", timeout=5, 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.invisibility_of_element((byType, locator))) self.log.info("Element is visible appeared on the web page") except: self.log.info("Element not appeared on the web page") return element NG_WRAPPER = '%(prefix)s' \ 'angular.element(document.querySelector(\'[data-ng-app]\')|(document).' \ 'injector().get(\'$browser\').notifyWhenNoOutStandingRequests(%(handler)s)' \ '%(suffix)s' # def wait_until_angular_ready(self, timeout=None, error=None): # """Waits until [https://goo.gl/Kzz8Y3|AngularJS] is ready to process the next request or # ``timeout`` expires. # # Arguments: # - ``timeout``: The maximum value to wait for [https://goo.gl/Kzz8Y3|AngularJS] # to be ready to process the next request. # See `introduction` for more information about ``timeout`` and # its default value. # - ``error``: The value that would be use to override the default error message. # # Examples: # | Wait Until Angular Ready | 15s | # """ # # pylint: disable=no-member # timeout = self._get_timeout_value(timeout, self._implicit_wait_in_secs) # if not error: # error = 'AngularJS is not ready in %s' % self._format_timeout(timeout) # # we add more validation here to support transition # # between AngularJs to non AngularJS page. # # pylint: disable=no-member # script = self.NG_WRAPPER % {'prefix': 'var cb=arguments[arguments.length-1];' # 'if(window.angular){', # 'handler': 'function(){cb(true)}', # 'suffix': '}else{cb(true)}'} # # pylint: disable=no-member # browser = self._current_browser() # browser.set_script_timeout(timeout) # # pylint: disable=bare-except # try: # WebDriverWait(browser, timeout, self._inputs['poll_frequency']). \ # until(lambda driver: driver.execute_async_script(script), error) # except TimeoutException: # # prevent double wait # pass # except: # self._debug(exc_info()[0]) # # still inflight, second chance. let the browser take a deep breath... # time.sleep(self._inputs['browser_breath_delay']) # try: # WebDriverWait(browser, timeout, self._inputs['poll_frequency']). \ # until(lambda driver: driver.execute_async_script(script), error) # except: # # instead of halting the process because AngularJS is not ready # # in <TIMEOUT>, we try our luck... # self._debug(exc_info()[0]) # finally: # browser.set_script_timeout(self._timeout_in_secs) # finally: # browser.set_script_timeout(self._timeout_in_secs) 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, 200);") def elementScroll(self, tablescroll, elementlocator): """ NEW METHOD """ dragger = ActionChains(self.driver) self.draggablePartOfScrollbar = self.driver.find_element_by_xpath( tablescroll) numberOfPixelsToDragTheScrollbarDown = 25 findFlag = False while not findFlag: dragger.move_to_element(self.draggablePartOfScrollbar). \ click_and_hold().move_by_offset(0, numberOfPixelsToDragTheScrollbarDown).release().perform() findFlag = self.isElementDisplayed(elementlocator, locatorType="xpath") if findFlag: break return findFlag def executeJavaScript(self, locator, locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty self.element = self.driver.find_element_by_xpath(locator) self.driver.execute_script("arguments[0].click()", self.element) self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def iselementSelected(self, locator, locatorType=""): """ Check if element is present """ try: element = self.driver.find_element_by_xpath(locator) flag = element.is_selected() if flag == True: self.log.info("Element is selected with locator: " + locator + " locatorType: ") return True else: self.log.info("Element not selected with locator: " + locator + " locatorType: ") return False except: self.log.info("Element not found") return False def wait_for_page_load(self, timeout=10): time.sleep(timeout) def wait_and_refresh(self, timeout=10): time.sleep(timeout) self.driver.refresh() WAIT_FOR_SCRIPT = """ callback = arguments[arguments.length - 1]; try { var testabilities = window.getAllAngularTestabilities(); var count = testabilities.length; var decrement = function() { count--; if (count === 0) { callback('completed'); } }; testabilities.forEach(function(testability) { testability.whenStable(decrement); }); } catch (err) { callback(err.message); } """ def wait_for_angular(self, timeout): self.driver.set_script_timeout(timeout) self.driver.execute_async_script(self.WAIT_FOR_SCRIPT)
class Users( BasePage ): log = cl.customLogger( logging.DEBUG ) def __init__(self, driver): super().__init__( driver ) self.driver = driver self.status = TestStatus( self.driver ) progressBar = "//div[@class='simple-notification success ng-trigger ng-trigger-enterLeave']" txtUserId = "//input[@id='ID']" txtNumberOfVotes = "//input[@id='votes']" txtFirstName = "//input[@id='firstName']" txtLastName = "//input[@id='lastName']" txtEmailId = "//input[@id='email']" txtPhone = "//input[@id='phone']" txtPassword = "******" txtRepeatPassword = "******" txtSearchUser = "******" # Select boxes ddlProfile = "//select[@formcontrolname='roleId']" ddlStatusfilter = "//span[@class='ml-2']/../following-sibling::div/div[text()='{0}']" ddlFilter = "//span[@class='ml-2']" # ddlProfile = "#select[@id='profile']" # Button btnAddUser = "******" btnAddSaveUser = "******" btnSaveUser = "******" btnBankUser = "******", "Bank User Button" btnAddMainUser = "******", "Add Main User" # rdoUserStatus = "#label[contains(@class,'custom-control custom-radio')]/span[text()='%s']" rdoUserStatus = "//label[contains(@class,'custom-control-label')][(text()='%s')]", "User Status Radio Button" # links Lnksetup = "//span[contains(.,'Setup')]" LnkView = "//*[text()[normalize-space() = '{0}']]//following-sibling::td//a[text()[normalize-space() = 'View']]" LnkViewEditDelete = "//td/following-sibling::td/span/a[contains(.,'{0}')]" LnkHiddenDelete = "//td[contains(.,' 970D')]/following-sibling::td/span[@style='visibility: hidden;']/a[contains(.,'Delete')]", "Delete Hidden Link" lnkResetPassWord = "******", "Reset Password Link" lnkBankUserStatusFilter = "//span[contains(text(),'%s')]", "Bank User Staus Filter Link" lblAddUser = "******", "Add User Label" lnkUserProfile = "//div#li[@class='nav-item d-none d-md-flex dropdown']/a/app-icon", "user Profile Link" actionList = "#div[@class='list-group']/a[text()[normalize-space() = '%s']]", "Action List on Account OvewView Page" # dates ActiveFromDate = "#input[@id='fromDate' and @placeholder='YYYY-MM-DD']", "Active From Date" ActiveToDate = "#input[@id='toDate' and @placeholder='YYYY-MM-DD']", "Active To Date" lnkiconActiveFromDate = "(#*[name()='svg' and @class='icon icon-calendar'])[1]", "Active From DateCalender Icon" lnkiconActiveToDate = "(#*[name()='svg' and @class='icon icon-calendar'])[2]", "Active To DateCalender Icon" # msg msg = "#div[contains(text(),'%s')]" # lable lblMandatory = "#label[@class='required'][contains(text(),'%s')]", "Mandatory Label" lblOptional = "#label[contains(.,'%s')]", "Optional Label" lblUserDetails = "//label[contains(.,'{0}')]/following-sibling::p" lblAccessRights = "//tbody/tr[@class='ng-star-inserted']/td[{0}]" # lblAccessRights = "//tbody/tr[@class='ng-star-inserted']//p[contains(text(),'{0}')]" lblStatus = "//label[contains(.,'{0}')]/../p/strong" strGenericTableXpath = "#td[contains(.,'%s')]#ancestor::tr#td[count(#*[normalize-space(text())='%s']#ancestor-or-self::th/preceding-sibling::th)+1]" # strUserName="******" strUserName = "******", "UserName" # strUserName="******" # other msgValidation = "#label[contains(.,'%s')]/../div" tblBankStatus = "#tbody[contains(@class,'ng-tns-c')]/tr[%s]/td[4]", "Bank Status in Table" tblBankStatusRows = "#tbody[contains(@class,'ng-tns-c')]/tr", "Bank Status rows in Table" tblCustStatus = "#tbody[@class='ng-tns-c14-6 ng-star-inserted']/tr/td[5]", "Customer Status in Table" tblCustStatusRows = "#tbody[@class='ng-tns-c14-6 ng-star-inserted']", "Customer Status rows in Table" btnDeleteCustomer = "#a[contains(text(),'%s')]/button", "Delete Customer Button" btnDeleteConfirm = "#div/button[contains(.,'%s')]", "Delete Confirm Button" btnCancelConfirm = "#div/a[contains(.,'%s')]", "Cancel Confirm Button" msgDeleteConfirm = "#div/p[contains(text(),'%s')]", "Delete Confirm Message" titleCustomerNameConfirm = "#div/h4[contains(text(),'%s')]", "Title Customer Name Confirm" adminTitle = "#a[contains(.,'Admin')]", "Admin Title" selectBankRoleID = "#select[@formcontrolname='roleId']", "Select Bank Role ID" txtRolesAllValue = "#select[@formcontrolname='roleId']/option", "Bank Role ID Values" btnChangelog = "#button[text()[normalize-space()='%s']]", "Changelog Button" btnEdit = "#button[@id='editButton1']", "Edit Button" btnClose = "//button[@type='submit']" strParentCustName = "#div/strong[contains(text(), '%s')]/parent::div/following-sibling::small[contains(text(),'%s')]", "Parent Customer Name" usersTitle = "#span[contains(.,'users')]", "Users Title" lblUserId = "#tbody[contains(@class,'ng-tns-c')]/tr/td[contains(.,'%s')]", "Users id" def createUsers(self, usersABO): try: self.wait_until_angular(3) self.clickOnAddUserButton() self.fillUsersDetails(usersABO) self.clickOnAddOrSaveButton() # self.verifyMessage("UserSuccessCreateMessage", "User is successfully Created", # " Not able to Create user. Success message not displayed.") except Exception as e: self.log.error( "Error occurred while creating user ::" ) def clickOnAddUserButton(self): try: self.waitForElement( self.btnAddUser, 4 ) # self.elementClick( self.btnAddUser.format( self.labelsOnUI.get( 'AddUser' ) ), # locatorType="xpath" ) self.executeJavaScript(self.btnAddUser.format(self.labelsOnUI.get('AddUser')), locatorType="xpath") except Exception as e: self.log.error( "Error occurred while click on the Add user button::" ) def fillUsersDetails(self, usersABO): try: self.wait_for_page_load(2) self.sendKeys(usersABO[self.labelsOnUI['UserID']][0], self.txtUserId, locatorType="xpath") self.sendKeys(usersABO[self.labelsOnUI['FirstName']][0], self.txtFirstName, locatorType="xpath") self.sendKeys(usersABO[self.labelsOnUI['LastName']][0], self.txtLastName, locatorType="xpath") self.sendKeys(usersABO[self.labelsOnUI['Email']][0], self.txtEmailId, locatorType="xpath") self.sendKeys(str(usersABO[self.labelsOnUI['Phone']][0]), self.txtPhone, locatorType="xpath") self.selectvaluefromDropdown(usersABO[self.labelsOnUI['lbl_Profile']][0], self.ddlProfile, locatorType="xpath") self.sendKeys(usersABO[self.labelsOnUI['Password']][0], self.txtPassword, locatorType="xpath") self.sendKeys(usersABO[self.labelsOnUI['RepeatPassword']][0], self.txtRepeatPassword, locatorType="xpath") except Exception as e: self.log.error( "Exception occurred while entering User's Details::" ) def clickOnAddOrSaveButton(self): try: # self.waitForElement(self.ddlAccountType ) self.elementClick(self.btnAddSaveUser.format(self.labelsOnUI['AddUser']), locatorType="xpath") except Exception as e: self.log.error( "Error occurred while click on the Add user button of Add user screen::" ) def searchUser(self, usersABO): try: self.wait_for_page_load( 7 ) self.sendKeysAndEnter(usersABO, self.txtSearchUser, locatorType="xpath") except Exception as e: self.log.error( "Exception occurred while doing search users ::" ) def verifyDetails(self, usersABO): result = False try: result = self.verifyUserDetails( usersABO ) self.closeUserDetailPage() except Exception as e: result = False self.log.error( "Exception occurred while doing search users ::" ) return result def clickOnViewUserlink(self, user): try: self.wait_for_page_load( 4 ) # self.waitForElement(self.LnkViewEditDelete.format( self.labelsOnUI.get( 'View' )),4,2) self.elementClick(self.LnkView.format(user.upper()), locatorType="xpath") except Exception as e: self.log.error( "Exception occurred in clickOnViewUser ::" ) def verifyUserDetails(self, usersDetails): result = False try: self.wait_for_page_load( 5 ) self.status = TestStatus(self.driver) self.status.mark(self.verify(self.lblUserDetails.format(self.labelsOnUI['UserID']), usersDetails[self.labelsOnUI['UserID']][0]), "Incorrect match") self.status.mark(self.verify(self.lblUserDetails.format(self.labelsOnUI['Lbl_FName']), usersDetails[self.labelsOnUI['Lbl_FName']][0]), "Incorrect match") self.status.mark(self.verify(self.lblUserDetails.format(self.labelsOnUI['Lbl_LName']), usersDetails[self.labelsOnUI['Lbl_LName']][0]), "Incorrect match") self.status.mark(self.verify(self.lblUserDetails.format(self.labelsOnUI['Email']), usersDetails[self.labelsOnUI['Email']][0]), "Incorrect match") self.status.mark(self.verify(self.lblUserDetails.format(self.labelsOnUI['Phone']), usersDetails[self.labelsOnUI['Phone']][0]), "Incorrect match") self.status.mark(self.verify(self.lblStatus.format(self.labelsOnUI['UserStatus']), usersDetails[self.labelsOnUI['UserStatus']][0]), "Incorrect match") self.status.mark(self.verify(self.lblAccessRights.format(self.labelsOnUI['BankId']), usersDetails[self.labelsOnUI['Lbl_BankID']][0]), "Incorrect match") self.status.mark(self.verify(self.lblAccessRights.format(self.labelsOnUI['Profile']), usersDetails[self.labelsOnUI['lbl_profile_User']][0]), "Incorrect match") result = self.status.aggregateResult("verifyUserDetails", result, "Verification is Successful") self.log.info("Successfully verify Customer basic details::") except Exception as e: result = False self.log.error( "Exception occurred while verifying user details ::" ) return result def closeUserDetailPage(self): try: self.waitForElement( self.btnClose ) self.elementClick(self.btnClose.format(self.labelsOnUI['AddUser']), locatorType="xpath") except Exception as e: self.log.error( "Exception occurred while doing search users ::" ) def verifyAddUserButtonNotDisplayed(self): result = False try: value = (self.isElementDisplayed(self.btnAddUser.format(self.labelsOnUI['AddUser']), locatorType="xpath")) if not value: result = True self.log.info("Successfully verify AddUser Button is Not Displayed::") except Exception as e: self.log.error("Failed to verify AddUser Button::") return result
class excelUtil(): log = lg.customLogger(logging.DEBUG) constants = Constants() # Open excel def setExcelFile(self,path): try: self.workbook = xlrd.open_workbook(path) except: self.log.error("Data file was not opened") # Get rowcount def getRowCount(self,sheetname): try: self.worksheet = "" self.worksheet = self.workbook.sheet_by_name(sheetname) iNum = self.worksheet.nrows+1 return iNum except: self.log.error("Failed to get row count") # Get cell value def getCellData(self,RowNum,ColNum,sheetname): try: self.worksheet = "" self.worksheet = self.workbook.sheet_by_name(sheetname) self.CellData = str(self.worksheet.cell_value(RowNum,ColNum)) return self.CellData except: self.log.error("Failed to get cell data: "+ str(RowNum)+ " "+ str(sheetname)) # Search for a value and exit if found and return rowID def getRowContains(self,testname,ColNum,sheetname): RowNum = 0 try: rowCount=0 rowCount = self.getRowCount(sheetname) for RowNum in range(0,rowCount): if self.getCellData(RowNum,ColNum,sheetname) == testname: break except: self.log.error("Row contains check failed") return RowNum # Return test steps count def getTestStepsCount(self,sheetname,testname,stepstart): try: rowCount=0 rowCount = self.getRowCount(sheetname) i=0 for i in range(stepstart,rowCount): if str(testname) != str(self.getCellData(i,self.constants.Col_TestCaseID,sheetname)): return i except: self.log.error("Failed to get steps count") return 0 # Return test steps count def getITCount(self,sheetn,testn,stepst): try: rowCount = 0 rowCount = self.getRowCount(sheetn) i = 0 for i in range(stepst, rowCount): if str(testn) != str(self.getCellData(i, self.constants.Col_TestCaseID, sheetn)): return i except: self.log.error("Failed to get steps count") return 0 # Return object xpath value def getLocator(self, sheetname, locatorKeyword): try: nTotalRow = self.getRowCount(sheetname) for nRow in range(0,nTotalRow): if locatorKeyword == "": break elif str(locatorKeyword) == str(self.getCellData(nRow, 0, sheetname)): locatorValue = str(self.getCellData(nRow, self.constants.Col_Locator, sheetname)) return locatorValue except: self.log.error("Failed to get object value") def getLocatorType(self, sheetname, locatorKeyword): try: nTotalRow = self.getRowCount(sheetname) for nRow in range(0, nTotalRow): if locatorKeyword == "": break elif str(locatorKeyword) == str(self.getCellData(nRow, 0, sheetname)): locatorType = str(self.getCellData(nRow, self.constants.Col_LocatorType, sheetname)) return locatorType except: self.log.error("Failed to get locator type") # Get test case iterations count def getTestIterations(self,sheetname,testname): try: isSheet = self.workbook.sheet_names() for i in range(len(isSheet)): if str(testname) == str(isSheet[i]): iterate = 0 iterate = self.getITCount(sheetname,testname,1) else: continue if iterate > 0: return iterate else: return 2 except Exception as e: return 2 # Get test data value if parametrized def getTestdatavalue(self,testname,data,rownum): try: self.test_work_sheet = self.workbook.sheet_by_name(testname) test_rows = self.test_work_sheet.nrows test_cols = self.test_work_sheet.ncols for irows in range(0,1): for icols in range(0,test_cols): test_data_header = self.getCellData(irows,icols,testname) if test_data_header == data: testdata_value = self.getCellData(rownum, icols, testname) return testdata_value else: pass except: pass
class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) # Call super constructor and pass driver. Need driver for LoginPage too. def __init__(self, driver): super().__init__(driver) self.driver = driver self.nav = NavigationPage(driver) # Locators # _login_link = "Login" # _email_field = "user_email" # _password_field = "user_password" # _login_button = "commit" _login_link = "Sign in" _email_field = "email" _password_field = "passwd" _login_button = "SubmitLogin" _successful_validation = "//p[@class='info-account']" _unsuccessful_validation = "//p[contains(text(),'There is 1 error')]" # The custom elementClick and sendKeys methods locate the element then perform the action on the element # sendKeys is the custom method, not send_keys def clickLoginLink(self): self.elementClick(self._login_link, locatorType="link") return True def enterEmail(self, email): self.sendKeys(email, self._email_field) return True def enterPassword(self, password): self.sendKeys(password, self._password_field) return True def clickLoginButton(self): self.elementClick(self._login_button, locatorType="id") return True def login(self, email="", password=""): self.clickLoginLink() time.sleep(1) self.log.info("Wait for a while") self.webScroll() self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() time.sleep(1) self.log.info("Wait for a while") def verifyLoginSuccessful(self): result = self.isElementPresent(locator=self._successful_validation, locatorType="xpath") return result def verifyLoginFailed(self): result = self.isElementPresent(locator=self._unsuccessful_validation, locatorType="xpath") return result def clearLoginFields(self): emailField = self.getElement(locator=self._email_field) emailField.clear() passwordField = self.getElement(locator=self._password_field) passwordField.clear() def verifyLoginTitle(self): return self.verifyPageTitle("Google") def logout(self): #self.nav.navigateToUserSettings() self.elementClick(locator="Sign out", locatorType="link")
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def screenShot(self, resultMessage): """ Takes screenshot of the current open web page """ fileName = resultMessage + "." + str(round( time.time() * 1000)) + ".png" screenshotDirectory = "../screenshots/" relativeFileName = screenshotDirectory + fileName currentDirectory = os.path.dirname(__file__) destinationFile = os.path.join(currentDirectory, relativeFileName) destinationDirectory = os.path.join(currentDirectory, screenshotDirectory) try: if not os.path.exists(destinationDirectory): os.makedirs(destinationDirectory) self.driver.save_screenshot(destinationFile) self.log.info("Screenshot save to directory: " + destinationFile) except: self.log.error("### Exception Occurred when taking screenshot") print_stack() def getByType(self, locatorType): locatorType = locatorType.lower() if locatorType == "id": return By.ID elif locatorType == "name": return By.NAME elif locatorType == "xpath": return By.XPATH elif locatorType == "css": return By.CSS_SELECTOR elif locatorType == "class": return By.CLASS_NAME elif locatorType == "link": return By.LINK_TEXT else: self.log.info("Locator type " + locatorType + " not correct/supported") return False def getElement(self, locator, locatorType="id"): element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info("Element found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def clickElement(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def sendKeys(self, data, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def isElementPresent(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) if element is not None: self.log.info("Element Found") return True else: self.log.info("Element not found") return False except: print("Element not found") return False def getPageTitle(self): try: return self.driver.title except: self.log.error("Title not found") def elementPresenceCheck(self, locator, byType): try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element Found") return True else: self.log.info("Element not found") return False except: self.log.info("Element not found") return False def waitForElement(self, locator, locatorType="id", timeout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, 10, poll_frequency=1, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until( EC.element_to_be_clickable((byType, "stopFilter_stops-0"))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") print_stack() return element
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def screenShot(self, resultMessage): fileName = resultMessage + "." + str(round( time.time() * 1000)) + ".png" screenShotDirectory = "../screenshots/" relativeFileName = screenShotDirectory + fileName currentDirectory = os.path.dirname(__file__) 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 saved to directory" + destinationFile) except: self.log.error("### Exception occured when taking screenshot") print_stack() def getTitle(self): return self.driver.title def getByType(self, locatorType): locatorType = locatorType.lower() if locatorType == "id": return By.ID elif locatorType == "name": return By.NAME elif locatorType == "xpath": return By.XPATH elif locatorType == "css": return By.CSS_SELECTOR elif locatorType == "class": return By.CLASS_NAME elif locatorType == "link": return By.LINK_TEXT else: self.log.info("Locator type " + locatorType + " not correct/supported") return False def getElement(self, locator, locatorType="id"): element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info("Element found with locator: " + locator + " and locator type: " + locatorType) except: self.log.info("Element not found with locator: " + locator + " and locator type: " + locatorType) return element def getElementList(self, locator, locatorType="id"): """ NEW METHOD Get list of elements """ element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_elements(byType, locator) self.log.info("Element list found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element list not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator="", locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def sendKeys(self, data, locator="", locatorType="id", element=None): """ Send keys to an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def getText(self, locator="", locatorType="id", element=None, info=""): """ NEW METHOD Get 'Text' on an element Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty self.log.debug("In locator condition") element = self.getElement(locator, locatorType) self.log.debug("Before finding text") text = element.text self.log.debug("After finding element, size is: " + str(len(text))) if len(text) == 0: text = element.get_attribute("innerText") if len(text) != 0: self.log.info("Getting text on element :: " + info) self.log.info("The text is :: '" + text + "'") text = text.strip() except: self.log.error("Failed to get text on element " + info) print_stack() text = None return text def getElementByPartialLinkText(self, text): element = self.driver.find_element_by_partial_link_text(text) return element def isElementPresent(self, locator="", locatorType="id", element=None): """ Check if element is present -> MODIFIED Either provide element or a combination of locator and locatorType """ self.driver.implicitly_wait(1) 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") self.driver.implicitly_wait(10) 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 with locator: " + locator + " locatorType: " + locatorType) else: self.log.info("Element not displayed with locator: " + locator + " locatorType: " + locatorType) return isDisplayed except: print("Element not found") return False def elementPresenceCheck(self, locator, byType): """ Check if element is present """ try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element present with locator: " + locator + " locatorType: " + str(byType)) return True else: self.log.info("Element not present with locator: " + locator + " locatorType: " + str(byType)) return False except: self.log.info("Element not found") return False def getCurrentUrl(self): currentUrl = self.driver.current_url return currentUrl def redirectUrlWithCurrent(self, url): currentUrl = self.getCurrentUrl() redirectUrl = self.driver.get(currentUrl + url) return redirectUrl def waitForElement(self, locator, locatorType="id", timeout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=pollFrequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until(EC.element_to_be_clickable((byType, locator))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") print_stack() return element def webScroll(self, locator, locatorType="id"): element = self.getElement(locator, locatorType) self.driver.execute_script("arguments[0].scrollIntoView(true);", element) def mouseHover(self, locator, locatorType="id"): element = self.getElement(locator, locatorType) actions = ActionChains(self.driver) actions.move_to_element(element).perform() def switchToFrame(self, locator): self.driver.switch_to.frame(locator) def getElementByTagName(self, tagName): self.driver.find_element_by_tag_name(tagName)