class Util(object): log = logger = LogGen.loggen() 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 Login_page(BasePage): textbox_username_id = "Email" textbox_password_id = "Password" button_login_xpath = "//input[@class='button-1 login-button']" link_logout_linktext = "Logout" text_invalidlogin_xpath = "//div[contains(text(),'Login was unsuccessful. Please correct the errors and try again.')]" text_usernametext_xpath = "//li[contains(text(),'John Smith')]" logger = LogGen.loggen() def clear_username(self): self.driver.find_element_by_id(self.textbox_username_id).clear() def clear_password(self): self.driver.find_element_by_id(self.textbox_password_id).clear() def enterEmail(self, username): self.sendKeys(username, self.textbox_username_id) def enterPassword(self, password): self.sendKeys(password, self.textbox_password_id) def clickLoginButton(self): self.elementClick(self.button_login_xpath, locatorType="xpath") def clickLogoutLink(self): self.elementClick(self.link_logout_linktext, locatorType="link") def login(self, username="", password=""): self.clear_username() self.clear_password() self.enterEmail(username) self.enterPassword(password) self.clickLoginButton() def logout(self): self.clickLogoutLink() def verify_login_failed(self): resp = self.isElementPresent(self.text_invalidlogin_xpath, locatorType="xpath") return resp def verify_login_successful(self): result = self.isElementPresent(self.text_usernametext_xpath, locatorType="xpath") return result def verifyTitle(self): return self.verifyPageTitle("Dashboard / nopCommerce administration")
class TestStatus(SeleniumDriver): logger = LogGen.loggen() def __init__(self, driver): super().__init__(driver) self.resultlist = [] def set_result(self, result, result_message): try: if result is not None: if result: self.resultlist.append("PASS") self.logger.info("### Verification Successful ::" + result_message) else: self.resultlist.append("FAIL") self.logger.info("### Verification Failed ::" + result_message) self.screenShot(result_message) else: self.resultlist.append("FAIL") self.logger.error("### Verification Failed ::" + result_message) self.screenShot(result_message) except: self.resultlist.append("FAIL") self.logger.error("### Exception Occurred !!!") self.screenShot(result_message) def mark(self, result, result_message): """ Mark the result of the verification point in a test case """ self.set_result(result, result_message) def final_mark(self, testname, result, result_message): """ 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.set_result(result, result_message) if "FAIL" in self.resultlist: self.logger.error(testname + " ### TEST FAILED") self.resultlist.clear() assert True == False else: self.logger.error(testname + " ### TEST PASSED") self.resultlist.clear() assert True == True
class Test_001_Login: baseURL = ReadConfig.get_application_url() username = ReadConfig.get_username() password = ReadConfig.get_password() logger = LogGen.loggen() path_to_screenshots = os.path.join('.', 'screenshots') def test_home_page_title(self, setup): self.logger.info("***Test_001_Login***") self.logger.info("***Verifying Home Page Title***") self.driver = setup self.driver.get(self.baseURL) actual_title = self.driver.title if actual_title == "Your store. Login": assert True self.logger.info("*** Home page title test is passed ***") self.driver.close() else: path_to_failed_home_page_title_test = os.path.join(self.path_to_screenshots, 'test_home_page_title_failed.png') self.driver.save_screenshot(path_to_failed_home_page_title_test) self.logger.error("*** Home page title test is failed ***") self.driver.close() assert False def test_login(self, setup): self.logger.info("***Verifying Login test***") self.driver = setup self.driver.get(self.baseURL) self.lp = LoginPage(self.driver) self.lp.set_user_name(self.username) self.lp.set_password(self.password) self.lp.click_login_button() actual_title = self.driver.title if actual_title == "Dashboard / nopCommerce administration": self.logger.info("*** Login test is passed ***") self.driver.close() assert True else: path_to_failed_login_test = os.path.join(self.path_to_screenshots, 'test_login_failed.png') self.driver.save_screenshot(path_to_failed_login_test) self.logger.error("*** Login test is failed ***") self.driver.close() assert False
class SeleniumDriver(): logger = LogGen.loggen() def __init__(self, driver): self.driver = driver 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.logger.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.logger.info("Element Found with locator: " + locator + " and locatorType: " + locatorType) except: self.logger.info("Element not found with locator: " + locator + " and locatorType: " + locatorType) return element def elementClick(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) element.click() self.logger.info("Clicked on element with locator: " + locator + " locatorType: " + locatorType) except: self.logger.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.logger.info("Sent data on element with locator: " + locator + " locatorType: " + locatorType) except: self.logger.info("Cannot send data on the element with locator: " + locator + " locatorType: " + locatorType) print_stack() def isElementPresent(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) if element is not None: self.logger.info("Element Found") return True else: self.logger.info("Element not found") return False except: self.logger.info("Element not found") return False def elementPresenceCheck(self, locator, byType): try: elementList = self.driver.find_elements(byType, locator) if len(elementList) > 0: self.logger.info("Element Found") return True else: self.logger.info("Element not found") return False except: self.logger.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.logger.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.logger.info("Element appeared on the web page") except: self.logger.info("Element not appeared on the web page") print_stack() return element 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.logger.info("Screenshot save to directory: " + destinationFile) except: self.logger.error("### Exception Occurred when taking screenshot") print_stack()
class Test_001_Search: logger = LogGen.loggen() # TODO сделать логгер в режиме добавления записей logger.info("Test_001_Search") path_to_screenshots = os.path.join('.', 'screenshots') # TODO добавить скриншоты yandex_search_URL = ReadConfig.get_yandex_search_url() def test_check_search_box(self, setup): self.logger.info("Checking if a search field exists") self.driver = setup self.driver.get(self.yandex_search_URL) self.yp = YandexSearchPage(self.driver) try: self.yp.find_search_box() self.logger.info( f"Test passed: Search field found by {self.yp.search_box_locator}" ) time.sleep(2) except TimeoutException: self.logger.error( f"Test failed: Search field not found by {self.yp.search_box_locator} for {self.yp.delay} seconds" ) finally: self.driver.quit() self.logger.info("---------------") def test_suggests_in_search_box(self, setup): self.logger.info("Checking suggests in search field") self.driver = setup self.driver.get(self.yandex_search_URL) self.yp = YandexSearchPage(self.driver) try: self.yp.set_text_to_search_box('Тензор') self.yp.find_suggest_box() self.yp.send_enter_to_search_box() request_results = self.yp.get_request_results() if request_results: self.search_href_in_list_of_links( request_results=request_results, link_to_search=r"https://tensor.ru/", number_results=5) else: self.logger.error( "Test failed: There is no links in result of search") except TimeoutException: # TODO добавить отработку различных ненайденок self.logger.error( f"Test failed: Suggest field not found by {self.yp.suggest_box_locator} for {self.yp.delay} seconds" ) finally: self.driver.quit() self.logger.info("---------------") def search_href_in_list_of_links(self, request_results, link_to_search: str, number_results: int): list_of_links = [] for element in request_results: element_with_link = element.find_element_by_tag_name('a') link = element_with_link.get_attribute("href") list_of_links.append(link) if link_to_search in list_of_links: index = list_of_links.index(link_to_search) + 1 if index <= number_results: self.logger.info( f"Test passed: {link_to_search} find in {index} request position" ) else: self.logger.error( f"Test failed: {link_to_search} find, but in {index} request position" ) else: self.logger.error( f"Test failed: {link_to_search} did not find in request")
class Test_002_Pictures: logger = LogGen.loggen() logger.info("Test_002_Pictures") path_to_screenshots = os.path.join('.', 'screenshots') # TODO добавить скриншоты yandex_search_URL = ReadConfig.get_yandex_search_url() yandex_pictures_URL = ReadConfig.get_yandex_pictures_url() def test_yandex_pictures_section_exist(self, setup): self.logger.info("Checking if a Pictures section exists") self.driver = setup self.driver.get(self.yandex_search_URL) self.yp = YandexSearchPage(self.driver) try: self.yp.find_yandex_pictures_section() self.logger.info( f"Test passed: Pictures section found by {self.yp.pictures_section_locator}" ) except TimeoutException: self.logger.error( f"Test failed: Pictures section not found by {self.yp.pictures_section_locator} for {self.yp.delay} seconds" ) finally: self.driver.quit() self.logger.info("---------------") def test_yandex_pictures_page_exist(self, setup): self.logger.info("Checking yandex pictures page exist") self.driver = setup self.driver.get(self.yandex_search_URL) self.yp = YandexSearchPage(self.driver) try: pictures_section = self.yp.find_yandex_pictures_section() pictures_section.click() self.yp.find_yandex_pictures_title() self.logger.info( f"Test passed: successful transition to the https://yandex.ru/images/" ) except TimeoutException: self.logger.error( f"Test failed: can't find picture title by {self.yp.pictures_title_locator} for {self.yp.delay} seconds" ) assert False finally: self.driver.quit() self.logger.info("---------------") def test_yandex_pictures_first_category(self, setup): self.logger.info("Checking the correctness of image search") self.driver = setup self.driver.get(self.yandex_pictures_URL) self.yp = YandexPicturesPage(self.driver) try: first_popular_request = self.yp.find_first_popular_request() first_popular_request.click() expected_text = first_popular_request.text picture_search_box = self.yp.find_picture_search_box() actual_text = picture_search_box.get_attribute("value") if expected_text == actual_text: self.logger.info( f"Test passed: the text of the first category matches with the search text" ) else: self.logger.error( f"Test failed: the text of the first category does not match the search text" ) except TimeoutException: self.logger.error( f"Test failed: can't find element {self.yp.pictures_title_locator} for {self.yp.delay} seconds" ) assert False finally: self.driver.quit() self.logger.info("---------------")
class Test_002_DDT_Login: baseURL = ReadConfig.get_application_url() path_to_excel_data = os.path.join('.', 'test_data', 'login_data.xlsx') logger = LogGen.loggen() def test_login_ddt(self, setup): self.logger.info("***Test_002_DDT_Login***") self.logger.info("***Verifying Login DDT test***") self.driver = setup self.driver.get(self.baseURL) self.lp = LoginPage(self.driver) self.rows = excel_utils.get_row_count(self.path_to_excel_data, 'Лист1') print('Number of Rows i a Excel: ', self.rows) status_list = [] for row in range(2, self.rows + 1): self.user = excel_utils.read_data(self.path_to_excel_data, 'Лист1', row, 1) self.password = excel_utils.read_data(self.path_to_excel_data, 'Лист1', row, 2) self.exp = excel_utils.read_data(self.path_to_excel_data, 'Лист1', row, 3) self.lp.set_user_name(self.user) self.lp.set_password(self.password) self.lp.click_login_button() time.sleep(2) actual_title = self.driver.title expected_title = "Dashboard / nopCommerce administration" if actual_title == expected_title: if self.exp == 'Pass': self.logger.info('*** Passed ***') self.lp.click_logout_button() status_list.append('Pass') elif self.exp == 'Fail': self.logger.error('*** Failed ***') self.lp.click_logout_button() status_list.append('Fail') elif actual_title != expected_title: if self.exp == 'Pass': self.logger.error('*** Failed ***') status_list.append('Fail') elif self.exp == 'Fail': self.logger.info('*** Passed ***') status_list.append('Pass') if 'Fail' not in status_list: self.logger.info('*** Login DDT test is passed ***') self.driver.close() assert True else: self.logger.error('*** Login DDT test is failed ***') self.driver.close() assert False self.logger.info('*** End of Login DDT Test ***') self.logger.info('\n')