class TrustId210012Overview(seleniumDriver): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver _hid_smartcard = '//select[@id="storage"]/option[2]' _front_voucher = 'voucher_num' _validity_1yr = '//*[@id="sponsor_validity_opt"]/option[2]' _overview_nxt = "//div[@id='page_action']/input[@id='next']" def front_voucher(self, vou): self.sendKeys(vou, self._front_voucher, locatorType='id') def validity_period_one_yr(self): self.clickElement(self._validity_1yr, locatorType='xpath') def overview_next(self): self.clickElement(self._overview_nxt, locatorType='xpath') def overview_one_yr_validity_option(self): self.validityPeriod1Yr() self.overviewNext()
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 LoginPage(BasePage): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _retailer_master = "//ul[@id='collapsibleMenuContainer']//a[text()='Retailer Master']" _retailer_position_mapping = "//ul[@id='collapsibleMenuContainer']//a[text()='Retailer Position Mapping']" _route_master = "//ul[@id='collapsibleMenuContainer']//a[text()='Route']" _retailer_visit_plan = "//ul[@id='collapsibleMenuContainer']//a[text()='Retailer Visit Plan']" def NavigateToRetailerMaster(self): self.elementClick(locator=self._retailer_master, locatorType="xpath") def NavigateToRetailerPositionMapping(self): self.elementClick(locator=self._retailer_position_mapping, locatorType="xpath") def NavigateToRouteMaster(self): self.elementClick(locator=self._route_master, locatorType="xpath") def NavigateToRetailerVisitPlan(self): self.elementClick(locator=self._retailer_visit_plan, locatorType="xpath")
class trustId210012Retrieval(seleniumDriver): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver _start_retrieval = '//*[@id="nav"]/input' _activation_code = 'var1' _account_password = '******' def start_retrieval(self): self.click_element(self._start_retrieval, locatorType='xpath') def activation_code(self): self.find_element(self._activation_code) self.paste_activation_code() def account_password(self, password): self.send_keys(password, self._account_password) def finish_retrieval(self): self.click_element(self._start_retrieval, locatorType='xpath') def retrieve_one_yr_validity_option(self, password): self.start_retrieval() self.activation_code() self.account_password(password) self.finish_retrieval()
class Util(object): log = cl.CustomLogger(logging.INFO) def sleep(self, sec, info=""): """ Put the program to wait for the specified amount of seconds :param sec: :param info: :return: """ if info is not None: self.log.info("Wait {} seconds for {}".format(sec, info)) try: time.sleep(sec) except InterruptedError: traceback.print_stack() def get_alpha_numeric(self, length, type="letters"): """ Get random string of characters :param length: :param type: Defaulted to 'letters'. Provide lower/upper/digits for different types :return: Returned random string of characters of specified parameters """ alpha_num = "" if type.lower() == "lower": case = string.ascii_lowercase elif type.lower() == "upper": case = string.ascii_uppercase
class TCaseStatus(SeleniumDriver): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): """ initiates Checkpoint class :param driver: """ super(TCaseStatus, self).__init__(driver) self.results_list = [] def set_result(self, result, result_message): try: if result is not None: # True or False if result: # if True self.results_list.append('PASS') self.log.info("## Verification Successful: {}".format(result_message)) else: # if False self.results_list.append('FAIL') self.log.error("## Verification Failed: {}".format(result_message)) self.screenshot(result_message) else: # if None for example - maybe need different value to append? self.results_list.append('FAIL') self.log.error("## Verification Failed: {} Expected results True or False, but Returned:{}".format(result_message, result)) self.screenshot(result_message) except: # if Something else happend - maybe need different value to append? self.results_list.append('FAIL') self.log.error("## Exception Occured While Evaluating Test Result!: {}. Expected results True or False, but Returned:{}".format(result_message, result)) self.screenshot(result_message) print_stack() def mark(self, result, result_message): """ Marks the result of the verification point in a test case :param result: :param result_message: :return: """ self.set_result(result, result_message) def mark_final(self, test_name, result, result_message): """ Marks the final result in the test case. This will the Test case final status. Called once per Test Case :param test_name: :param result: :param result_message: :return: """ self.set_result(result, result_message) if "FAIL" in self.results_list: self.log.error("## {}: Test Case Failed".format(test_name)) self.results_list.clear() assert True == False else: self.log.info("## {}: Test Case Successful".format(test_name)) self.results_list.clear() assert True == True
class TestStatus(SeleniumDriver): log = cl.CustomLogger(logging.INFO) def __init__(self, driver): """ Inits check point class """ super(TestStatus, self).__init__(driver) self.resultList = [] def setResult(self, result, resultMessage): try: if result is not None: if result: self.resultList.append("PASS") self.log.info("### VERIFICATION SUCCESSFUL:: + " + resultMessage) else: self.resultList.append("FAIL") self.log.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) print_stack() """ Mark the result of the verification point in a test case """ def mark(self, result, resultMessage): self.setResult(result, resultMessage) def markFinal(self, testName, result, resultMessage): """ Mark the final result of the verification point in a test case This needs to be called at least once in a test case This should be final test status of the test case """ self.setResult(result, resultMessage) if "FAIL" in self.resultList: self.log.error(testName, "### TEST FAILED") self.resultList.clear() assert True == False else: self.log.info(testName, "### TEST SUCCESSFUL") self.resultList.clear() assert True == True
class LoginPage(BasePage): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _user_field = "UserName" _password_field = "Password" _login_button = "Login" def enterEmail(self, email): self.sendKeys(email, self._user_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._login_button, locatorType="id") def Login(self, email="", password=""): self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccessful(self): result = self.isElementPresent("notifyAlert", locatorType="id") return result def verifyLoginFaild(self): result = self.isElementPresent( "//div[contains(text(),'Invalid User Name Or Password.')]", locatorType="xpath") return result def verifyLoginTitle(self): return self.verifyPageTitle("IvyCPG - Login")
class RegisterCoursesPage(BasePage): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #Locators _search_box = "//div[@class='input-group']//input[@id='search-courses']" #xpath _mac_linux_course = "//div[@class='col-lg-12']//div[@title='Mac Linux Command Line Basics']" #xpath _all_cources = "//div[@class='row course-list list']//div[@class='course-listing-title']" _search_course_button = 'search-course-button' #id _course = "//div[contains(@class,'course-listing-title') and contains(text(),'{0}')]" _course_curriculum_header = "//div[@class='container']//h2[contains(text(), 'Course Curriculum')]" _enroll_button_top = "//button[@id='enroll-button-top']" _payment_information_header = "//section[@class='spc__section']//div[text()='Payment Information']" _cc_number_iframe_name = "__privateStripeFrame12" _cc_number = "//span//input[@name='cardnumber']" _cc_expiration_date_iframe_name = "__privateStripeFrame13" _cc_expiration_date = "//span//input[@name='exp-date']" _cc_cvc_iframe_name = "__privateStripeFrame14" _cc_cvc = "//span//input[@name='cvc']" _country_dropdown = "//div[@class='form-group']//select[@name='country_code']" # it may return 2 nodes _postal_code_iframe_name = "__privateStripeFrame15" _postal_code = "zipCode" #id _buy_now_button = "//div[@class='m-b-4-xs _3pM7B']//button[@data-test='confirm-enroll']" _agreed_to_terms_checkbox = "//section[@class='spc__section spc__section--terms']" \ "//input[@id='agreed_to_terms_checkbox']" _use_another_card = "//div[@class='p-3-xs']//button[text()='Use another card']" #elements actions def enter_course_name(self, course_name): self.send_Keys(course_name, self._search_box, locator_type="xpath") def click_search_for_course_button(self): self.element_click(self._search_course_button, locator_type='id') def select_course_to_enroll(self, full_course_name): self.element_click(locator=self._course.format(full_course_name), locator_type="xpath") def select_mac_linux_course(self): self.element_click(self._mac_linux_course, locator_type="xpath") def click_enroll_button_top(self): self.element_click(self._enroll_button_top, locator_type="xpath") def click_use_another_card(self): self.element_click(self._use_another_card, locator_type="xpath") time.sleep(3) def enter_cc_number(self, cc_number): #this is to handle dinamic iframe. In real work situation the dinamic iframe is bad practice # Frame takes 6 seconds to show, even more time.sleep(6) #self.switch_to_frame(name=self._cc_number_iframe_name) self.switch_frame_by_index(self._cc_number, locator_type="xpath") self.send_Keys(cc_number, self._cc_number, locator_type="xpath") self.switch_to_default_content() def enter_exp_date(self, exp_date): #self.switch_to_frame(name=self._cc_expiration_date_iframe_name) self.switch_frame_by_index(self._cc_expiration_date, locator_type="xpath") self.send_Keys(exp_date, self._cc_expiration_date, locator_type="xpath") self.switch_to_default_content() def enter_cvc(self, cvc): #self.switch_to_frame(name=self._cc_cvc_iframe_name) self.switch_frame_by_index(self._cc_cvc, locator_type="xpath") self.send_Keys(cvc, self._cc_cvc, locator_type="xpath") self.switch_to_default_content() def enter_postal_code(self, postal_code): #self.switch_to_frame(name=self._postal_code_iframe_name) self.switch_frame_by_index(self._postal_code, locator_type="id") self.send_Keys(postal_code, self._postal_code, locator_type="id") self.switch_to_default_content() def click_buy_now_button(self): self.element_click(self._buy_now_button, locator_type="xpath") # TODO start here and in register_courses_tests # try the 2 following methods and see if they work correctly def select_agreed_checkbox(self): selected = self.select_checkbox(self._agreed_to_terms_checkbox, locator_type='xpath') def unselect_agreed_checkbox(self): unselected = self.unselect_checkbox(self._agreed_to_terms_checkbox, locator_type="xpath") #main functions def search_for_course( self, course_name='' ): #parameters are optional - to test search for empty course self.enter_course_name(course_name) self.click_search_for_course_button() def verify_redirected_to_course_details_page(self): self.web_scroll(direction='down') result = self.is_element_present(self._course_curriculum_header, locator_type="xpath") self.web_scroll(direction="up") return result def enroll_in_course_from_course_details_page(self): self.click_enroll_button_top() def verify_redirected_to_checkout_page(self): result = self.is_element_present(self._payment_information_header, "xpath") return result def enter_another_card_details_postal_code(self, cc_number="", exp_date="", cvc="", postal_code=""): self.web_scroll(direction="down") self.click_use_another_card() self.enter_cc_number(cc_number) self.enter_exp_date(exp_date) self.enter_cvc(cvc) self.enter_postal_code(postal_code) def verify_buy_now_button_disabled(self): result = not self.isEnabled( self._buy_now_button, locator_type="xpath", info="Buy Now Button") return result def verify_buy_now_button_enabled(self): result = self.isEnabled(self._buy_now_button, locator_type="xpath", info="Buy Now Button") return result def clear_cc_fields(self): self.clear_field(self._cc_number, locator_type="xpath") self.clear_field(self._cc_expiration_date, locator_type="xpath") self.clear_field(self._cc_cvc, locator_type="xpath") self.clear_field(self._postal_code, locator_type="xpath")
class trustId210012Approval(seleniumDriver): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver _account_mgmt = '//*[@id="acctCert"]/a' _lname_search = '//*[@id="mainContent"]/form/table/tbody/tr[4]/td[1]/input' _search = '//*[@id="mainContent"]/form/table/tbody/tr[8]/td[2]/input' _select_acct = '//*[@id="mainContent"]/form/p[3]/input' _approve_acct = '//*[@id="mainContent"]/form[1]/p/select/option[16]' _update = '//*[@id="mainContent"]/form[1]/p/input' _popup_window = '//*[@id="popup"]/form/div/input' _activation_code = '//*[@id="mainContent"]/form[2]/p/select/optgroup[2]/option[6]' _continue = '//*[@id="mainContent"]/form[2]/p/input' _cert_id = 'cert_id' def account_mgmt(self): self.click_element(self._account_mgmt, locatorType='xpath') def lname_search(self, lname): self.send_keys(lname, self._lname_search, locatorType='xpath') def search_acct(self): self.click_element(self._search, locatorType='xpath') def select_acct(self): self.click_element(self._select_acct, locatorType='xpath') def approve_acct(self): self.click_element(self._approve_acct, locatorType='xpath') def update(self): self.click_element(self._update, locatorType='xpath') def approve_one_yr_validity_option(self, lname): self.account_mgmt() self.lname_search(lname) self.search_acct() self.select_acct() self.approve_acct() self.update() ##### Close Approve Account Window def close_approve_window(self): self.wait_for_element(self._popup_window, locatorType='xpath') self.click_element(self._popup_window, locatorType='xpath') ##### Get Activation Code def activation_code(self): self.click_element(self._activation_code, locatorType='xpath') def contine(self): self.click_element(self._continue, locatorType='xpath') def get_code(self): self.activation_code() self.contine() ##### Copy Code and close window def copyCode(self): self.wait_for_element(self._cert_id) self.copy_activation_code() def close_popup(self): self.click_element(self._popup_window, locatorType='xpath') def close_code_window(self): self.copy_code() self.close_popup()
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 else: self.log.info("Locator type " + locatorType + " not correct/supported") return False def getElement(self, locator, locatorType="id"): element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info("Element found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def getElementList(self, locator, locatorType="id"): """ NEW METHOD Get list of elements """ element = None try: locatorType = locatorType.lower() byType = self.getByType(locatorType) element = self.driver.find_elements(byType, locator) self.log.info("Element list found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Element list not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator="", locatorType="id", element=None): """ Click on an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def sendKeys(self, data, locator="", locatorType="id", element=None): """ Send keys to an element -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def getText(self, locator="", locatorType="id", element=None, info=""): """ NEW METHOD Get 'Text' on an element Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty self.log.debug("In locator condition") element = self.getElement(locator, locatorType) self.log.debug("Before finding text") text = element.text self.log.debug("After finding element, size is: " + str(len(text))) if len(text) == 0: text = element.get_attribute("innerText") if len(text) != 0: self.log.info("Getting text on element :: " + info) self.log.info("The text is :: '" + text + "'") text = text.strip() except: self.log.error("Failed to get text on element " + info) print_stack() text = None return text def isElementPresent(self, locator="", locatorType="id", element=None): """ Check if element is present -> MODIFIED Either provide element or a combination of locator and locatorType """ try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) if element is not None: self.log.info("Element present with locator: " + locator + " locatorType: " + locatorType) return True else: self.log.info("Element not present with locator: " + locator + " locatorType: " + locatorType) return False except: print("Element not found") return False def isElementDisplayed(self, locator="", locatorType="id", element=None): """ NEW METHOD Check if element is displayed Either provide element or a combination of locator and locatorType """ isDisplayed = False try: if locator: # This means if locator is not empty element = self.getElement(locator, locatorType) if element is not None: isDisplayed = element.is_displayed() self.log.info("Element is displayed with locator: " + locator + " locatorType: " + locatorType) else: self.log.info("Element not displayed with locator: " + locator + " locatorType: " + locatorType) return isDisplayed except: print("Element not found") return False def elementPresenceCheck(self, locator, byType): """ Check if element is present """ try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.log.info("Element present with locator: " + locator + " locatorType: " + str(byType)) return True else: self.log.info("Element not present with locator: " + locator + " locatorType: " + str(byType)) return False except: self.log.info("Element not found") return False def waitForElement(self, locator, locatorType="id", timeout=10, pollFrequency=0.5): element = None try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=pollFrequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until(EC.element_to_be_clickable((byType, locator))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") print_stack() return element def webScroll(self, direction="up"): """ NEW METHOD """ if direction == "up": # Scroll Up self.driver.execute_script("window.scrollBy(0, -1000);") if direction == "down": # Scroll Down self.driver.execute_script("window.scrollBy(0, 1000);")
class RegisterCoursesPage(BasePage): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver #locators: _search_box = "//input[@id='search']" #xpath _search_button = '//button[@type="submit"]' #xpath _course_name = "//h4[@class='dynamic-heading']" #xpath _enroll_button = "//div[@class='col-md-8 col-md-offset-2']//button" #xpath _cc_num = "//input[@name='cardnumber']" #xpath _num_iframe = "__privateStripeFrame4855" #name _cc_exp = "exp-date" #name _exp_iframe = "__privateStripeFrame4857" _cc_cvv = "cvc" #name _cvc_iframe = "__privateStripeFrame4856" _submit_enroll = "free" #name _enroll_error_message = "//span[text()='Your card number is invalid.']" #xpath def enter_course_name(self, name): self.element_send(name, self._search_box, "xpath") self.element_click(self._search_button, "xpath") def select_course_to_enroll(self, full_course_name): JS_course_name = self.get_text(self._course_name, "xpath") if full_course_name.lower() == JS_course_name.lower(): self.element_click(self._course_name, "xpath") def enter_card_num(self, num): time.sleep(6) self.switch_frame_by_index(self._cc_num) self.element_send(num, self._cc_num, "xpath") self.switch_to_default() def enter_card_exp(self, exp): self.switch_frame_by_index(self._cc_exp, "name") self.element_send(exp, self._cc_exp, "name") self.switch_to_default() def enter_card_cvv(self, cvv): self.switch_frame_by_index(self._cc_cvv, "name") self.element_send(cvv, self._cc_cvv, "name") self.switch_to_default() def click_enroll_submit_button(self): self.element_click(self._submit_enroll, "name") def enter_credit_card_info(self, num, exp, cvv): self.enter_card_num(num) self.enter_card_exp(exp) self.enter_card_cvv(cvv) def enroll_course(self, num="", exp="", cvv=""): self.element_click(self._enroll_button, "xpath") self.driver.execute_script("window.scrollBy(0, 700);") time.sleep(2) self.enter_credit_card_info(num, exp, cvv) self.click_enroll_submit_button() def verify_enroll_failed(self): if self.is_element_present(self._enroll_error_message, "xpath"): time.sleep(3) return self.is_element_displayed(self._enroll_error_message, "xpath") else: return False
class SeleniumDriver(): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def get_title(self): return self.driver.title def get_by_type(self, locatorType): locatorType = locatorType.lower() if locatorType == 'id': return By.ID elif locatorType == 'xpath': return By.XPATH elif locatorType == 'name': return By.NAME elif locatorType == 'class': return By.CLASS_NAME elif locatorType == 'css': return By.CSS_SELECTOR elif locatorType == 'link': return By.LINK_TEXT else: self.log.info('Element: ' + locatorType + ' not supported ') return False def find_element(self, locator, locatorType='id'): element= None try: byType = self.getByType(locatorType) element = self.driver.find_element(byType, locator) self.log.info('Found Element by locatorType: ' + locatorType + 'and locator: ' + locator) except: self.log.info('Element not found by locatorType: ' + locatorType + 'and locator: ' + locator) return element def click_element(self, locator, locatorType='id'): try: element = self.findElement(locator, locatorType) element.click() self.log.info('Found Element by locatorType: ' + locatorType + 'and locator: ' + locator) except: self.log.info('Element not found by locatorType: ' + locatorType + 'and locator: ' + locator) print_stack() def send_keys(self, data, locator, locatorType='id'): try: element = self.findElement(locator, locatorType) element.send_keys(data) self.log.info('Found Element by locatorType: ' + locatorType + 'and locator: ' + locator) except: self.log.info('Element not found by locatorType: ' + locatorType + 'and locator: ' + locator) print_stack() def time_stamp(self): n = None n = self.driver.datetime.now().strftime('%a.%H.%M.%S.%f') return n def copy_activation_code(self): activationCode = None activationCode = self.driver.find_element_by_id('cert_id').text return activationCode def paste_activation_code(self): activationCode = None activationCode = self.driver.copyActivationCode.send_keys(activationCode) return activationCode def element_present(self, locator, locatorType='id'): try: element = self.findElement(locator, locatorType) if element is not None: self.log.info('Element found by locatorType: ' + locatorType + 'and locator: ' + locator) return True else: self.log.info('Element not found by locatorType: ' + locatorType + 'and locator: ' + locator) return False except: self.log.info('Element not found by locatorType: ' + locatorType + 'and locator: ' + locator) def wait_for_element(self, locator, locatorType='id', timeout=10, pollFrequency=.5): element = None try: byType = self.getByType(locatorType) self.log.info('Element appeared ::' + str(timeout) + ':: seconds before it was clickable') wait = WebDriverWait(self.b, 10, poll_frequency=.5, ignored_exceptions=[ElementNotSelectableException, ElementNotVisibleException, NoSuchElementException]) element = wait.until(EC.element_to_be_clickable((byType, 'Stop Feature Stops 0'))) self.log.info('Element appeared on site') except: self.log.info('Element didn\'t appear on site') print_stack() return element
class WebBrowser(): instance = None log = cl.CustomLogger() def __init__(self, context): self.driver = context.driver self.context = context def get_element(self, element): """Espera e retorna o elemento @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento """ try: el = self.wait_element(element, timeout=10) self.log.info("Element found in get element... "+element) except: el = None self.log.info("Element not found in get element...") return el def wait_element(self, element, timeout=10): """Espera o elemento ser exibido na tela pelo tempo definido pelo usuário @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param timeout(int): tempo máximo de espera """ try: self.log.info("Waiting for :: " + str(timeout) + " :: seconds for element "+element) element = WebDriverWait(self.context.driver, 10).until( EC.presence_of_element_located((By.XPATH, element)) ) print("---------------------------------------\n") print("el:",element) except ElementNotFoundException: self.log.error("Element was not found in wait element...") raise except TimeoutException: self.log.error("Element was not found in wait element...") raise return element def click_on(self, element): """Clica no elemento @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento """ try: element = self.get_element(element) element.click() self.log.info("Clicked on : ", element) except (ElementNotClickableException, ElementNotFoundException): print_stack() raise def send_keys(self, element, text=""): """Envia texto ao elemento @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param text(str) """ try: element = self.get_element(element) element.send_keys(text) self.log.info("Keys sent to: ", element) except ElementNotFoundException: self.log.error("Could not send keys to element: ", element) print_stack() raise def select_element_by_text(self, element, text=""): """Seleciona o elemento em um menu do tipo select pelo atributo texto @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param text(str) """ try: element = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(By.XPATH(element))) select = Select(element) select.select_by_visible_text(text) self.log.info("Selected element from menu: " + element) except: self.log.info("Could not select element: " + element) print_stack() def select_element_by_index(self, element, index=0): """Seleciona o elemento em um menu do tipo select pelo atributo texto @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param text(str) """ try: element = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(By.XPATH(element))) select = Select(element) select.select_by_index(index) self.log.info("Selected element from menu: " + element) except: self.log.info("Could not select element: " + element) print_stack() def is_element_present(self, element): """Verifica se o elemento está presente. Retorna true caso esteja e false caso não. @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento """ try: element = self.get_element(element) if element: 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 go_to_page(self, url): self.driver.get(url) def TakeScreenshot(self, resultMessage): """Tira screenshot da tela e salva no diretório do teste @param resultMessage(str): parte do nome do arquivo """ folder_name = os.path.join(str(pytest.time_start_format), self.context.scenario.name.replace('@','').replace(' ','').replace('-','_') + '/') pytest.screenshotDirectory = os.path.join('screenshots/', folder_name) file_name = str(datetime.now().strftime("%H_%M_%S")) + '_' + resultMessage.replace(' ', '_') + '.png' final_file = pytest.screenshotDirectory + file_name try: if not os.path.exists(pytest.screenshotDirectory): os.makedirs(pytest.screenshotDirectory) self.driver.save_screenshot(final_file) self.log.info("Screenshot saved to: " + final_file) except: self.log.error("### Exception Ocurred") print_stack()
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 saved to directory: " + destinationFile) allure.attach(self.driver.get_screenshot_as_png(), name=fileName, attachment_type=AttachmentType.PNG) 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 == "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 locatorType = locatorType.lower() try: 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 getElements(self, locator, locatorType="id"): element = None locatorType = locatorType.lower() try: byType = self.getByType(locatorType) element = self.driver.find_elements(byType, locator) self.log.info("Elements Found with locator: " + locator + " and locatorType: " + locatorType) except: self.log.info("Elements not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.click() self.log.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot click on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def sendKeys(self, data, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def clearField(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.clear() self.log.info("Cleared data on element with locator: " + locator + " locatorType: " + locatorType) except: self.log.info("Cannot clear data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def isElementPresent(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) if element is not None: self.log.info("Element Found") return True else: self.log.info("Element not found") return False except: self.log.info("Element not found") return False def areElementsPresent(self, locator, locatorType="id"): try: elementList = self.getElements(locator, locatorType) if 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 locatorType = locatorType.lower() try: byType = self.getByType(locatorType) self.log.info("Waiting for maximum:: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, timeout, poll_frequency=pollFrequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until(EC.element_to_be_clickable((byType, locator))) self.log.info("Element appeared on the web page") except: self.log.info("Element not appeared on the web page") print_stack() return element
class SeleniumDriver(): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): self.driver = driver def get_title(self): return self.driver.title def get_by_type(self, locator_type): #function gets the locator type and returns the right By.locator for it locator_type = locator_type.lower() if locator_type == "id": return By.ID elif locator_type == "name": return By.NAME elif locator_type == "xpath": return By.XPATH elif locator_type == "css": return By.CSS_SELECTOR elif locator_type == "class": return By.CLASS_NAME elif locator_type == "link": return By.LINK_TEXT else: self.log.info("Locator type " + locator_type + " not correct/supported") return False def get_element(self, locator, locator_type='id'): #function gets the By.locator type and the locator itself and finds the element element = None try: locator_type = locator_type.lower() by_type = self.get_by_type(locator_type) element = self.driver.find_element(by_type, locator) self.log.info('Element Found: ' + locator + " --- " + locator_type) except: self.log.info('Element not found: ' + locator + " --- " + locator_type) return element def is_element_present(self, locator, locator_type="id", element=None): try: if locator: element = self.get_element(locator, locator_type) if element is not None: self.log.info("Element present with locator: " + locator + " locator_type: " + locator_type) return True else: self.log.info("Element not present with locator: " + locator + " locator_type: " + locator_type) return False except: print("Element not found") return False def element_presence_check(self, locator, by_type): #checks whether there are elements under the given locator try: element_list = self.driver.find_elements(by_type, locator) if element_list > 0: return True else: self.log.info("Element not found") return False except: self.log.info('Element not found') return False def element_click(self, locator, locator_type="id", element=None): try: if locator: element = self.get_element(locator, locator_type) element.click() self.log.info("Clicked on element with locator: " + locator + " locator_type: " + locator_type) except: self.log.info("Cannot click on the element with locator: " + locator + " locator_type: " + locator_type) print_stack() def element_send(self, data, locator, locator_type="id", element=None): try: if locator: element = self.get_element(locator, locator_type) element.send_keys(data) self.log.info("Sent data on element with locator: " + locator + " locator_type: " + locator_type) except: self.log.info("Cannot send data on the element with locator: " + locator + " locator_type: " + locator_type) print_stack() def wait_for_element(self, locator, locator_type="id", timeout=10, poll_frequency=0.5): element = None try: by_type = self.get_by_type(locator_type) self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable") wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll_frequency, ignored_exceptions=[ NoSuchElementException, ElementNotVisibleException, ElementNotSelectableException ]) element = wait.until(ec.element_to_be_clickable( (by_type, 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 screenshot(self, result_message): file_name = result_message + "." + str(round( time.time() * 1000)) + ".png" screenshot_dir = "../screenshots/" dir_path = screenshot_dir + file_name current_dir = os.path.dirname(__file__) destination_file = os.path.join(current_dir, dir_path) destination_dir = os.path.join(current_dir, screenshot_dir) try: if not os.path.exists(destination_dir): os.makedirs(destination_dir) self.driver.save_screenshot(destination_file) self.log.info("Screenshot was saved to directory: " + destination_file) except: self.log.error("### Exception occurred when taking screenshot") print_stack() def web_scroll(self, direction="up"): if direction == "up": self.driver.execute_script("window.scrollBy(0, -1000);") if direction == "down": self.driver.execute_script("window.scrollBy(0, 1000);") def is_element_displayed(self, locator="", locator_type="id", element=None): is_displayed = False try: if locator: # This means if locator is not empty element = self.get_element(locator, locator_type) if element is not None: is_displayed = element.is_displayed() self.log.info("Element is displayed with locator: " + locator + " locator type: " + locator_type) else: self.log.info("Element not displayed with locator: " + locator + " locator type: " + locator_type) return is_displayed except: print("Element not found") return False def get_text(self, locator="", locator_type="id", element=None, info=""): try: if locator: self.log.debug("In locator condition") element = self.get_element(locator, locator_type) 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 get_element_list(self, locator, locator_type="id"): element = None try: locator_type = locator_type.lower() by_type = self.get_by_type(locator_type) element = self.driver.find_elements(by_type, locator) self.log.info("Element list found with locator: " + locator + " and locator_type: " + locator_type) except: self.log.info("Element list not found with locator: " + locator + " and locator_type: " + locator_type) return element def switch_to_frame(self, id="", name="", index=None): if id: self.driver.switch_to.frame(id) elif name: self.driver.switch_to.frame(name) else: self.driver.switch_to.frame(index) def switch_frame_by_index(self, locator, locator_type="xpath"): result = False try: iframe_list = self.get_element_list("//iframe", locator_type="xpath") self.log.info("Length of IFrame list: ") self.log.info(str(len(iframe_list))) for i in range(len(iframe_list)): self.switch_to_frame(index=iframe_list[i]) result = self.is_element_present(locator, locator_type) if result: self.log.info("IFrame index is: ") self.log.info(str(i)) break self.switch_to_default() return result except: print("IFrame index not found") return result def switch_to_default(self): self.driver.switch_to.default_content()
class BasePage(): log = cl.CustomLogger() def __init__(self, driver): self.driver = driver self.resultList = [] def takeScreenshot(self, resultMessage): folderName = str(pytest.time_start) + '/' + os.environ.get( 'PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0].split( '___')[0] + '/' pytest.screenshotDirectory = os.path.join('screenshots/', folderName) fileName = resultMessage.replace(' ', '_') + '_' + str( round(time.time() * 1000)) + '.png' finalFile = pytest.screenshotDirectory + fileName try: if not os.path.exists(pytest.screenshotDirectory): os.makedirs(pytest.screenshotDirectory) self.driver.save_screenshot(finalFile) self.log.info("Screenshot saved to: " + finalFile) except: self.log.error("### Exception Ocurred") print_stack() def go_to(self, url): self.driver.get(url) def GetElement(self, locator): element = None try: element = self.driver.find_element(*locator) self.log.info("Element found...") except: self.log.info("Element not found...") raise return element def GetElements(self, locator): elements = self.driver.find_elements(*locator) if len(elements) > 0: self.log.info("Element found...") return True else: self.log.info("Element not found...") return False def ClickOn(self, locator): try: element = self.GetElement(locator) element.click() self.log.info("Clicked on : " + str(locator[1])) except: self.log.info("Could not click on element: " + str(locator[1])) print_stack() raise def SendKeys(self, locator, text=""): try: element = self.GetElement(locator) element.send_keys(text) self.log.info("Keys sended to: " + str(locator[1])) except: self.log.info("Could not send keys to element: " + str(locator[1])) print_stack() raise def SelectElementByText(self, locator, text=""): try: element = self.GetElement(locator) select = Select(element) select.select_by_visible_text(text) self.log.info("Selected element from menu: " + str(locator[1])) except: self.log.info("Could not select element: " + str(locator[1])) print_stack() raise def IsElementPresent(self, locator): try: element = self.GetElement(locator) if element: 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 WaitElement(self, locator, timeout=20): element = None try: self.log.info("Waiting for :: " + str(timeout) + " :: seconds for element") element = WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located(locator)) except: self.log.info("Element not found: " + str(locator[1])) print_stack() return element def get_element_size(self, locator): el = self.GetElement(locator) return el.size def get_element_attribute(self, locator, attribute): el = self.GetElement(locator) return el.get_attribute(attribute) def setResult(self, result, resultMessage): self.takeScreenshot(resultMessage) try: if result: self.resultList.append("PASS") self.log.info("### VERIFICATION SUCCESSFULL:: " + resultMessage) else: self.resultList.append("FAIL") self.log.info("### VERIFICATION FAILED:: " + resultMessage) except: self.resultList.append("FAIL") self.log.info("### EXCEPTION OCCURRED:: " + 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(testName + " ###TEST FAILED...") self.resultList.clear() assert True == False else: self.log.info(testName + " ###TEST SUCCESSFUL...") self.resultList.clear() assert True == True
class BasePage: """Cria a BasePage com diversas funções built in @param driver: instância do webdriver passada por parametro """ log = cl.CustomLogger() def __init__(self, driver): self.driver = driver self.resultList = [] def GetByType(self, locator_type): """Cria um objeto do tipo da busca a que o elemento vai ser submetido @param locator_type(str): tipo de localizador do elemento """ locator_type = locator_type.lower() if safe_str_cmp(locator_type, "id"): return By.ID if safe_str_cmp(locator_type, "name"): return By.NAME if safe_str_cmp(locator_type, "xpath"): return By.XPATH else: self.log.info("Locator type " + locator_type + "not correct/support...") def TakeScreenshot(self, resultMessage): """Tira screenshot da tela e salva no diretório do teste @param resultMessage(str): parte do nome do arquivo """ folder_name = os.path.join( str(pytest.time_start_format), os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ') [0].split('___')[0] + '/') pytest.screenshotDirectory = os.path.join('screenshots/', folder_name) file_name = str( datetime.now().strftime("%H_%M_%S")) + '_' + resultMessage.replace( ' ', '_') + '.png' final_file = pytest.screenshotDirectory + file_name try: if not os.path.exists(pytest.screenshotDirectory): os.makedirs(pytest.screenshotDirectory) self.driver.save_screenshot(final_file) self.log.info("Screenshot saved to: " + final_file) except: self.log.error("### Exception Ocurred") print_stack() def GetElement(self, locator_type="xpath", locator=""): """Espera e retorna o elemento @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento """ element = None try: by_type = self.GetByType(locator_type) element = self.WaitElement(locator=locator, locator_type=by_type, timeout=50) self.log.info("Element found...") except: self.log.info("Element not found...") return element def ClickOn(self, locator_type="xpath", locator=""): """Clica no elemento @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento """ try: element = self.GetElement(locator_type, locator) element.click() self.log.info("Clicked on : " + locator + " with locatorType: " + locator_type) except (ElementNotClickableException, ElementNotFoundException): print_stack() raise def SendKeys(self, locator_type="xpath", locator="", text=""): """Envia texto ao elemento @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param text(str) """ try: element = self.GetElement(locator_type, locator) element.send_keys(text) self.log.info("Keys sent to: " + locator + " with locatorType: " + locator_type) except ElementNotFoundException: self.log.error("Could not send keys to element: " + locator + " with locatorType: " + locator_type) print_stack() raise def SelectElementByText(self, locator_type="xpath", locator="", text=""): """Seleciona o elemento em um menu do tipo select pelo atributo texto @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param text(str) """ try: element = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((locator_type, locator))) # element = self.GetElement(locator_type, locator) select = Select(element) select.select_by_visible_text(text) self.log.info("Selected element from menu: " + locator + " with locatorType: " + locator_type) except: self.log.info("Could not select element: " + locator + " with locatorType: " + locator_type) print_stack() def IsElementPresent(self, locator_type="xpath", locator=""): """Verifica se o elemento está presente. Retorna true caso esteja e false caso não. @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento """ try: element = self.GetElement(locator_type, locator) if element: 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 WaitElement(self, locator_type="xpath", locator="", timeout=10): """Espera o elemento ser exibido na tela pelo tempo definido pelo usuário @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param timeout(int): tempo máximo de espera """ element = None try: by_type = self.GetByType(locator_type) self.log.info("Waiting for :: " + str(timeout) + " :: seconds for element") element = WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located((by_type, locator))) except ElementNotFoundException: self.log.error("Element was not found...") raise except TimeoutException: self.log.error("Element was not found...") raise return element def SetResult(self, result, result_message): """Seta o resultado de determinado teste e tira screenshot @param result(bool): resultado do teste @param result_message(str): mensagem de verificação """ self.TakeScreenshot(result_message) try: if result: self.resultList.append("PASS") self.log.info("### VERIFICATION SUCCESSFULL:: " + result_message) else: self.resultList.append("FAIL") self.log.info("### VERIFICATION FAILED:: " + result_message) except: self.resultList.append("FAIL") self.log.info("### EXCEPTION OCCURRED:: " + result_message) def Mark(self, result, result_message): """Invoca set result. Novas ações serão implementadas @param result(bool): resultado do teste @param result_message(str): mensagem de verificação """ self.SetResult(result, result_message) def MarkFinal(self, test_name, result, result_message): """Seta o resultado de determinado teste, tira screenshot e finaliza o teste @param result(bool): resultado do teste @param result_message(str): mensagem de verificação """ self.SetResult(result, result_message) if "FAIL" in self.resultList: self.log.error(test_name + " ###TEST FAILED...") # self.resultList.clear() assert False else: self.log.info(test_name + " ###TEST SUCCESSFUL...") # self.resultList.clear() assert True """ Go to a web page @:param url: url page to be accessed """ def GoToPage(self, url): self.driver.get(url)
class TrustId210012Info(seleniumDriver): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver _first_name = 'first_name' _last_name = 'last_name' _home_phone = 'hphone' _email = 'email' _mailing_state = '//*[@id="mailing_state"]/optgroup[6]/option[48]' _ind_country = '//*[@id="ind_country"]/option[210]' _password = '******' _password_confirm = 'password_confirm' _question_1 = 'security_q1' _question_2 = 'security_q2' _question_3 = 'security_q3' _answer_1 = 'answer_1' _answer_2 = 'answer_2' _answer_3 = 'answer_3' _info_next = 'personal_info_confirm' _confirm_info = '/html/body/div[11]/div[3]/div/button[1]/span' def first_name(self, fname): self.send_keys(fname, self._first_name) def last_name(self, lname): self.send_keys(lname, self._last_name) self.send_keys(Keys.CONTROL, 'a') self.send_keys(Keys.CONTROL, 'c') def home_phone(self, hphone): self.send_keys(hphone, self._home_phone) def email_address(self, email): self.send_keys(email, self._email) def mailing_state(self): self.click_element(self._mailing_state, locatorType='xpath') def individual_country(self): self.click_element(self._ind_country, locatorType='xpath') def password_one(self, password): self.send_keys(password, self._password) def password_confirm(self, password): self.send_keys(password, self._password_confirm) def question_one(self, question): self.send_keys(question, self._question_1) def question_two(self, question): self.send_keys(question, self._question_2) def question_three(self, question): self.send_keys(question, self._question_3) def answer_one(self, answer): self.send_keys(answer, self._answer_1) def answer_two(self, answer): self.send_keys(answer, self._answer_2) def answer_three(self, answer): self.send_keys(answer, self._answer_3) def info_next(self): self.click_element(self._info_next) def confirm_info(self): self.click_element(self._confirm_info, locatorType='xpath') def info_one_yr_validity_option(self, fname, n, hphone, email, password, question, answer): self.first_name(fname) self.last_name(n) self.home_phone(hphone) self.email_address(email) self.mailing_state() self.individual_country() self.password_one(password) self.password_confirm(password) self.question_one(question) self.question_two(question) self.question_three(question) self.answer_one(answer) self.answer_two(answer) self.answer_three(answer) self.info_next() self.confirm_info()
class ElementNotClickableException(Exception): log = cl.CustomLogger() def __init__(self, locator, locator_type): self.log.error("[Exceptions] - Could not click on element: " + locator + " with locatorType: " + locator_type)
class LoginPage(BasePage): #getting the log in this class, so the name of the class will show up in logs log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__( driver ) # calling the __init__ method of the super class (Selenium Driver) and providing the driver to it self.driver = driver self.navigation = NavigationPage(self.driver) # Locators letscodeit _login_link = "Login" #locator: link _email_field = 'user_email' #locator: id _password_field = "user_password" #locator: id _login_button = "commit" #locator: name # Locators orangehrm _username_field_hrm = "//div[@id='divUsername']/input[@id='txtUsername']" #locator: xpath _password_field_hrm = "txtPassword" #locator: id _login_button_hrm = "btnLogin" #locator: id # Elements actions # letscodit def click_login_link(self): self.element_click(self._login_link, locator_type='link') def enter_email(self, email): self.send_Keys( email, self._email_field ) #not providing locator_type because using 'id' default one def clear_email(self): self.clear_field(self._email_field) def enter_password(self, password): self.send_Keys(password, self._password_field) def click_login_button(self): self.element_click(self._login_button, locator_type="name") # hrm def enter_username_hrm(self, username): self.send_Keys(username, self._username_field_hrm, locator_type="xpath") def clear_username_hrm(self): self.clear_field(self._username_field_hrm, locator_type="xpath") def clear_password_hrm(self): self.clear_field(self._password_field_hrm, locator_type="id") def enter_password_hrm(self, password): self.send_Keys(password, self._password_field_hrm) def click_login_button_hrm(self): self.element_click(self._login_button_hrm) # Main functions # letscodit def go_to_login_page(self): self.click_login_link() def login(self, email='', password='' ): #parameters are optional e.g. for testing empty credentials self.clear_email() self.enter_email(email) self.enter_password(password) self.click_login_button() def verify_redirected_to_login_page(self): result = self.is_element_present(self._login_button, locator_type="name") return result def verify_login_successful(self): result = self.is_element_present( "//div[@id='navbar']//li[@class='dropdown']", locator_type="xpath") return result # returns boolean def verify_login_failed(self): result = self.is_element_present( "//div[contains(text(), 'Invalid email or password')]", locator_type="xpath") return result def verify_login_title(self): return self.verify_page_title(expected_title="Let's Kode") def logout(self): self.navigation.navigate_profile_icon() element = self.wait_for_element(locator='//div//a[@href="/sign_out"]', locator_type='xpath', pollFrequency=1) self.element_click(element=element) # hrm def login_hrm(self, username='', password=''): self.clear_username_hrm() self.clear_password_hrm() self.enter_username_hrm(username) time.sleep(2) self.enter_password_hrm(password) time.sleep(2) self.click_login_button_hrm() def verify_login_successfull_hrm(self): result = self.is_element_present( "//div[@id='branding']//a[text()='Welcome User']", locator_type='xpath') return result # returns boolean def verify_login_failed_hrm(self): result = self.is_element_present( "//div//span[text()='Invalid credentials']", locator_type="xpath") return result def verify_empty_username_login_failed_hrm(self): result = self.is_element_present( "//div[@id='divLoginButton']//span[text()='Username cannot be empty']", locator_type="xpath") return result def verify_login_title_hrm(self): return self.verify_page_title(expected_title="OrangeHRM") def logout_hrm(self): self.navigation.logout() # 4. observe recent changed and remove that is not needed
class SQLException(Exception): log = cl.CustomLogger() def __init__(self, query): self.log.error("[Exceptions] - Error while execution the sql query: " + str(query))
class LoginPage(BasePage): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators _login_link = "Login" _email_field = "user_email" _password_field = "user_password" _login_button = "commit" # def getLoginLink(self): # return self.driver.find_element(By.LINK_TEXT, self._login_link) # # def getEmailField(self): # return self.driver.find_element(By.ID, self._email_field) # # def getPasswordField(self): # return self.driver.find_element(By.ID, self._password_field) # # def getLoginButton(self): # return self.driver.find_element(By.NAME, self._login_button) # Actions def clickLoginLink(self): self.elementClick(self._login_link, locatorType="linktext") def enterEmail(self, email): self.sendKeys(email, self._email_field) def enterPassword(self, password): self.sendKeys(password, self._password_field) def clickLoginButton(self): self.elementClick(self._login_button, locatorType="name") def clearLoginFields(self): self.clearField(self._email_field) self.clearField(self._password_field) # Methods def login(self, email="", password=""): self.clickLoginLink() self.enterEmail(email) self.enterPassword(password) self.clickLoginButton() def verifyLoginSuccessful(self): result = self.isElementPresent( "//*[@id='navbar']//span[text()='Test Account']", locatorType="xpath") return result def verifyLoginFailed(self): result = self.isElementPresent( "//div[contains(text(), 'Invalid email or password.')]", locatorType="xpath") return result def verifyLoginTitle(self): return self.verifyPageTitle("Let's Kode It")
class ElementNotFoundException(Exception): log = cl.CustomLogger() def __init__(self, element): self.log.error("[Exceptions] - Element not found: " + str(element))
class TrustId210012Payment(seleniumDriver): log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) self.driver = driver _select_cc = 'ccPaymentType' _cc_number = 'creditCardNum' _security_code = 'card_security_code' _exp_month = '//*[@id="cc_exp_mm"]/option[7]' _exp_year = '//*[@id="cc_exp_yyyy"]/option[7]' _billing_address = 'billing_address1' _billing_city = 'billing_city' _billing_zip = 'billing_postal_code' _subscriber_agreement = 'Subscriber Agreement' # link text _subscriber_box = 'agree_checkbox' _submit_app = '//*[@id="next"]' def cc_button(self): self.clickElement(self._select_cc) def cc_payment(self, ccNumber): self.sendKeys(ccNumber, self._cc_number) def security_code(self, ccCode): self.sendKeys(ccCode, self._security_code) def exp_month(self): self.clickElement(self._exp_month, locatorType='xpath') def exp_year(self): self.clickElement(self._exp_year, locatorType='xpath') def billing_address(self, billAddress): self.sendKeys(billAddress, self._billing_address) def billing_city(self, billCity): self.sendKeys(billCity, self._billing_city) def billing_zip(self, billZip): self.sendKeys(billZip, self._billing_zip) def subscriber_agreement(self): self.clickElement(self._subscriber_agreement, locatorType='link') def subscriber_box(self): self.clickElement(self._subscriber_box) def submit_billing_info(self): self.clickElement(self._submit_app, locatorType='xpath') def payment_one_yr_validity_option(self, ccNumber, ccCode, billAddress, billCity, billZip): self.cc_button() self.cc_payment(cc_number) self.security_code(cc_code) self.exp_month() self.exp_year() self.billing_address(bill_address) self.billing_city(bill_city) self.billingZip(bill_zip) self.subscriber_agreement() def submit_application(self): self.subscriber_box() self.submit_billing_info()
class NavigationPage(BasePage): #page: https://letskodeit.teachable.com/courses #getting the log in this class, so the name of the class will show up in logs log = cl.CustomLogger(logging.DEBUG) def __init__(self, driver): super().__init__( driver ) # calling the __init__ method of the super class (Selenium Driver) and providing the driver to it self.driver = driver # Locators letscodeit _my_courses = '//a[@href="/courses/enrolled"]' _all_courses = '//a[@href="/courses"]' _practice = '//a[@href="/pages/practice"]' _profile_icon = '//img[@class="gravatar"]' _letskodeit_icon = '//div/a[@class="navbar-brand header-logo"]' # Locators orangehrm #TODO #_welcome_user = "******" #id _welcome_user = "******" _logout = "//div[@id='welcome-menu']//a[text()='Logout']" #_logout = "//div//a[text()='Logout']" # Elements actions # letscodit def navigate_to_all_courses(self): self.element_click(self._all_courses, locator_type='xpath') def navigate_to_my_courses(self): self.element_click(self._my_courses, locator_type='xpath') def navigate_to_practice(self): self.element_click(self._practice, locator_type='xpath') def navigate_profile_icon(self): element = self.wait_for_element(self._profile_icon, locator_type='xpath', pollFrequency=1) self.element_click(element=element) def navigate_to_letskodeit_icon(self): self.element_click(self._letskodeit_icon, locator_type='xpath') # hrm def select_welcome_user(self): welcome_user_element = self.driver.find_element_by_xpath( self._welcome_user) #used ActionChains because regular click() was not working on this element ActionChains(self.driver).move_to_element(welcome_user_element).click( welcome_user_element).perform() def select_logout(self): logout_element = self.wait_for_element(locator=self._logout, locator_type='xpath', pollFrequency=1) self.element_click(element=logout_element) # Main functions # letscodit # hrm def logout(self): self.select_welcome_user() self.select_logout()