class AddToFavouritePage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _categories_dropdown = "//div[@id='navbarNavDropdown']/div/ul[2]/li[3]/a" _category = "//section[@id='loadTopCategory']//aside" _category_breadcrumb = "//div[contains(@class,'pageheading')]//a[@id='clickCategory']" _category_tiles = "//div[@id='loadCategoryGroup']//div[contains(@class,'carousel-inner')]" _add_to_fav_link = "(//i[contains(@sectionofpage,'{0}')])[1]" _OK_button = "(//button[text()='OK'])[1]" _success_msg = "//div[contains(text(),'Added to your favourites.')]" def add_to_favouritefn(self): elements = [] elements = self.driver.find_elements_by_xpath(self._category_tiles) try: self.log.info("Inside loop") cat_hovered = elements[randint(0, len(elements) - 1)] self.log.info("Category idetified randomly %s", cat_hovered) text_cat_hovered = self.getText(element=cat_hovered) self.driver.execute_script( "arguments[0].scrollIntoView({block: 'center', inline: 'center'});", cat_hovered) time.sleep(4) action = ActionChains(self.driver) action.move_to_element(cat_hovered).perform() self.log.info("Hovered to element [%s] ", cat_hovered) time.sleep(2) #import pdb; pdb.set_trace() fav_link = self._add_to_fav_link.format(text_cat_hovered) target = self.driver.find_element_by_xpath(fav_link) self.driver.execute_script("arguments[0].click();", target) time.sleep(2) self.log.info("Clicked on the favourites icon") except Exception as e: self.log.error("Could not click on hovered tile link [%s]", e) self.log.error("Exception Caught: {}".format( traceback.format_exc())) self.log.error("".join(traceback.format_stack())) def verifyAddToFavourite(self): #self.driver.switch_to.frame("0") time.sleep(2) element = self.getElement(self._success_msg, locatorType="xpath") self.log.info("Added to favourites success message encountered [%s]", element) result = self.isElementPresent(self._success_msg, locatorType="xpath") #import pdb; pdb.set_trace() if result == True: self.elementClick(self._OK_button, locatorType="xpath") return result else: return False
class StatusCheck(SeleniumDriver): log = cl.customLogger(logging.INFO) def __init__(self, driver): """ Inits CheckPoint class """ super(StatusCheck, self).__init__(driver) self.resultList = [] def setResult(self, result, resultMessage): try: if result is not None: if result == True: 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, tcName, 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(tcName + " ### TEST FAILED") self.resultList.clear() else: self.log.info(tcName + " ### TEST SUCCESSFUL") self.resultList.clear()
class LoginPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _email_field = "email" _password_field = "password" _login_button = "//button[contains(text(),'Sign in')]" _Ampro_logo = "(//nav[@id='tsc_nav_1']/a/img)[1]" _incorrect_credentials_msg = "spanerrormsg" _logout = "//span[contains(@class,'glyphicon-log-out')]" 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="xpath") def login(self, email="", password=""): self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() time.sleep(2) def verifyLoginSuccessful(self): result = self.isElementPresent(self._Ampro_logo, locatorType="xpath") return result def verifyLoginFailed(self): result = self.isElementPresent(self._incorrect_credentials_msg, locatorType="xpath") return result
class CreateNewStrategyPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _categories_dropdown = "//div[@id='navbarNavDropdown']/div/ul[2]/li[3]/a" _category = "//section[@id='loadTopCategory']//aside" _category_breadcrumb = "//div[contains(@class,'pageheading')]//a[@id='clickCategory']" _category_tiles = "//div[@id='loadCategoryGroup']//div[contains(@class,'carousel-inner')]" _category_tile_link = "(//a[contains(@sectionofpage,'{0}')])[1]" _strategy_icon = "(//div[contains(@class,'icons')]/a/i)[1]" _insights_reports_tile = "(//div[@id='loadReports1']//div[contains(@class,'catContainer border')]//div/img)[1]" _continue_button = "IdContinue" _questions = "//form[contains(@class,'qaForm margin0')]//div//span[contains(@class,'quesNum')]//parent::label" _first_answer = "(//form[contains(@class,'qaForm margin0')]//div[{0}]//li[1]//div[contains(@class,'radio-btn')]//label)[1]" _show_my_strategy_button = "btnQASubmit" _strategy_plot = "strategeyDiv" def create_new_strategy_home_page(self): elements = [] elements = self.driver.find_elements_by_xpath(self._category_tiles) try: for x in elements: self.log.info("Inside loop") cat_hovered = elements[randint(0, len(elements) - 1)] self.log.info("Category idetified randomly %s", cat_hovered) text_cat_hovered = self.getText(element=cat_hovered) self.driver.execute_script( "arguments[0].scrollIntoView({block: 'center', inline: 'center'});", cat_hovered) time.sleep(4) action1 = ActionChains(self.driver) action1.move_to_element(cat_hovered).perform() self.log.info("Hovered to element [%s] ", cat_hovered) time.sleep(2) report_link = self._category_tile_link.format(text_cat_hovered) target = self.driver.find_element_by_xpath(report_link) target_text = self.getText(element=target) self.log.info("Link text on category tile [%s]", target_text) if target_text not in "Insights reports": continue else: break self.driver.execute_script("arguments[0].click();", target) time.sleep(4) self.log.info( "Landed on insight reports page %s", self.isElementPresent(self._random_click_insight_reports, locatorType="xpath")) tile = self.waitForElement(self._insights_reports_tile, locatorType="xpath") action2 = ActionChains(self.driver) action2.move_to_element(tile).perform() self.log.info("Tile found [%s] [%s]", tile.is_displayed(), tile) self.log.info("Hovered over Insight reports tile") icon = self.getElement(self._strategy_icon, locatorType="xpath") self.log.info("Strategy icon identified [%s]", icon) action2.move_to_element(icon).click().perform() self.waitForElement("iframeAutoLogin") self.driver.switch_to.frame("iframeAutoLogin") self.elementClick(self._continue_button) for q in range(1, 13): answer_clicked = self.getElement(self._first_answer.format(q), locatorType="xpath") self.log.info("Answer selected [%s]", self.getText(element=answer_clicked)) self.driver.execute_script("arguments[0].click();", answer_clicked) self.log.info("Question [%s] answered", q) time.sleep(2) #self.driver.find_element_by_tag_name('body').send_keys(Keys.END) submit_button = self.getElement(self._show_my_strategy_button) self.driver.execute_script("arguments[0].click();", submit_button) time.sleep(3) except Exception as e: self.log.error("Could not click on hovered tile link [%s]", e) self.log.error("Exception Caught: {}".format( traceback.format_exc())) self.log.error("".join(traceback.format_stack())) def verifycreatenewstrategy(self): result = self.isElementPresent(self._strategy_plot) if result == True: return result else: return False
class Covid19ResourceCentrePage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _Ampro_logo = "(//nav[@id='tsc_nav_1']/a/img)[1]" _Covid19_resource_centre = "//div[@id='navbarNavDropdown']/div/ul[2]/li[1]/a" _Sector_deep_dive = "covidsectorDeepDive-tab" _Category_snapshot = "covidcategorySnapshot-tab" _100_day_framework = "covid100DayFramework-tab" _Covid19_video_series = "covidcovid19VideoSeries-tab" _Covid19_breadcrumb = "//div[@class='row']/div/ol//li[contains(@class,'breadcrumb-item active')]" _No_record_message = "//div[contains(text(),'No record found')]" _tab1_img = "//div[@id='sectioncovidsectorDeepDive']/div[1]/div[1]/img" _tab2_img = "//div[@id='sectioncovidcategorySnapshot']/div[1]/div[1]/img" _tab3_img = "//div[@id='sectioncovid100DayFramework']/div[1]/div[1]/img" _tab4_vdo = "//div[@id='sectioncovidvideoSeries']/div[1]/iframe" def navigateToHome(self): self.elementClick(locator=self._Ampro_logo, locatorType="xpath") def navigateToCovid19ResourceCentre(self): self.elementClick(locator=self._Covid19_resource_centre, locatorType="xpath") time.sleep(2) def navigateToSectorDeepDive(self): self.webScroll(direction="down") self.elementClick(locator=self._Sector_deep_dive) time.sleep(2) def navigateToCategorySnapshot(self): self.elementClick(locator=self._Category_snapshot) time.sleep(2) def navigateTo100DayFramework(self): self.elementClick(locator=self._100_day_framework) time.sleep(2) def navigateToCovid19VideoSeries(self): self.elementClick(locator=self._Covid19_video_series) time.sleep(2) self.webScroll(direction="up") def verifyNavigationToCovid19Tab(self): result = self.isElementPresent(self._Covid19_breadcrumb, locatorType="xpath") return result def verifyNavigationToSectorDeepDive(self): tab1Message = self.getElement(self._No_record_message, locatorType="xpath") r1 = self.isElementPresent(self._tab1_img, locatorType="xpath") r2 = tab1Message.is_displayed() if r1 == True or r2 == True: #import pdb;pdb.set_trace() return True else: return False def verifyNavigationToCategorySnapshot(self): tab2Message = self.getElement(self._No_record_message, locatorType="xpath") r1 = self.isElementPresent(self._tab2_img, locatorType="xpath") r2 = tab2Message.is_displayed() if r1 == True or r2 == True: #import pdb;pdb.set_trace() return True else: return False def verifyNavigationTo100DayFramework(self): tab3Message = self.getElement(self._No_record_message, locatorType="xpath") r1 = self.isElementPresent(self._tab3_img, locatorType="xpath") r2 = tab3Message.is_displayed() if r1 == True or r2 == True: #import pdb;pdb.set_trace() return True else: return False def verifyNavigationToCovid19VideoSeries(self): tab4Message = self.getElement(self._No_record_message, locatorType="xpath") r1 = self.isElementPresent(self._tab4_vdo, locatorType="xpath") r2 = tab4Message.is_displayed() if r1 == True or r2 == True: #import pdb;pdb.set_trace() return True else: return False
class AllIntelligencePage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _all_intelligence = "//div[@id='navbarNavDropdown']/div/ul[2]/li[4]/a" _insights_reports = "(//a[contains(text(),'Insights reports')])[1]" _breadcrumb = "//div[contains(@class,'pageheading')]//ol//li[3]//a" _sustainability_reports = "(//a[contains(text(),'Sustainability reports')])[1]" _innovation_trends = "(//a[contains(text(),'Innovation trends')])[1]" _mega_trends = "(//a[contains(text(),'Mega trends')])[1]" _category_briefings = "(//a[contains(text(),'Category briefings')])[1]" _CASME_insights = "(//a[contains(text(),'CASME insights')])[1]" _cost_structures_drivers = "(//a[contains(text(),'Cost structures and drivers')])[1]" _commodities = "(//a[contains(text(),'Commodities')])[1]" _select_country = "//div[@id='collapseFilter']//button[@title='--Select country--']" _select_cost_structure = "//div[@id='collapseFilter']//button[@title='-- Select cost structure --']" _apply_button = "//div[@id='collapseFilter']//button[contains(text(),'Apply')]" _first_country = "(//ul[contains(@class,'multiselect-container dropdown-menu')]//li[3]//label)[1]" _first_cs = "//div[@id='collapseFilter']/div[2]/span[2]/div/ul/li[3]/a/label" _chart = "//div[@id='cs_chart']/div[2]" def navigateToAllIntelligence(self): self.elementClick(self._all_intelligence, locatorType="xpath") self.log.info("Clicked on All Intelligence top menu") def navigateToInsightsReports(self): action = ActionChains(self.driver) first_link = self.getElement(self._insights_reports, locatorType="xpath") action.move_to_element(first_link).click().perform() self.log.info( "Clicked on Insight Reports under All Intelligence top menu") time.sleep(4) def verifyNavigationToInsightsReports(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Insight reports [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Insights reports" and attribute_value == "All intelligence - Insights reports": return True else: return False def navigateToSustainabilityReports(self): action = ActionChains(self.driver) second_link = self.getElement(self._sustainability_reports, locatorType="xpath") action.move_to_element(second_link).click().perform() self.log.info( "Clicked on Sustainability Reports under All Intelligence top menu" ) time.sleep(4) def verifyNavigationToSustainabilityReports(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Sustainability reports [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Sustainability reports" and attribute_value == "All intelligence - Sustainability reports": return True else: return False def navigateToInnovationTrends(self): action = ActionChains(self.driver) third_link = self.getElement(self._innovation_trends, locatorType="xpath") action.move_to_element(third_link).click().perform() self.log.info( "Clicked on Innovation trends under All intelligence top menu") time.sleep(4) def verifyNavigationToInnovationTrends(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Innovation trends [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Innovation trends" and attribute_value == "All intelligence - Innovation trends": return True else: return False def navigateToMegaTrends(self): action = ActionChains(self.driver) fourth_link = self.getElement(self._mega_trends, locatorType="xpath") action.move_to_element(fourth_link).click().perform() self.log.info("Clicked on Mega trends under All intelligence top menu") time.sleep(4) def verifyNavigationToMegaTrends(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Mega trends [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Mega trends" and attribute_value == "All intelligence - Mega trends": return True else: return False def navigateToCategoryBriefings(self): action = ActionChains(self.driver) fifth_link = self.getElement(self._category_briefings, locatorType="xpath") action.move_to_element(fifth_link).click().perform() self.log.info( "Clicked on Category Briefings under All intelligence top menu") time.sleep(4) def verifyNavigationToCategoryBriefings(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Category briefings [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Category briefings" and attribute_value == "All intelligence - Category briefings": return True else: return False def navigateToCASMEInsights(self): action = ActionChains(self.driver) sixth_link = self.getElement(self._CASME_insights, locatorType="xpath") action.move_to_element(sixth_link).click().perform() self.log.info( "Clicked on CASME insights under All intelligence top menu") time.sleep(4) def verifyNavigationToCASMEInsights(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to CASME insights [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "CASME insights" and attribute_value == "All intelligence - CASME insights": return True else: return False def navigateToCostStructuresNDrivers(self): action = ActionChains(self.driver) seventh_link = self.getElement(self._cost_structures_drivers, locatorType="xpath") action.move_to_element(seventh_link).click().perform() self.log.info( "Clicked on Cost structures and drivers under All intelligence top menu" ) time.sleep(2) def chartFormation(self): try: self.elementClick(self._select_country, locatorType="xpath") self.log.info( "Select country dropdown clicked on Cost Structures and drivers" ) action = ActionChains(self.driver) element1 = self.getElement(self._first_country, locatorType="xpath") action.move_to_element(element1).click().perform() self.log.info("First country selected from dropdown") time.sleep(2) self.elementClick(self._select_cost_structure, locatorType="xpath") self.log.info( "Select cost structure dropdown clicked on Cost Structures and drivers" ) time.sleep(2) element2 = self.getElement(self._first_cs, locatorType="xpath") self.driver.execute_script("arguments[0].click();", element2) self.log.info("First cost structure selected") time.sleep(2) self.elementClick(self._apply_button, locatorType="xpath") self.log.info("Apply button clicked") time.sleep(2) except: self.log.error("Could not click on hovered tile link [%s]", e) self.log.error("Exception Caught: {}".format( traceback.format_exc())) self.log.error("".join(traceback.format_stack())) def verifyChartFormation(self): result = self.isElementPresent(self._chart, locatorType="xpath") if result == True: return result else: return False def verifyNavigationToCostStructuresNDrivers(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Cost structures and drivers [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Cost structures and drivers" and attribute_value == "All intelligence - Cost structures and drivers": return True else: return False def navigateToCommodities(self): action = ActionChains(self.driver) eighth_link = self.getElement(self._commodities, locatorType="xpath") #import pdb;pdb.set_trace() action.move_to_element(eighth_link).click().perform() self.log.info("Clicked on Commodities under All intelligence top menu") time.sleep(4) def verifyNavigationToCommodities(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Commodities [%s]", breadcrumb) attribute_value = breadcrumb.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Commodities" and attribute_value == "All intelligence - Commodities": return True else: return False
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 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 elif locatorType == "tagname": return By.TAG_NAME else: self.log.error("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.error("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def getElements(self,locator,locatorType): elements=None try: locatorType=locatorType.lower() byType=self.getbyType(locatorType) elements=self.driver.find_elements(byType,locator) self.log.info('element Found with locator '+ locator+ ' and locatorType '+locatorType) except: self.log.error('Element not found in getElement '+ locator+ ' and locatorType '+locatorType) return elements def elementClick(self,locator="", locatorType="id", element=None): try: if locator: element=self.getElement(locator, locatorType) element.click() self.log.info('Element found and clicked with locator: '+ locator+ ' and locatorType '+locatorType) except: self.log.error('Element could not be clicked with locator: '+ locator+ ' and locatorType '+locatorType) def sendKeys(self,data,locator="",locatorType="id", element=None): try: if locator: element=self.getElement(locator, locatorType) element.clear() element.send_keys(data) self.log.info('Data sent to element with locator '+locator+" and locatortype "+locatorType) except: self.log.error('Data could not be sent to element with locator '+locator+" and locatortype "+locatorType) def sendKeysWhenReady(self, data, locatorType="id",locator="" ): try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(10) + " :: seconds for element to be visible") wait = WebDriverWait(self.driver, timeout=10, poll_frequency=1, ignored_exceptions=[NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException]) element = wait.until(EC.visibility_of_element_located((byType, locator))) self.log.info("Element appeared on the web page") element.click() element.send_keys(data) if element.get_attribute("value") != data: self.log.debug("Text is not sent by xpath in field so try to send string char by char!") element.clear() for i in range(len(data)): element.send_keys(data[i] + "") self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Element not appeared on the web page") self.log.error("Exception Caught: {}".format(traceback.format_exc())) self.log.error("".join(traceback.format_stack())) def isElementPresent(self, locator, locatorType="id"): try: 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.error("Element not present with locator: " + locator + " locatorType: " + locatorType) return False except: self.log.error("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 present with locator: " + locator + " locatorType: " + str(byType)) return True else: self.log.error("Element not present with locator: " + locator + " locatorType: " + str(byType)) return False except: self.log.error("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, StaleElementReferenceException]) 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 getText(self,locator="",locatorType="id",element="", info=""): try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) text = element.text else: text = element.text if len(text) == 0: text = element.get_attribute("innerText") if len(text) != 0: self.log.info("Getting text on element :: " + info) self.log.info("The text is :: '" + text + "'") text = text.strip() except: self.log.error("Failed to get text on element " + info) print_stack() text = None return text def webScroll(self,direction="up"): if direction=="up": self.driver.execute_script("window.scrollBy(0,-1000);") time.sleep(3) elif direction=="down": self.driver.execute_script("window.scrollTo(0,250);") time.sleep(3)
class CategoriesPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _categories_dropdown = "//div[@id='navbarNavDropdown']/div/ul[2]/li[3]/a" _category = "//section[@id='loadTopCategory']//aside" _category_breadcrumb = "//div[contains(@class,'pageheading')]//a[@id='clickCategory']" _category_tiles = "//div[@id='loadCategoryGroup']//div[contains(@class,'carousel-inner')]" _category_tile_link = "(//a[contains(@sectionofpage,'{0}')])[1]" def navigateToHome(self): self.elementClick(locator=self._ampro_logo, locatorType="xpath") def navigateToCategoryViaTopMenu(self): self.elementClick(locator=self._categories_dropdown, locatorType="xpath") time.sleep(2) links = [] #import pdb;pdb.set_trace() links = self.driver.find_elements_by_xpath(self._category) link_selected = links[randint(0, len(links) - 1)] config.text_on_dropdown_item = self.getText(element=link_selected) link_selected.click() time.sleep(2) def navigateToCategoryViaHomepg(self): elements = [] try: elements = self.driver.find_elements_by_xpath(self._category_tiles) config.cat_hovered = elements[randint(0, len(elements) - 1)] config.text_cat_hovered = self.getText(element=config.cat_hovered) self.driver.execute_script( "arguments[0].scrollIntoView({block: 'center', inline: 'center'});", config.cat_hovered) time.sleep(4) action = ActionChains(self.driver) action.move_to_element(config.cat_hovered).perform() self.log.info( "Hovered to element [%s] on location [%s] with size [%s]", config.cat_hovered, config.cat_hovered.location, config.cat_hovered.size) time.sleep(2) report_link = self._category_tile_link.format( config.text_cat_hovered) config.target = self.driver.find_element_by_xpath(report_link) time.sleep(2) self.driver.execute_script("arguments[0].click();", config.target) #action.move_to_element(config.target).click().perform() time.sleep(4) except Exception as e: self.log.error("Could not click on hovered tile link [%s]", e) self.log.error("Exception Caught: {}".format( traceback.format_exc())) self.log.error("".join(traceback.format_stack())) def verifyNavigationToCategoryViaTopMenu(self): config.text_on_breadcrumb = self.getText( locator=self._category_breadcrumb, locatorType="xpath") if config.text_on_dropdown_item == config.text_on_breadcrumb: return True else: return False def verifyNavigationToCategoryViaHomepg(self): config.textafterclick = self.getText(locator=self._category_breadcrumb, locatorType="xpath") #import pdb;pdb.set_trace() if config.text_cat_hovered == config.textafterclick: return True else: return False
class SolutionsPage(SeleniumDriver): allHandles = None log = cl.customLogger(logging.DEBUG) def __init__(self,driver): super().__init__(driver) self.driver=driver #Locators _solutions="//div[@id='navbarNavDropdown']/div/ul[2]/li[6]/a" _my_solutions="//div[@id='navbarNavDropdown']/div/ul[2]/li[6]/div/ul[1]" #_my_solutions="(//a[contains(text(),'My solutions')])[1]" _first_item_my_solutions="(//ul[contains(@class,'navbar-nav mt-3')]//li[6]//div//div/a)[1]" _my_request="//div[@id='navbarNavDropdown']/div/ul[2]/li[6]/div/ul[2]" _attribute="//input[@id='timeInSeconds']" _my_deliverables="//div[@id='navbarNavDropdown']/div/ul[2]/li[6]/div/ul[3]" _more_offerings="//div[@id='navbarNavDropdown']/div/ul[2]/li[6]/div/ul[4]" def navigateToSolutions(self): self.elementClick(self._solutions,locatorType="xpath") self.log.info("Clicked on Solutions top menu") def navigateToMysolutions(self): global allHandles action = ActionChains(self.driver) parentHandle = self.driver.current_window_handle self.log.info("Parent handle for the current page identified [%s]",parentHandle) first_link = self.getElement(self._my_solutions,locatorType="xpath") action.move_to_element(first_link).click().perform() self.log.info("Clicked on My solutions under Solutions top menu") time.sleep(2) second_link = self.getElement(self._first_item_my_solutions,locatorType="xpath") action.move_to_element(second_link).click().perform() time.sleep(2) self.log.info("Clicked on first link under My solutions") allHandles = self.driver.window_handles self.log.info("There are now 2 windows with different handles [%s]",len(allHandles)) for handle in allHandles: self.log.info("At Handle [%s]", handle) if handle not in parentHandle: self.driver.switch_to.window(handle) time.sleep(2) self.driver.close() break self.driver.switch_to.window(parentHandle) def verifyNavigationToSolutions(self): if len(allHandles) == 2: return True else: return False def navigateToMyrequest(self): global allHandles action = ActionChains(self.driver) parentHandle = self.driver.current_window_handle self.log.info("Parent handle for the current page identified [%s]",parentHandle) first_link = self.getElement(self._my_request,locatorType="xpath") action.move_to_element(first_link).click().perform() time.sleep(2) self.log.info("Clicked on My request under Solutions") allHandles = self.driver.window_handles self.log.info("There are now 2 windows with different handles [%s]",len(allHandles)) for handle in allHandles: self.log.info("At Handle [%s]", handle) if handle not in parentHandle: self.driver.switch_to.window(handle) time.sleep(2) self.driver.close() break self.driver.switch_to.window(parentHandle) def verifyNavigationToMyrequest(self): if len(allHandles) == 2: return True else: return False def navigateToMydeliverables(self): global allHandles action = ActionChains(self.driver) parentHandle = self.driver.current_window_handle self.log.info("Parent handle for the current page identified [%s]",parentHandle) first_link = self.getElement(self._my_deliverables,locatorType="xpath") action.move_to_element(first_link).click().perform() time.sleep(2) self.log.info("Clicked on My request under Solutions") allHandles = self.driver.window_handles self.log.info("There are now 2 windows with different handles [%s]",len(allHandles)) for handle in allHandles: self.log.info("At Handle [%s]", handle) if handle not in parentHandle: self.driver.switch_to.window(handle) time.sleep(2) self.driver.close() break self.driver.switch_to.window(parentHandle) def verifyNavigationToMydeliverables(self): if len(allHandles) == 2: return True else: return False
class ToolsnTemplatesPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _ampro_logo = "(//nav[@id='tsc_nav_1']/a/img)[1]" _tools_n_templates = "//div[@id='navbarNavDropdown']/div/ul[2]/li[2]/a" _tools_templates_breadcrumb = "//div[@class='row']/div/ol//li[contains(@class,'breadcrumb-item active')]" _share_icon = "//i[@id='shareTools']" _email = "shareEmail" _comment = "shareComment" _share_button = "btnShareTools" _share_success_msg = "errorMsgShare" _strategy_tool = "//a[contains(text(),'Strategy tool')]" _create_strategy_modal_title = "(//div[contains(@class,'modal-header')]/h5)[2]" _modal_dropdown = "//span[@id='select2-_Report-container']" _close_button = "//div[@id='shareToolsPopUp']//div/button/span" def navigateToHome(self): self.elementClick(locator=self._ampro_logo, locatorType="xpath") def navigateToToolsnTemplates(self): self.elementClick(locator=self._tools_n_templates, locatorType="xpath") time.sleep(2) def strategyTool(self): self.elementClick(self._strategy_tool, locatorType="xpath") time.sleep(3) #this method randomly clicks on the available share icons on page def fileSharing(self, Email, Comment): self.driver.refresh() time.sleep(2) self.driver.find_element_by_tag_name('body').send_keys(Keys.END) time.sleep(2) links = [] #import pdb;pdb.set_trace() links = self.driver.find_elements_by_xpath(self._share_icon) l = links[randint(0, len(links) - 1)] l.click() time.sleep(2) self.sendKeys(Email, self._email) time.sleep(2) self.sendKeys(Comment, self._comment) time.sleep(2) self.elementClick(self._share_button) def verifyNavigationToToolsnTemplates(self): result = self.isElementPresent(self._tools_templates_breadcrumb, locatorType="xpath") return result def verifyStrategyCreation(self): self.driver.switch_to.frame(0) time.sleep(2) result = self.isElementPresent(self._modal_dropdown, locatorType="xpath") return result self.driver.switch_to.default_content() def verifyFileSharing(self): result = self.isElementPresent(self._share_success_msg) self.elementClick(self._close_button, locatorType="xpath") time.sleep(1) self.driver.find_element_by_tag_name('body').send_keys(Keys.HOME) time.sleep(2) return result
class ResourcesPage(SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _resources = "//div[@id='navbarNavDropdown']/div/ul[2]/li[5]/a" _blogs = "(//a[contains(text(),'Blogs')])[1]" _breadcrumb = "//div[contains(@class,'pageheading')]//ol//li[3]" _attribute = "//input[@id='timeInSeconds']" _case_studies = "(//a[contains(text(),'Case studies')])[1]" _podcasts_n_videos = "(//a[contains(text(),'Podcasts and videos')])[1]" _spend_matters_insights = "(//a[contains(text(),'Spend matters insights')])[1]" _thought_leadership = "(//a[contains(text(),'Thought leadership')])[1]" _CASME_resource_centre = "(//a[contains(text(),'CASME resource centre')])[1]" _CASME_logo = "//a[contains(@class,'logo pull-left site-logo')]/img" def navigateToResources(self): self.elementClick(self._resources, locatorType="xpath") self.log.info("Clicked on Resources top menu") def navigateToBlogs(self): action = ActionChains(self.driver) first_link = self.getElement(self._blogs, locatorType="xpath") action.move_to_element(first_link).click().perform() self.log.info("Clicked on Blogs under All Intelligence top menu") time.sleep(3) def verifyNavigationToBlogs(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") attribute = self.getElement(self._attribute, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Blogs [%s]", breadcrumb) attribute_value = attribute.get_attribute("pagename") self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Blogs" and attribute_value == "Resources- Blogs": return True else: return False def navigateToCaseStudies(self): action = ActionChains(self.driver) second_link = self.getElement(self._case_studies, locatorType="xpath") action.move_to_element(second_link).click().perform() self.log.info( "Clicked on Case studies under All Intelligence top menu") time.sleep(3) def verifyNavigationToCaseStudies(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") attribute = self.getElement(self._attribute, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Case studies [%s]", breadcrumb) attribute_value = attribute.get_attribute("pagename") #import pdb;pdb.set_trace() self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Case studies" and attribute_value == "Resources- Case studies": return True else: return False def navigateToPodcastsnVideos(self): action = ActionChains(self.driver) third_link = self.getElement(self._podcasts_n_videos, locatorType="xpath") action.move_to_element(third_link).click().perform() self.log.info( "Clicked on Podcasts and videos under All Intelligence top menu") time.sleep(3) def verifyNavigationToPodcastsnVideos(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") attribute = self.getElement(self._attribute, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Podcasts and videos [%s]", breadcrumb) attribute_value = attribute.get_attribute("pagename") #import pdb;pdb.set_trace() self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Podcasts and videos" and attribute_value == "Resources- Podcasts and videos": return True else: return False def navigateToSpendMattersInsights(self): action = ActionChains(self.driver) fourth_link = self.getElement(self._spend_matters_insights, locatorType="xpath") action.move_to_element(fourth_link).click().perform() self.log.info( "Clicked on Spend Matters Insights under All Intelligence top menu" ) time.sleep(3) def verifyNavigationToSpendMattersInsights(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") attribute = self.getElement(self._attribute, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Spend matters insights [%s]", breadcrumb) attribute_value = attribute.get_attribute("pagename") #import pdb;pdb.set_trace() self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Spend matters insights" and attribute_value == "Resources- Spend matters insights": return True else: return False def navigateToThoughtLeadership(self): action = ActionChains(self.driver) fifth_link = self.getElement(self._thought_leadership, locatorType="xpath") action.move_to_element(fifth_link).click().perform() self.log.info( "Clicked on Thought leadership under All Intelligence top menu") time.sleep(3) def verifyNavigationToThoughtLeadership(self): breadcrumb = self.getElement(self._breadcrumb, locatorType="xpath") attribute = self.getElement(self._attribute, locatorType="xpath") text = self.getText(element=breadcrumb) self.log.info("Redirected to Thought leadership [%s]", breadcrumb) attribute_value = attribute.get_attribute("pagename") #import pdb;pdb.set_trace() self.log.info("Attribute value for pagename on breadcrumb [%s]", attribute_value) if text == "Thought leadership" and attribute_value == "Resources- Thought leadership": return True else: return False def navigateToCASMEResourceCentre(self): action = ActionChains(self.driver) sixth_link = self.getElement(self._CASME_resource_centre, locatorType="xpath") parentHandle = self.driver.current_window_handle self.log.info("Parent Handle identified [%s]", parentHandle) action.move_to_element(sixth_link).click().perform() self.log.info( "Clicked on CASME resource centre under All Intelligence top menu") time.sleep(3) #Finding all handles handles = self.driver.window_handles for handle in handles: if handle not in parentHandle: self.driver.switch_to.window(handle) time.sleep(2) break def verifyNavigationToCASMEResourceCentre(self): result = self.isElementPresent(self._CASME_logo, locatorType="xpath") if result == True: return result else: return False