class LoginPage(BasePage): log = cl.custom_logging(logging.DEBUG) def __init__(self, driver): super(LoginPage, self).__init__( driver) # Passing the driver instance to parent/super class self.driver = driver # Locators _loginLink = "Login" _emailField = "user_email" _passwordField = "user_password" _loginButton = "commit" def clickLoginLink(self): self.clickElement(self._loginLink, "link") def enterEmail(self, email): self.sendKeys(email, self._emailField) def enterPassword(self, password): self.sendKeys(password, self._passwordField) def clickLoginButton(self): self.clickElement(self._loginButton, "name") def login_user(self, email, password): self.clickLoginLink() self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyValidLogin(self): element_presence = self.isElementPresent("search-courses", locator_type="id") return element_presence def verifyInvalidLogin(self): element_presence = self.isElementPresent( "//div[contains(text(), 'Invalid email or password.')]", locator_type="xpath") return element_presence def verifyTitle(self): if "Google" in self.getTitle( ): # Intentionally failing the test by passing incorrect expected Title return False else: return True
class LoginPage(BasePage): log = cl.custom_logging(logging.DEBUG) def __init__(self, driver): super(LoginPage, self).__init__( driver) # Passing the driver instance to parent/super class self.driver = driver # Locators _usernameField = "username-input-area" # id _passwordField = "password-input-area" # id _loginButton = "btn" # id def enterEmail(self, email): self.sendKeys(email, self._usernameField) def enterPassword(self, password): self.sendKeys(password, self._passwordField) def clickLoginButton(self): self.clickElement(self._loginButton) def login_user(self, email, password): self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyValidLogin(self): element_presence = self.isElementPresent("grouptTitle", locator_type="id") return element_presence def verifyInvalidLogin(self): element_presence = self.isElementPresent( "//div[contains(text(), 'Invalid Credentials')]", locator_type="xpath") return element_presence def verifyTitle(self): if "ROC - Subex Ltd - Home Dashboard" in self.getTitle(): return True else: return False
class DBConnection: log = cl.custom_logging(logLevel=logging.DEBUG) def __init__(self): self.conn = None self.cursor = None def get_db_connection(self): try: db_user_name = 'rocref' # Reference DB Username db_user_password = '******' # Reference DB Password db_sid = 'orcl' # Reference DB Oracle SID db_host = 'localhost' # Reference DB Host Machine db_port = '1521' # Reference DB Oracle Port conn_string = f"{db_user_name}/{db_user_password}@{db_sid}" self.log.info("Attempting database connection") self.conn = cx_Oracle.connect(conn_string) self.cursor = self.conn.cursor() self.log.info("Database connection established.") except: self.log.exception("**** Database connection failed.") return self.cursor def execute_sql(self, query): try: cursor = self.get_db_connection() results = cursor.execute(query) query_result = [ row for row in results ] # Populating every row from query results using List Comprehension method self.log.debug("Executed SQL query: " + query) except cx_Oracle.DatabaseError: self.log.exception( "**** The connection to db has issues. Query couldn't be executed." ) except cx_Oracle.InterfaceError: self.log.exception("**** Database connection is not open") finally: return query_result self.cursor.close() self.conn.close() self.log.debug("Database connection is closed")
class BasePage(SeleniumDriver): log = cl.custom_logging(logging.INFO) def __init__(self, driver): self.driver = driver def verify_page_title(self, expected_title): actual_title = self.getTitle() if actual_title == expected_title: self.log.info("Page Title Matched to :" + expected_title) else: self.log.info("Page Title Not Matched to :" + expected_title) def click_clear_button(self): self.clickElement("clear") def click_search_button(self): self.click_clear_button() self.clickElement("search")
class TestStatus(SeleniumDriver): log = cl.custom_logging(logging.INFO) def __init__(self, driver): self.driver = driver super(TestStatus, self).__init__(driver) # Passing the driver instance to parent/super class self.resultList = [] def set_status(self, result, resultMessage): try: if result is 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) except: self.resultList.append("FAIL") self.log.error("*** Exception Occurred") self.screenshot(resultMessage) def mark(self, result, resultMessage): self.set_status(result, resultMessage) def mark_final(self, testName, result, resultMessage): self.set_status(result, resultMessage) if "FAIL" in self.resultList: self.log.error(testName + ": Test was Failed") self.resultList.clear() assert True == False # To mark the test as failure else: self.log.info(testName + ": Test was Passed") self.resultList.clear() assert True == True # To mark the test as success
class SeleniumDriver: log = cl.custom_logging(logging.DEBUG) def __init__(self, driver): self.driver = driver def getTitle(self): return self.driver.title def getBy(self, locator_type): locatorType = locator_type.lower() if locatorType == "id": return By.ID elif locatorType == "name": return By.NAME elif locatorType == "xpath": return By.XPATH elif locatorType == "class": return By.CLASS_NAME elif locatorType == "link": return By.LINK_TEXT elif locatorType == "partial_link": return By.PARTIAL_LINK_TEXT elif locatorType == "tag": return By.TAG_NAME elif locatorType == "css": return By.CSS_SELECTOR else: self.log.error("*** The locator type ", locatorType, " is not valid") return False def waitForElement(self, locator, locator_type="id", timeoutSecs=10, poll_freq=1): element = None print("Waiting for the Element for max ", timeoutSecs, " secs with polling frequency of ", poll_freq, " secs..") wait = WebDriverWait(self.driver, timeout=timeoutSecs, poll_frequency=poll_freq, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) try: getby = self.getBy(locator_type) element = wait.until(EC.element_to_be_clickable((getby, locator))) self.log.info("Element was found with locator: ", locator) except: self.log.error("*** Element was not found with locator: ", locator) return element def isElementPresent(self, locator, locator_type="id", timeoutSecs=10, poll_freq=1): try: print("Waiting for the Element for max", timeoutSecs, "secs with polling frequency of", poll_freq, "secs..") wait = WebDriverWait(self.driver, timeout=timeoutSecs, poll_frequency=poll_freq, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) getby = self.getBy(locator_type) element = wait.until( EC.presence_of_element_located((getby, locator))) self.log.info("Element is present with locator: ", locator) return True except: self.log.error("*** Element is not present with locator: ", locator) return False def isElementDisplayed(self, timeoutSecs=7, poll_freq=1, element=None): try: print("Waiting for the Element display for max ", timeoutSecs, " secs with polling frequency of ", poll_freq, "secs..") wait = WebDriverWait(self.driver, timeout=timeoutSecs, poll_frequency=poll_freq, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) result = wait.until(EC.visibility_of_element_located(element)) if result is not None: self.log.info("Element is displayed") return True else: self.log.error("*** Element is not displayed") return False except: self.log.error( "*** Exception occurred while checking for element display") return False def clickElement(self, locator, locator_type="id"): try: element = self.waitForElement(locator, locator_type) element.click() self.log.info("Element was clicked with locator: '" + locator + "' and locator_type: " + locator_type) except: self.log.error("*** Element was not found with locator: '" + locator + "' and locator_type: " + locator_type) print_stack() def sendKeys(self, data, locator, locator_type="id"): try: element = self.waitForElement(locator, locator_type) element.send_keys(data) self.log.info("Keys were sent to element with locator: '" + locator + "' and locator_type: " + locator_type) except: self.log.error( "*** Keys were not sent to element with locator: '" + locator + "' and locator_type: " + locator_type) print_stack() def screenshot(self, resultMessage): filename = resultMessage + "." + str(time.time() * 1000) + ".png" file_dir = "/screenshots/" full_file = file_dir + filename try: if not os.path.exists(file_dir): os.makedirs(file_dir) self.driver.save_screenshot(full_file) self.log.info("Screenshot saved as " + full_file) except: self.log.error("*** Exception while saving screenshot") print_stack() def scrollPage(self, direction="up"): if direction.lower() == "up": self.driver.execute_script("window.scrollBy(0, -1000);") elif direction.lower() == "half-up": self.driver.execute_script("window.scrollBy(0, -500);") elif direction.lower() == "half-down": self.driver.execute_script("window.scrollBy(0, 500);") elif direction.lower() == "little-up": self.driver.execute_script("window.scrollBy(0, -200);") elif direction.lower() == "little-down": self.driver.execute_script("window.scrollBy(0, 200);") else: self.driver.execute_script("window.scrollBy(0, 1000);") def switch_to_frame(self, frame_name): try: self.driver.switch_to.frame(frame_name) self.log.info("Switched to frame: " + frame_name) except: self.log.error("*** Exception occurred while switching to frame") def switch_default_content(self): self.driver.switch_to.default_content() def select_dropdown_value(self, dropdown_value, dropdown_locator, dropdown_locator_type="id"): select = Select( self.waitForElement(dropdown_locator, dropdown_locator_type)) try: select.select_by_visible_text(dropdown_value) self.log.info("Selected drop down value as : " + dropdown_value) except: self.log.error("*** Drop down Value not found: " + dropdown_value)
class CoursesPage(BasePage): log = cl.custom_logging(logging.INFO) # Locators in Courses Page _find_course_field = "search-courses" _search_course_button = "search-course-button" _javascript_course_link = "//div[@class='course-listing-title' and contains(text(), 'JavaScript for beginners')]" _enroll_course_button = "enroll-button" _cr_num_iframe = "__privateStripeFrame5" _cr_num_field = "cardnumber" _expiry_date_iframe = "__privateStripeFrame6" _expiry_date_field = "exp-date" _cvc_iframe = "__privateStripeFrame7" _cvc_field = "cvc" _country_code_dropdown = "country_code_credit_card-cc" _postal_code_iframe = "__privateStripeFrame8" _postal_code_field = "postal" _save_payment_details_checkbox = "save-payment-details" _terms_checkbox = "agreed_to_terms_checkbox" _final_enroll_button = "confirm-purchase" _error_message = "//div[contains(text(),'The card was declined.')]" def __init__(self, driver): self.driver = driver super(CoursesPage, self).__init__(driver) def search_course(self, course_name): self.sendKeys(course_name, self._find_course_field) self.clickElement(self._search_course_button) self.log.info("Searched for course: " + course_name) def select_javascript_course(self, course_name): if course_name.lower() in "javascript for beginners": self.clickElement(self._javascript_course_link, locator_type="xpath") self.log.info("Selected the course: 'JavaScript for beginners'") def click_enroll_course(self): self.scrollPage("down") self.clickElement(self._enroll_course_button) self.log.info("Clicked on Enroll Course button") def enter_card_num(self, card_number): self.switch_to_frame(self._cr_num_iframe) self.sendKeys(card_number, self._cr_num_field, locator_type="name") self.switch_default_content() self.log.debug("Entered Card Number") def enter_expiry_date(self, exp_date): """ Enter the Expiry Date in MM/YY format :param exp_date: :return: None """ self.switch_to_frame(self._expiry_date_iframe) self.sendKeys(exp_date, self._expiry_date_field, locator_type="name") self.switch_default_content() self.log.debug("Entered Card Expiry Date") def enter_cvc_code(self, cvc_code): self.switch_to_frame(self._cvc_iframe) self.sendKeys(cvc_code, self._cvc_field, locator_type="name") self.switch_default_content() self.log.debug("Entered CVC Code") def choose_country(self, country_name): self.select_dropdown_value( dropdown_locator=self._country_code_dropdown, dropdown_value=country_name) self.log.debug("Selected Country") def enter_postal_code(self, postal_code): self.switch_to_frame(self._postal_code_iframe) self.sendKeys(postal_code, self._postal_code_field, locator_type="name") self.switch_default_content() self.log.debug("Entered Postal Code") def disable_save_payment_details(self): self.clickElement(self._save_payment_details_checkbox) self.log.debug("Disabled saving payment details") def accept_terms(self): self.clickElement(self._terms_checkbox) self.log.debug("Accepted Terms and Conditions") def submit_payment(self): self.clickElement(self._final_enroll_button) self.log.info("Submitted Payment Details") def enter_payment_details(self, card_num, card_exp_date, cvc_num, country_name, pin_code): try: self.enter_card_num(card_num) self.enter_expiry_date(card_exp_date) self.enter_cvc_code(cvc_num) self.choose_country(country_name) self.enter_postal_code(pin_code) self.log.info("Entered Payment details.") except: self.log.error( "*** Exception occurred during entering payment details.") print_stack() def enroll_javascript_course(self, card_num, card_exp_date, cvc_num, country, pin_code): self.search_course("JavaScript for beginners") self.select_javascript_course("JavaScript for beginners") self.click_enroll_course() self.scrollPage("half-down") self.enter_payment_details(card_num, card_exp_date, cvc_num, country, pin_code) self.disable_save_payment_details() self.accept_terms() self.submit_payment() self.log.info("Enrolled for course.") def verify_error_presence(self): try: error_present = self.isElementPresent(self._error_message, "xpath") if error_present is not None: self.log.info("Error Message is present") return True else: self.log.error("*** Error Message was Not present") return False except: self.log.error( "*** Exception occurred while checking for Error Message") print_stack() return False