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 LoginTest(unittest.TestCase): log = cl.customLogger(logging.INFO) @pytest.fixture(autouse=True) def classSetup(self, oneTimeDriverSetup): self.lp = LoginPage(self.driver) self.ts = TestStatus(self.driver) @pytest.mark.regression @pytest.mark.sanity @pytest.mark.run(order=2) def test_web_validLogin(self): self.lp.login("*****@*****.**", "abcabc") result2 = self.lp.verifyLoginTitle() self.ts.mark(result2, "Title is incorrect") result1 = self.lp.verifyLoginSuccessful() self.ts.markFinal("test_validLogin", result1, "Login was not successful") @pytest.mark.regression @pytest.mark.sanity @pytest.mark.run(order=1) def test_web_invliadLogin(self): time.sleep(4) self.lp.login("*****@*****.**", "abcabc") self.lp.logout() self.lp.login("*****@*****.**", "123") result = self.lp.verifyInvalidLogin() self.ts.markFinal("test_invalid_Login", result, "Invalid Login Test Failed")
class AccountPage(SeleniumDriver, LocatorsAccountSettings): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def open_account_settings(self): self.elementClick(LocatorsAccountSettings.user_button_id) self.elementClick(LocatorsAccountSettings.account_settings_css, locatorType='css') # self.waitForElement(LocatorsAccountSettings.check_account_email_id) def verify_account_settings(self): # Verifying we are on the right page by finding change password button: verify = self.isElementPresent(LocatorsAccountSettings.change_account_pass_id) return verify def clear_settings(self): self.elementClick(LocatorsAccountSettings.clear_chart_css, locatorType='css') self.elementClick(LocatorsAccountSettings.clear_custom_css, locatorType='css') self.elementClick(LocatorsAccountSettings.clear_button_id) time.sleep(1) def yes_on_popup(self): self.elementClick(LocatorsAccountSettings.clear_custom_yes_xpath, locatorType='xpath') self.waitForElement(LocatorsAccountSettings.markets_button_text, locatorType='link')
class NavigationPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _my_courses = ("My Courses","link") _all_courses = ("ALL COURSES","link") _practice = ("Practice","link") _user_settings_icon = "dropdownMenu1" def navigateToAllCourses(self): self.elementClick(*self._all_courses) def navigateToMyCourses(self): self.elementClick(*self._my_courses) def navigateToPractice(self): self.elementClick(*self._practice) def navigateToUserSettings(self): self.elementClick(self._user_settings_icon)
class ApiHelper(): log = cl.customLogger(logging.DEBUG) def get(self, uri, params=None, header=None): try: if not header: header = {"Content-Type": "application/json"} res = requests.get(url=uri, params=params, headers=header) if (res.status_code == 200): self.log.info("the requested url " + uri + "with params " + str(params) + " is successful ") return res else: self.log.info( "the requested url is not successful please check the url and params " + uri + " " + str(params)) except: self.log.error("unable to perform get call for url " + uri + " params " + str(params)) def post(self, uri, params=None, header=None): try: if not header: header = {"Content-Type": "application/json"} res = requests.get(url=uri, json=params, headers=header) if (res.status_code == 200): self.log.info("the requested url is not successful") return res else: self.log.info( "the requested url is not successful please check the url and params " + uri + " " + params) except: self.log.error("unable to perform get call for url " + uri + " params " + params)
class WebDriverFactory(): log = cl.customLogger(logging.INFO) def __init__(self, browser): self.browser = browser def getWebDriverInstance(self): baseUrl = "https://courses.letskodeit.com/" if self.browser == "iexplorer": driver = webdriver.Ie() elif self.browser == "firefox": driver = webdriver.Firefox() elif self.browser == "chrome": options = Options() options.add_argument("--disable-notifications") #chrome_path = "/Users/mohammedwaasim/Documents/workspace_python/drivers/chromedriver" driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) elif self.browser == "headless": options = Options() options.headless = True options.add_argument("--disable-notifications") driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options) else: self.log.error("no such driver found driver not initiated") driver.implicitly_wait(5) driver.maximize_window() #driver.get(baseUrl), commented bcoz there is another testcase addded for different website return driver
class MarketsPage(MarketsLocators, SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def click_markets(self): # Click on markets button in the navbar: self.elementClick(MarketsLocators.markets_css, locatorType='css') self.waitForElement(MarketsLocators.market_performance_arrows_xpath, locatorType='xpath') def verify_markets_performance(self): # Verify markets verify_markets = self.isElementPresent( MarketsLocators.market_performance_columnpicker_id) return verify_markets def click_markets_quick_performance(self): self.elementClick(MarketsLocators.market_quick_performance_css, locatorType='css') self.waitForElement(MarketsLocators.market_quick_performance_group_id) def verify_markets_quick_performance(self): verify_quick_performance = self.isElementPresent( MarketsLocators.market_quick_performance_next_id) return verify_quick_performance def click_markets_overview(self): self.elementClick(MarketsLocators.market_overview_css, locatorType='css') self.waitForElement(MarketsLocators.market_overivew_arrows_xpath, locatorType='xpath') def verify_markets_overview(self): verify_overview = self.isElementPresent( MarketsLocators.market_overview_picker_id) return verify_overview def click_markets_charts(self): self.elementClick(MarketsLocators.market_chart_css, locatorType='css') self.waitForElement(MarketsLocators.market_chart_reload_css, locatorType='css') def verify_markets_chart(self): verify_charts = self.isElementPresent( MarketsLocators.market_chart_picker_id) return verify_charts def click_quoteboard(self): self.elementClick(MarketsLocators.market_quoteboard_css, locatorType='css') self.waitForElement(MarketsLocators.market_quoteboard_group_id) def verify_quoteboard(self): verify_quoteboard = self.isElementPresent( MarketsLocators.market_quoteboard_picker_id) return verify_quoteboard
class NdtvHomePageMap(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def world_tab(self) -> WebElement: return self.getElement("//div[@class='topnav_cont']/a[text()='WORLD']", "xpath")
class LoginPage(SeleniumDriver, LocatorsLP): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def enterUsername(self, username): self.clearElement(LocatorsLP.username_id) self.sendKeys(username, LocatorsLP.username_id) def enterPassword(self, password): self.clearElement(LocatorsLP.password_id) self.sendKeys(password, LocatorsLP.password_id) def clickEula(self): self.elementClick(LocatorsLP.eula_css_check, locatorType='css') def clickLogin(self): self.elementClick(LocatorsLP.login_btn_id) def verifyInvalidLogin(self): result = self.isElementPresent(LocatorsLP.eula_warning_id) return result def verifyValidLogin(self): result = self.isElementPresent(LocatorsLP.user_button_id) return result def login_eula_check(self, username, password): """ Method for login tests (both valid and invalid) when eula is checked. """ self.enterUsername(username) self.enterPassword(password) if self.checkAttribute('eulaAccepted') != 'true': self.clickEula() self.clickLogin() def login_no_eula(self, username, password): """ Method for login tests when eula is NOT checked. """ self.enterUsername(username) self.enterPassword(password) if self.checkAttribute('eulaAccepted') == 'true': self.clickEula() self.clickLogin() def logout(self): """ Performs logout. """ self.elementClick(LocatorsLP.user_button_id) self.elementClick(LocatorsLP.logout_css, locatorType='css')
class NdtvHomePage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.map = NdtvHomePageMap(driver) self.driver = driver def click_world_tab(self): self.elementClick(element=self.map.world_tab()) print("in click world tab")
class RegisterCoursePageMap(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def search_box(self) -> WebElement: return self.getElement("course", "name") def course(self, courseName) -> WebElement: return self.getElement( f"//div[contains(@class,'course-title')]//h4[contains(text(),'{courseName}')]", "xpath") def all_courses(self): return self.getElement("course-listing-title", "xpath") def enroll_button(self): return self.getElement("//button[text()='Enroll in Course']", "xpath") def cc_num(self): return self.getElement("cardnumber", "name") def cc_exp(self): return self.getElement("exp-date", "name") def cc_cvv(self): return self.getElement("cvc", "name") def submit_enroll(self): return self.getElement("(//button[contains(@class,'btn-submit')])[2]", "xpath") def enroll_error_message(self): return self.getElement( "//div[@class='card-errors has-error']/ul/li/span", "xpath") def card_number_frame(self): return self.getElement( "//iframe[@title='Secure card number input frame']", "xpath") def expiry_date_frame(self): return self.getElement( "//iframe[@title='Secure expiration date input frame']", "xpath") def security_code_frame(self): return self.getElement("//iframe[@title='Secure CVC input frame']", "xpath")
class WorldNewsPage(BasePage): log = cl.customLogger(logging.INFO) def __init__(self, driver): super().__init__(driver) self.driver = driver self.map = WorldNewsPageMap(driver) def click_section_menu(self): self.map.webScroll("down") self.map.section_menu().click() def click_weather(self): self.elementClick(element=self.map.weather_option())
class NdtvWeather(unittest.TestCase): log = cl.customLogger(logging.INFO) @pytest.fixture(autouse=True) def classSetup(self, oneTimeDriverSetup): print("get object of page classes") self.ndtv_web_data = getYamlData(self.ndtv_test_file, 'ndtv_web') self.open_api_data = getYamlData(self.ndtv_test_file, 'open_api') self.ndtv_home_page = NdtvHomePage(self.driver) self.ndtv_world_page = WorldNewsPage(self.driver) self.weather_report_page = WeatherReportPage(self.driver) self.api = ApiHelper() self.temp_comp = TempretureComparetor( self.open_api_data['acceptableVariance']) @pytest.mark.regression @pytest.mark.run(order=1) def test_web_navigate_ndtv(self): print("write test1") self.driver.get(self.ndtv_web_data['url']) print(self.driver.title) assert self.ndtv_web_data['title'] == self.ndtv_home_page.getTitle() @pytest.mark.regression @pytest.mark.run(order=2) def test_web_validate_temp(self): print("write test2 here") self.driver.get(self.ndtv_web_data['url']) print(self.driver.title) self.ndtv_home_page.click_world_tab() self.ndtv_world_page.wait_for_page_to_load() self.ndtv_world_page.click_section_menu() self.ndtv_world_page.click_weather() self.ndtv_city_temp = self.weather_report_page.get_temp_for_given_city( self.ndtv_web_data['city']) print(self.ndtv_city_temp) params = {} params.__setitem__("q", self.open_api_data['city']) params.__setitem__("appid", self.appid) url = self.open_api_data['base_uri'] + self.open_api_data['endpoint'] resp = self.api.get(url, params=params) resp = resp.json() kelvin_temp = resp['main']['temp'] self.api_temp_c = float( kelvin_temp) - self.open_api_data['kelvin_diff'] weather_ui = Weather(self.ndtv_city_temp) weather_api = Weather(self.api_temp_c) self.temp_comp.compare_temprature(weather_ui, weather_api)
class testunittest(unittest.TestCase): log = cl.customLogger(logging.DEBUG) @classmethod def setUpClass(cls): cls.config = cc.createConfigfromYaml(config_file) cls.log.info("Executing Setup Class") driverKeys = cls.config['driver'].keys() if 'chrome' in driverKeys: cls.driverLocation = cls.config['driver']['chrome'] else: raise ("Invalid driver error")
class WorldNewsPageMap(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def weather_option(self) -> WebElement: self.waitForElement("//div[@id='topnav']/ul/li[@class='n_weather']/a", "xpath", 10, .75) return self.getElement("//div[@id='topnav']//li[@class='n_weather']/a", "xpath") def section_menu(self) -> WebElement: self.waitForElement("topnav_section", "id") return self.getElement("topnav_section")
class TempretureComparetor(): log = cl.customLogger(logging.INFO) def __init__(self, variance: int): self.variance = variance def compare(self, w1: Weather, w2: Weather): return abs(w1.temp_c - w2.temp_c) def compare_temprature(self, w1: Weather, w2: Weather): self.log.info( f"performing comparision of temperature between {w1.temp_c} and {w2.temp_c} with the referance temp of {self.variance}" ) if (self.compare(w1, w2) <= self.variance): return True else: raise CustomException( f"WTF temperature reported by NDTV is {w1.temp_c} and openweatherapi is {w2.temp_c} and it is too huge Shouldn't NDTV be sued for false Weather Reporting!" )
class TestStatus(BasePage): log = cl.customLogger(logging.INFO) def __init__(self, driver): super(TestStatus, self).__init__(driver) self.resultlist = [] def setResult(self, result, resultMessage): try: if result is not None: if result: self.resultlist.append("PASS") self.log.info("###Verification Successful") else: self.resultlist.append("FAIL") self.log.info("###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) def mark(self, result, resultMessage): self.setResult(result, resultMessage) def markFinal(self, testName, result, resultMessage): self.setResult(result, resultMessage) if "FAIL" in self.resultlist: self.log.error("###### TEST FAILED") self.resultlist.clear() assert True == False else: self.log.info(testName + "###### TEST PASSED") self.resultlist.clear() assert True == True
class LoginPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver self.nav = NavigationPage(driver) #locators # _login_link="//a[contains(text(),'Sign In')]" # _email_filed="email" # _pwd_filed="password" # _loign_button="//input[@type='submit']" _login_link = ("//a[contains(text(),'Sign In')]", "xpath") _email_filed = ("email", "id") _pwd_filed = ("password", "id") _loign_button = ("//input[@type='submit']", "xpath") def clickLoginLink(self): self.log.debug("clicking on login link") self.elementClick(*self._login_link) self.log.debug("clicked on login link successfully") def enterEmail(self, email): self.log.debug("entering email id") self.sendKeys(email, *self._email_filed) self.log.debug("email entered successfully") def enterPwd(self, pwd): self.log.debug("entering password") self.sendKeys(pwd, *self._pwd_filed) self.log.debug("password entered successfully") def clickLoginButton(self): self.log.debug("clicking on on login button") self.elementClick(*self._loign_button) self.log.debug("clicked on login button successfully") def login(self, username="", pwd=""): self.log.debug("performing login actions") self.driver.get("https://courses.letskodeit.com/") self.clickLoginLink() time.sleep(3) self.enterEmail(username) self.enterPwd(pwd) self.clickLoginButton() self.log.debug("login action completed successfully") def verifyLoginSuccessful(self): result = self.isElementPresent("//h1[text()='All Courses']", locatorType="xpath") return result def verifyInvalidLogin(self): result = self.isElementPresent("//span[contains(text(),'invalid')]", locatorType="xpath") return result def verifyLoginTitle(self): return self.verifyPageTitle("All Courses") def logout(self): self.nav.navigateToUserSettings() self.elementClick( locator= "//div[contains(@class,'navbar-buttons')]//a[@href='/logout']", locatorType="xpath")
class BasePage(): log = cl.customLogger(logging.INFO) def __init__(self, driver): self.driver = driver self.util = Util() def screenShot(self, resultMessage): fileName = resultMessage + "." + str(round( time.time() * 1000)) + ".png" screenShotDir = "../screenshots/" relativeFileName = screenShotDir + fileName currentDir = os.path.dirname(__file__) destinationFile = os.path.join(currentDir, relativeFileName) destinationDir = os.path.join(currentDir, screenShotDir) try: if not os.path.exists(destinationDir): os.makedirs(destinationDir) self.driver.save_screenshot(destinationFile) allure.attach.file(destinationFile) self.log.info("Screenshot save to directory" + destinationDir) except: self.log.error("#### Exception Occurred") 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 == "classname": return By.CLASS_NAME elif locatorType == "linktext": 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 + " with locator type " + locatorType) except: self.log.info("Element not found with locator " + locator + " with locator type " + locatorType) x = 10 return element def getElement_ele(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 + " with locator type " + locatorType) except: self.log.info("Element not found with locator " + locator + " with locator type " + locatorType) x = 10 return element def getElementList(self, locator, locatorType="id"): elements = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) elements = self.driver.find_elements(byType, locator) self.log.info("Element list found wiht locator" + locator + " and locator type " + locatorType) except: self.log.info("Element list NOT found wiht locator" + locator + " and locator type " + locatorType) return elements def elementClick(self, locator="", locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) 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) 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) text = None return text def isElementPresent(self, locator="", locatorType="id", element=None): try: if locator: element = self.getElement(locator, locatorType) if element is not None: self.log.info("Element Found with locator") return True else: self.log.info("Element not found") 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 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=None, locatorType="id", timeout=10, pollFrequency=0.5, element=None): delayed_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=pollFrequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) if (element): delayed_element = wait.until(EC.visibility_of(element)) else: delayed_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 delayed_element def webScroll(self, direction="up"): if (direction == "up"): self.driver.execute_script("window.scrollBy(0,-1000);") self.log.info("scrolling page up") else: self.driver.execute_script("window.scrollBy(0,800);") self.log.info("scrolling page down") def isEnabled(self, locator, locatorType="id", info=""): """ Check if element is enabled Parameters: 1. Required: 1. locator - Locator of the element to check 2. Optional: 1. locatorType - Type of the locator(id(default), xpath, css, className, linkText) 2. info - Information about the element, label/name of the element Returns: boolean Exception: None """ element = self.getElement(locator, locatorType=locatorType) enabled = False try: attributeValue = self.getElementAttributeValue( element=element, attribute="disabled") if attributeValue is not None: enabled = element.is_enabled() else: value = self.getElementAttributeValue(element=element, attribute="class") self.log.info( "Attribute value From Application Web UI --> :: " + value) enabled = not ("disabled" in value) if enabled: self.log.info("Element :: '" + info + "' is enabled") else: self.log.info("Element :: '" + info + "' is not enabled") except: self.log.error("Element :: '" + info + "' state could not be found") return enabled def getElementAttributeValue(self, attribute, element=None, locator="", locatorType="id"): """ Get value of the attribute of element Parameters: 1. Required: 1. attribute - attribute whose value to find 2. Optional: 1. element - Element whose attribute need to find 2. locator - Locator of the element 3. locatorType - Locator Type to find the element Returns: Value of the attribute Exception: None """ if locator: element = self.getElement(locator=locator, locatorType=locatorType) value = element.get_attribute(attribute) return value def switchToFrame(self, id="", name="", index=None, element=None): """ Switch to iframe using element locator inside iframe Parameters: 1. Required: None 2. Optional: 1. id - id of the iframe 2. name - name of the iframe 3. index - index of the iframe Returns: None Exception: None """ try: if id: self.driver.switch_to.frame(id) elif name: self.driver.switch_to.frame(name) elif index: self.driver.switch_to.frame(index) else: self.driver.switch_to.frame(element) except: self.log.error("no such frame with given details") def switchToDefaultContent(self): """ Switch to default content Parameters: None Returns: None Exception: None """ self.driver.switch_to.default_content() def verifyPageTitle(self, titleToVerify): try: return self.util.verifyTextContains(self.getTitle(), titleToVerify) except: self.log.error("Failed to assert title") return False def wait_for_page_to_load(self): WebDriverWait(self.driver, 120).until(lambda driver: driver.execute_script( 'return document.readyState') == 'complete')
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def screenShot(self): # step by step Automation - lesson 52 current_time = moment.now().strftime('%d-%m-%Y__%H-%M-%S') test_name = inspect.stack()[1][3] screenshot_name = test_name + '_ ' + current_time self.driver.save_screenshot( 'C:/MJ/MJ/PROJECTS/AutomationWebstation/reports/screenshots/' + screenshot_name + '.png') 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"): ''' just clicks on the element :param locator: :param locatorType: :return: ''' 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"): ''' just sends data to elements! :param locator: :param locatorType: :return: ''' 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 clearElement(self, locator, locatorType="id"): ''' clear fields of any inputs. ''' try: element = self.getElement(locator, locatorType) element.clear() self.log.info("Cleared the element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot clear the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def checkAttribute(self, locator, locatorType="id"): ''' Used for checkboxes to check their status (checked/not checked). ''' # element = None # try: element = self.getElement(locator, locatorType).get_attribute('checked') # print("Status of element with locator: " + locator + " locatorType: " + locatorType + 'is' + element) # except: # print("Cannot confirm the status of the element with locator: " + locator + " locatorType: " + locatorType) # print_stack() return element 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: self.log.info("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 - locator: " + locator) print_stack() return element
class SeleniumDriver(): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): # type: (object) -> object 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 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.debug("Element found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.debug("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def getElementList(self, locator, locatorType="id"): element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_elements(byType, locator) self.log.debug("Element list found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.debug("Element list not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator="", locatorType="id", element=None): try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.click() self.log.debug("Clicked on element: {}".format(element)) except: self.log.info("Cannot click on the element ") 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.debug("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.error("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def getText(self, locator="", locatorType="id", element=None, info=""): 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 isElementPresent(self, locator="", locatorType="id", element=None): 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): isDisplayed = False try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) self.log.info(element) if element is not None: isDisplayed = element.is_displayed() self.log.info("Element is displayed :" + str(isDisplayed) + " with locator: " + locator + " locatorType: " + locatorType) else: self.log.info("Element is displayed :" + str(isDisplayed) + " with locator: " + locator + " locatorType: " + locatorType) return isDisplayed except: print("Element not found") return False def elementPresenceCheck(self, locator, byType): try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element 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 waitForElementvisible(self, locator, locatorType="id", timeout=10, pollFrequency=0.5): self.log.info("Estamos dentro del waitforElementVisible") element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timeout) + "seconds for element with Locator : " + locator + " and locator type: " + byType + " is visible") wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=pollFrequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) # element = wait.until(EC.visibility_of_element_located(By.XPATH(locator))) element = wait.until( EC.visibility_of_element_located((byType, locator))) self.log.info("Element is visible on the web page") except: self.log.info("Element not displayed on the web page") print_stack() return element def webScroll(self, direction="up"): if direction == "up": # Scroll Up self.driver.execute_script("window.scrollBy(0, -1000);") if direction == "down": # Scroll Down self.driver.execute_script("window.scrollBy(0, 1000);")
class DaxDetailPage(SeleniumDriver, LocatorsDax, LocatorsAdidas): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): # main advantage of super is with multiple inheritance where troubles may happen. # super allows: to avoid using the base class name explicitly; Working with Multiple Inheritance super().__init__(driver) self.driver = driver global ldw ldw = LocatorsDaxWaits global lda lda = LocatorsDaxAsserts def click_dax(self): self.elementClick(LocatorsDax.dax_symbol_id) self.waitForElement(ldw.overview_chart_1d_id) dax_element = self.isElementPresent(lda.overview_minichart_id) assert dax_element == True def open_new_window(self): self.elementClick(LocatorsDax.action_menu_id) self.elementClick(LocatorsDax.open_newwindow_css, locatorType='css') # Find parent handle -> Main Window parent_handle = self.driver.current_window_handle # Find all handles, there should two handles handles = self.driver.window_handles # Switch to new window: for handle in handles: if handle not in parent_handle: self.driver.switch_to.window(handle) self.driver.maximize_window() def click_constituents(self): self.elementClick(LocatorsDax.constituents_css, locatorType='css') self.waitForElement(ldw.constituents_columnpicker_id) const_element = self.isElementPresent(lda.constituents_quoteboard_css, locatorType='css') assert const_element == True def click_overview(self): self.elementClick(LocatorsDax.overview_css, locatorType='css') self.waitForElement(ldw.overview_chart_1d_id) overview_element = self.isElementPresent(lda.overview_minichart_id) assert overview_element == True def click_chart(self): self.elementClick(LocatorsDax.chart_css, locatorType='css') self.waitForElement(ldw.chart_setdefault_id) chart_element = self.isElementPresent(lda.chart_savetemplate_id) assert chart_element == True def click_topflop(self): self.elementClick(LocatorsDax.topflop_css, locatorType='css') self.waitForElement(ldw.topflop_reload_css, locatorType='css') topflop_element = self.isElementPresent(lda.topflop_clos_css, locatorType='css') assert topflop_element == True def click_timessales(self): self.elementClick(LocatorsDax.timessales_css, locatorType='css') self.waitForElement(ldw.timesales_startdate_id) timesales_element = self.isElementPresent(lda.timesales_starthour_id) assert timesales_element == True def click_news(self): self.elementClick(LocatorsDax.news_css, locatorType='css') self.waitForElement(ldw.news_size_id) news_element = self.isElementPresent(lda.news_ecdata_css, locatorType='css') assert news_element == True def click_options(self): self.elementClick(LocatorsDax.options_css, locatorType='css') self.waitForElement(ldw.options_reset_id) options_element = self.isElementPresent(lda.options_search_id) assert options_element == True def click_derivatives(self): self.elementClick(LocatorsDax.derivatives_css, locatorType='css') self.waitForElement(ldw.derivatives_columnpicker_id) derivatives_element = self.isElementPresent( lda.derivatives_actionmenu_id) assert derivatives_element == True def click_adidas(self): self.click_constituents() self.elementClick(LocatorsAdidas.adidas_id) self.waitForElement(LocatorsAdidas.adidasid_wait_1D_id) adidas_element = self.isElementPresent( LocatorsAdidas.adidasid_assert_chart_id) assert adidas_element == True def click_adidas_profile(self): self.elementClick(LocatorsAdidas.profile_css, locatorType='css') self.waitForElement(LocatorsAdidas.profile_wait_website_css, locatorType='css') profile_element = self.isElementPresent( LocatorsAdidas.profile_assert_ir_css, locatorType='css') assert profile_element == True def click_adidas_financials(self): self.elementClick(LocatorsAdidas.financials_css, locatorType='css') self.waitForElement(LocatorsAdidas.financials_wait_picker_id) financials_element = self.isElementPresent( LocatorsAdidas.financials_assert_estimates_css, locatorType='css') assert financials_element == True def click_adidas_analyzer(self): self.elementClick(LocatorsAdidas.analyzer_css, locatorType='css') self.waitForElement(LocatorsAdidas.analyzer_wait_sortarrows_css, locatorType='css') analyzer_element = self.isElementPresent( LocatorsAdidas.analyzer_assert_chart_css, locatorType='css') assert analyzer_element == True def click_adidas_tradescreen(self): self.elementClick(LocatorsAdidas.traderscreen_css, locatorType='css') self.waitForElement(LocatorsAdidas.tradescreen_wait_picker_id) tradescreen_element = self.isElementPresent( LocatorsAdidas.tradescreen_assert_count_css, locatorType='css') assert tradescreen_element == True
class CurrenciesPage(CurrenciesLocators, SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def click_currencies(self): # Performance page is the default currencies page self.elementClick(CurrenciesLocators.currencies_icon_link, locatorType='link') self.waitForElement(CurrenciesLocators.currencies_peformance_picker_id) def verify_currencies_performance(self): verify_performance = self.isElementPresent( CurrenciesLocators.currencies_performance_arrows_xpath, locatorType='xpath') return verify_performance def click_currencies_quick_performance(self): self.elementClick(CurrenciesLocators.currencies_quick_performance_css, locatorType='css') self.waitForElement( CurrenciesLocators.currencies_quick_performance_next_id) def verify_currencies_quick_performance(self): verify_qp = self.isElementPresent( CurrenciesLocators.currencies_quick_performance_arrows_xpath, locatorType='xpath') return verify_qp def click_currencies_overview(self): self.elementClick(CurrenciesLocators.currencies_overview_css, locatorType='css') self.waitForElement(CurrenciesLocators.currencies_overview_arrows_id) def verify_currencies_overview(self): verify_overview = self.isElementPresent( CurrenciesLocators.currencies_overview_picker_id) return verify_overview def click_currencies_chart(self): self.elementClick(CurrenciesLocators.currencies_chart_css, locatorType='css') self.waitForElement(CurrenciesLocators.currencies_chart_picker_id) def verify_currencies_chart(self): verify_chart = self.isElementPresent( CurrenciesLocators.currencies_chart_reload_css, locatorType='css') return verify_chart def click_currencies_quoteboard(self): self.elementClick(CurrenciesLocators.currencies_quoteboard_css, locatorType='css') self.waitForElement(CurrenciesLocators.currencies_quoteboard_picker_id) def verify_currencies_quoteboard(self): verify_quoteboard = self.isElementPresent( CurrenciesLocators.currencies_quote_board_aud_cad_css, locatorType='css') return verify_quoteboard def click_currencies_crossrates(self): self.elementClick(CurrenciesLocators.cross_rates_link, locatorType='link') self.waitForElement(CurrenciesLocators.cross_eur_usd_last_id) def verify_currencies_crossrates(self): verify_crossrates = self.isElementPresent( CurrenciesLocators.cross_usd_jpy_last_id) return verify_crossrates def click_currencies_cryptos(self): self.elementClick(CurrenciesLocators.cryptos_link, locatorType='link') self.waitForElement(CurrenciesLocators.cryptos_btc_flag_css, locatorType='css') def verify_currencies_cryptos(self): verify_cryptos = self.isElementPresent( CurrenciesLocators.cryptos_btc_link, locatorType='link') return verify_cryptos def click_currencies_crypto_pairs(self): self.elementClick(CurrenciesLocators.crypto_pairs_link, locatorType='link') self.waitForElement(CurrenciesLocators.crypto_pairs_group_id) def verify_currencies_crypto_pairs(self): verify_crypto_pairs = self.isElementPresent( CurrenciesLocators.crypto_pairs_picker_id) return verify_crypto_pairs def click_currencies_crypto_news(self): self.elementClick(CurrenciesLocators.crypto_news_link, locatorType='link') self.waitForElement(CurrenciesLocators.crypto_news_chart_reload_css, locatorType='css') def verify_currencies_crypto_news(self): verify_crypto_news = self.isElementPresent( CurrenciesLocators.crypto_news_chart_resizer_id) return verify_crypto_news
class HomePage(LocatorsHp, LocatorsLP, SeleniumDriver): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver def click_user_button(self): self.driver.find_element_by_id(LocatorsLP.user_button_id).click() def click_logout(self): self.driver.find_element_by_css_selector(LocatorsLP.logout_css, locatorType='css').click() def click_markets(self): self.elementClick(LocatorsHp.markets_css, locatorType='css') self.waitForElement(LocatorsHp.arrows_id) markets_element = self.isElementPresent(LocatorsHp.column_picker_class, locatorType='class') assert markets_element == True def click_currencies(self): self.elementClick(LocatorsHp.currencies_css, locatorType='css') self.waitForElement(LocatorsHp.arrows_id) currencies_element = self.isElementPresent( LocatorsHp.column_picker_class, locatorType='class') assert currencies_element == True def click_commodities(self): self.elementClick(LocatorsHp.commodities_css, locatorType='css') self.waitForElement(LocatorsHp.arrows_id) commodities_element = self.isElementPresent( LocatorsHp.column_picker_class, locatorType='class') assert commodities_element == True def click_fixincome(self): self.elementClick(LocatorsHp.fix_income_css, locatorType='css') self.waitForElement(LocatorsHp.arrows_id) fixincome_element = self.isElementPresent( LocatorsHp.column_picker_class, locatorType='class') assert fixincome_element == True def click_futures(self): self.elementClick(LocatorsHp.futures_css, locatorType='css') self.waitForElement(LocatorsHp.arrows_id) futures_element = self.isElementPresent(LocatorsHp.column_picker_class, locatorType='class') assert futures_element == True def click_news(self): self.elementClick(LocatorsHp.news_css, locatorType='css') self.waitForElement(LocatorsHp.news_home_css, locatorType='css') news_element = self.isElementPresent(LocatorsHp.news_search_class, locatorType='class') assert news_element == True def click_workspace(self): self.elementClick(LocatorsHp.workspace_css, locatorType='css') self.waitForElement(LocatorsHp.workspace_new_css, locatorType='css') workspace_element = self.isElementPresent( LocatorsHp.workspace_assert_css, locatorType='css') assert workspace_element == True def click_watchlist(self): self.elementClick(LocatorsHp.watchlist_css, locatorType='css') self.waitForElement(LocatorsHp.watchlist_new_css, locatorType='css') watchlist_element = self.isElementPresent( LocatorsHp.watchlist_assert_css, locatorType='css') assert watchlist_element == True def click_covid(self): self.elementClick(LocatorsHp.covid_css, locatorType='css') self.waitForElement(LocatorsHp.covid_map_css, locatorType='css') covid_element = self.isElementPresent(LocatorsHp.covid_assert_css, locatorType='css') assert covid_element == True def click_trump(self): self.elementClick(LocatorsHp.trump_css, locatorType='css') self.waitForElement(LocatorsHp.trump_icon_css, locatorType='css') trump_element = self.isElementPresent(LocatorsHp.trump_assert_css, locatorType='css') assert trump_element == True def click_screener(self): self.elementClick(LocatorsHp.screener_css, locatorType='css') self.waitForElement(LocatorsHp.screener_tab_css, locatorType='css') screener_element = self.isElementPresent( LocatorsHp.screener_assert_css, locatorType='css') assert screener_element == True def click_funds(self): self.elementClick(LocatorsHp.funds_css, locatorType='css') self.waitForElement(LocatorsHp.funds_overview_css, locatorType='css') funds_element = self.isElementPresent(LocatorsHp.funds_assert_css, locatorType='css') assert funds_element == True def click_portfolio(self): self.elementClick(LocatorsHp.portfolio_css, locatorType='css') self.waitForElement(LocatorsHp.portfolio_new_css, locatorType='css') portfolio_element = self.isElementPresent( LocatorsHp.portfolio_assert_css, locatorType='css') assert portfolio_element == True def click_calednar(self): self.elementClick(LocatorsHp.calendar_css, locatorType='css') self.waitForElement(LocatorsHp.calendar_filter_css, locatorType='css') calendar_element = self.isElementPresent( LocatorsHp.calendar_assert_css, locatorType='css') assert calendar_element == True def click_analyzer(self): self.elementClick(LocatorsHp.analyzer_css, locatorType='css') self.waitForElement(LocatorsHp.analyzer_filter_css, locatorType='css') analyzer_element = self.isElementPresent( LocatorsHp.analyzer_assert_css, locatorType='css') assert analyzer_element == True def click_backtester(self): self.elementClick(LocatorsHp.backtester_css, locatorType='css') self.waitForElement(LocatorsHp.backtester_help_css, locatorType='css') backtester_element = self.isElementPresent( LocatorsHp.backtester_assert_css, locatorType='css') assert backtester_element == True def click_alerts(self): self.elementClick(LocatorsHp.alerts_css, locatorType='css') self.waitForElement(LocatorsHp.alerts_calendar_css, locatorType='css') alerts_element = self.isElementPresent(LocatorsHp.alerts_assert_css, locatorType='css') assert alerts_element == True def click_ecdata(self): self.elementClick(LocatorsHp.economic_data_css, locatorType='css') self.waitForElement(LocatorsHp.economic_filter_css, locatorType='css') ecdata_element = self.isElementPresent(LocatorsHp.economic_assert_css, locatorType='css') assert ecdata_element == True def click_etf(self): self.elementClick(LocatorsHp.etfs_css, locatorType='css') self.waitForElement(LocatorsHp.etf_overview_css, locatorType='css') etf_element = self.isElementPresent(LocatorsHp.etf_assert_css, locatorType='css') assert etf_element == True def click_derivatives(self): self.elementClick(LocatorsHp.derivatives_css, locatorType='css') self.waitForElement(LocatorsHp.derivatives_issuers_css, locatorType='css') derivatives_element = self.isElementPresent( LocatorsHp.derivatives_assert_css, locatorType='css') assert derivatives_element == True def click_realtime(self): self.elementClick(LocatorsHp.realtime_css, locatorType='css') self.waitForElement(LocatorsHp.arrows_id) realtime_element = self.isElementPresent( LocatorsHp.realtime_assert_css, locatorType='css') assert realtime_element == True
class RegisterCoursesPage(BasePage): log = cl.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.map = RegisterCoursePageMap(driver) self.driver = driver ################ ### Locators ### ################ #_search_box = "course" #_course = "//div[contains(@class,'course-title')]//h4[contains(text(),'{0}')]" # _all_courses = "course-listing-title" # _enroll_button = "//button[text()='Enroll in Course']" # _cc_num = "cardnumber" # _cc_exp = "exp-date" # _cc_cvv = "cvc" # _submit_enroll = "(//button[contains(@class,'btn-submit')])[2]" # _enroll_error_message = "//div[@class='card-errors has-error']/ul/li/span" # _card_number_frame="//iframe[@title='Secure card number input frame']" # _expiry_date_frame="//iframe[@title='Secure expiration date input frame']" # _security_code_frame="//iframe[@title='Secure CVC input frame']" ############################ ### Element Interactions ### ############################ def enterCourseName(self, name): self.sendKeys(name, element=self.map.search_box()) def selectCourseToEnroll(self, fullCourseName): self.elementClick(element=self.map.course(fullCourseName)) def clickOnEnrollButton(self): self.elementClick(element=self.map.enroll_button) def enterCardNum(self, num): self.switchToFrame(element=self.map.card_number_frame) self.sendKeys(num, element=self.map.cc_num) self.switchToDefaultContent() def enterCardExp(self, exp): self.switchToFrame(element=self.map.expiry_date_frame) self.sendKeys(exp, element=self.map.cc_exp) self.switchToDefaultContent() def enterCardCVV(self, cvv): self.switchToFrame(element=self.map.security_code_frame) self.sendKeys(cvv, element=self.map.cc_cvv) self.switchToDefaultContent() def clickEnrollSubmitButton(self): self.elementClick(element=self.map.submit_enroll) def enterCreditCardInformation(self, num, exp, cvv): self.enterCardNum(num) self.enterCardExp(exp) self.enterCardCVV(cvv) def enrollCourse(self, num="", exp="", cvv=""): self.clickOnEnrollButton() self.webScroll(direction="down") self.enterCreditCardInformation(num, exp, cvv) self.clickEnrollSubmitButton() def verifyEnrollFailed(self): result = self.isElementPresent(element=self.map.enroll_error_message) return result