def click_submenu(parent, element): """ @summary: click on the sub-element specified of the parent specified @param: parent: format of parent: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") @param: element: format of element: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") """ try: """ parent_elem = find_element(parent[0], parent[1]) mov = ActionChains(Context().browser).move_to_element(parent_elem) mov.perform() wait_until(element[1],120,1,element[0]) elem = find_element(element[0], element[1]) elem.click() Context().logger.debug("Clicking on ({0})".format(element[1])) """ parent_elem = find_element(parent[0], parent[1]) parent_elem.click() wait_until(element[1], 120, 1, element[0]) elem = find_element(element[0], element[1]) elem.click() Context().logger.debug("Clicking on ({0})".format(element[1])) except: Context().logger.error("Cannot click on the element ({0})".format(element[1])) take_screenshot("Exception.png") raise
def reinstall_shop(self, var_test): new_store = False Context().logger.info("Reinstallation of an existing store") try: new_store = installationScreen().reinstall_shop(var_test) Context().logger.info("reinstallation is ok") except: Context().logger.warning("Issue to reinstall the store") return new_store
def install_shop(self, var_test): new_store = False Context().logger.info("Creation of a new store") try: new_store = installationScreen().install_shop(var_test) Context().logger.info("New store is created") except: Context().logger.warning("Issue to create the new store") return new_store
def drag_and_drop(source, xoffset, yoffset): actions = [] if source: actions.append(lambda: Context().browser.execute(Command.MOVE_TO, {'element': source.id})) actions.append(lambda: Context().browser.execute(Command.MOUSE_DOWN, {})) actions.append( lambda: Context().browser.execute(Command.MOVE_TO, {'xoffset': int(xoffset), 'yoffset': int(yoffset)})) actions.append(lambda: Context().browser.execute(Command.MOUSE_UP, {})) for action in actions: action() return actions
def add_employee(self,var_test): found_employee = False try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) try: adminPageScreen().go_to_admin_menu('Preferences','Preferences_employees') Context().logger.info("Go on Back-office - employees menu") except: Context().logger.warning("Issue to go on Back-office - employees menu") raise time.sleep(3) try: new_employee = adminemployeeScreen().add_employees(var_test) Context().logger.info("the new employee has been added") except: Context().logger.warning("Issue to add the new employee") raise try: found_employee = adminemployeeScreen().check_employee(new_employee) Context().logger.info("Find informations about the employee") except: Context().logger.warning("Issue to find informations about the employee") raise time.sleep(3) try: loginAdminPageScreen().disconnect() except: Context().logger.warning("Issue with log out") raise return found_employee except: return False raise
def catalog(self): Logger().info("Go to the catalog menu") try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) adminPageScreen().go_to_admin_menu('Catalog') time.sleep(5) Logger().success("Go to the catalog menu") except: raise
def orders(self): Logger().info("Go to the orders menu") try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) adminPageScreen().go_to_admin_menu('CustomerThreads', 'CustomerThreads_return') time.sleep(5) Logger().success("Go to the orders menu") except: raise
def assert_that(predicate, error_message, debug_message=None): """ @summary Given a predicate: throws an exception containing a user defined error message @param predicate: a condition that will valued either as True or False @param error_message: when predicate -> False, an exception is raised an contain an error message @return None @throws Test.TestAssertException """ if not predicate: ui.take_screenshot() Context().logger.error(error_message) raise Test.TestAssertException(error_message) if debug_message is not None: Context().logger.debug("assertion passed : " + debug_message)
def is_existant(element): """ @summary: check if an element exists from the method and element's information given in the parameter of the function @param: method: xpath or css @param: element: format of element, e.g.: "//[@id='login']" or "#login" """ try: elet = "" if element[0] == "xpath": elet = Context().browser.find_element_by_xpath(element[1]) elif element[0] == "css": elet = Context().browser.find_element_by_css_selector(element[1]) return True except: return False
def set_text_script(element, value): """ @summary: fill the specified element with the value in parameter by a script @param: element: format of element: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") @param: value: value that you want to put in the element """ if value != "": try: elem = find_element(element[0], element[1]) Context().browser.execute_script("arguments[0].value = '" + value + "';", elem) Context().logger.debug("Filled the element ({0}) with ({1})".format(element[1], value)) except: Context().logger.error("Cannot fill the element ({0}) with ({1})".format(element[1], value)) take_screenshot("Exception.png") raise
def open_all_controller(self): open_controllers = True try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) try: adminPageScreen().open_all_contoller() Context().logger.info("Open all controllers") except: Context().logger.warning("Issue to open all controllers") open_controllers = False raise return open_controllers except: return False
def click(element, test=None): """ @summary: click on the element specified @param: element: format of element: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") """ try: elem = find_element(element[0], element[1]) Context().browser.execute_script("window.scrollTo(0, " + str(elem.location['y'] - 150) + ")") elem.click() Context().logger.debug("Clicking on ({0})".format(element[1])) except: if test == None: Context().logger.error("Cannot click on the element ({0})".format(element[1])) take_screenshot("Exception.png") else: Context().logger.debug("Cannot click on the element ({0})".format(element[1])) raise
def modify_product(self, var_test): found_product = False try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) try: adminPageScreen().go_to_admin_menu('Catalog', 'Catalog_products') Context().logger.info("Go on catalog - products menu") except: Context().logger.warning( "Issue to go on catalog - products menu") raise time.sleep(3) try: found_product = catalogProductScreen().modify_product(var_test) Context().logger.info("the product has been modified") except: Context().logger.warning("Issue to modify the product") raise time.sleep(3) try: loginAdminPageScreen().disconnect() except: Context().logger.warning("Issue with log out") raise return found_product except: raise
def add_product(self, var_test): new_product = False try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) try: adminPageScreen().go_to_admin_menu('Catalog') Context().logger.info("Go on catalog - products menu") except: Context().logger.warning( "Issue to go on catalog - products menu") raise time.sleep(3) new_product = catalogProductScreen().add_product(var_test) if new_product == True: Context().logger.info("the new product has been added") else: Context().logger.warning("Issue to add the new product") time.sleep(5) try: loginAdminPageScreen().disconnect(product_page=False) except: Context().logger.warning("Issue with log out") raise return new_product except: raise
def product_catalog_sort(self, var_test): new_product = False try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) try: adminPageScreen().go_to_admin_menu('Catalog') Context().logger.info("Go on catalog - products menu") except: Context().logger.warning( "Issue to go on catalog - products menu") raise time.sleep(3) try: new_product = catalogProductScreen().product_catalog_sort( var_test) Context().logger.info("the catalog has been checked") except: Context().logger.warning("Issue to check the category") raise time.sleep(3) try: loginAdminPageScreen().disconnect(product_page=False) except: Context().logger.warning("Issue with log out") raise return new_product except: raise
def sort_modules(self, var_test): module_check = False try: loginAdminPageScreen().connect(Context().environment.login, Context().environment.password) time.sleep(3) try: adminPageScreen().go_to_admin_menu_by_move( 'Modules', 'Modules_modules') Context().logger.info("Go on modules - modules menu") except: Context().logger.warning( "Issue to go on modules - modules menu") raise time.sleep(3) try: module_check = ModuleScreen().sort_modules(var_test) Context().logger.info("the module was found") except: Context().logger.warning("Issue with the module test") raise time.sleep(3) try: loginAdminPageScreen().disconnect(product_page=False) except: Context().logger.warning("Issue with log out") raise return module_check except: raise
def upload_file(element, fileUpload, is_submit=False): """ """ img_selected = os.path.abspath(os.curdir) + "/datasets/" + fileUpload elem = find_element(element[0], element[1]) Context().browser.execute_script('arguments[0].setAttribute("style", "")', elem) elem.send_keys(img_selected) if is_submit != False: elem.submit()
def find_elements(method, element, not_log=False): """ @summary: find an element with the method and element's information given in the parameter of the function @param: method: xpath or css @param: element: format of element, e.g.: "//[@id='login']" or "#login" """ try: elet = "" if method == "xpath": elet = Context().browser.find_elements_by_xpath(element) elif method == "css": elet = Context().browser.find_elements_by_css_selector(element) return elet except: if not_log == False: Context().logger.error("Cannot find the element ({0})".format(element)) take_screenshot("Exception.png") raise
def choose_a_dd_value(element, desired_value): """ @summary: Method used to check for occurence of a value in the DD, if not selects a random value. @param element: DD items in a list format @param desired_value: Value to be searched @return: A True flag indicating a successful click """ if desired_value != "": found = option_selector(element, desired_value) if found is not None: try: new_element = ("css", found) click(new_element) Context().logger.debug("Clicking on ({0})".format(new_element)) return True except: Context().logger.error("Cannot click on the element ({0})".format(element[1])) take_screenshot("Exception.png") raise
def wait_loader(predicate, timeout_seconds, period=0.25): """ @summary Call repeatedly the predicate until it returns true or timeout_seconds passed. @param predicate: a condition, modelized as a callable, that will valued either as True or False @param timeout_seconds: the timeout in second @param period: the time to sleep between 2 calls to predicate. Defaults to 0.25s. @return True if a call to predicate returned True before timeout_seconds passed, else False """ Context().logger.info("waiting until predicate is true for {end} seconds".format(end=timeout_seconds)) ultimatum = time.time() + timeout_seconds while time.time() < ultimatum: Context().logger.debug("checking predicate for wait until : {spent} / {end}".format( spent=str(time.time() - (ultimatum - timeout_seconds)), end=timeout_seconds)) try: Context().browser.find_element_by_xpath(predicate).is_displayed() Context().logger.info("Loader is display") except: return True time.sleep(period) return False
def set_text(element, value, clear=None): """ @summary: fill the specified element with the value in parameter @param: element: format of element: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") @param: value: value that you want to put in the element """ if value != "": try: elem = find_element(element[0], element[1]) if clear == True: elem.clear() if type(value) != int: if value.startswith('#') and value.endswith('#'): from commons.Dataset import Dataset value = Dataset().helper_eval(value) elem.send_keys(value) Context().logger.debug("Filled the element ({0}) with ({1})".format(element[1], value)) except: Context().logger.error("Cannot fill the element ({0}) with ({1})".format(element[1], value)) take_screenshot("Exception.png") raise
def wait_until(predicate, timeout_seconds, period=0.25, show_log=True): """ @summary Call repeatedly the predicate until it returns true or timeout_seconds passed. @param predicate: a condition, modelized as a callable, that will valued either as True or False @param timeout_seconds: the timeout in second @param period: the time to sleep between 2 calls to predicate. Defaults to 0.25s. @return True if a call to predicate returned True before timeout_seconds passed, else False """ if show_log: Context().logger.info( "waiting until predicate is true for {end} seconds".format( end=timeout_seconds)) ultimatum = time.time() + timeout_seconds while time.time() < ultimatum: Context().logger.debug( "checking predicate for wait until : {spent} / {end}".format( spent=str(time.time() - (ultimatum - timeout_seconds)), end=timeout_seconds)) if predicate(): return True time.sleep(period) return False
def get_attribute(element, attribute): """ @summary: find the class of an element @param: element: format of element, e.g.: "//[@id='login']" or "#login" @return: class of the element """ try: elem = find_element(element[0], element[1]) return elem.get_attribute(attribute) except: Context().logger.error("cannot find the text element ({0})".format(element[1])) take_screenshot("Exception.png") raise
def checkbox(element, status_wanted): """ @summary: click on the element specified @param: element: format of element: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") """ try: if status_wanted == "1": status_wanted = "true" status_log = "Check" else: status_wanted = "None" status_log = "Uncheck" elem = find_element(element[0], element[1]) status = get_attribute(element, "checked") if str(status) != status_wanted: Context().browser.execute_script("window.scrollTo(0, " + str(elem.location['y'] - 150) + ")") elem.click() Context().logger.debug(status_log + "({0})".format(element[1])) except: Context().logger.error("Cannot check/uncheck the element ({0})".format(element[1])) take_screenshot("Exception.png") raise
def native_set_text(element, text): """ @summary: type a string using the OS native events @param: element: format of element: ('method','identification'), e.g.: ("xpath","//[@id='login']") or ("css","#login") @param: text: str, the text to type """ if text != "": try: elem = find_element(element[0], element[1]) elem.click() except: Context().logger.error("Cannot click on the element ({0})".format(element[1])) take_screenshot("Exception.png") raise stream = keyboard_stream(text) try: for val in stream: SendInput(val) Context().logger.debug("Filled the element ({0}) with ({1})".format(element[1], text)) except: Context().logger.error("Cannot fill the element ({0}) with ({1})".format(element[1], text)) take_screenshot("Exception.png")
def take_screenshot(filename='screenshot.png'): """ @summary: Take a screenshot of the page displayed in the active webdriver instance @param filename: str, optional. The name of the file. """ context = Context() timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') config = Configuration() if config.function_test != None: filename = str(config.browser) + "-" + str(config.datasets_file_name).replace("'", "").replace("[", "").replace( "]", "") + '-' + str(config.function_test) + '_' + timestamp + '_' + filename else: filename = str(config.browser) + '-' + str(config.datasets_file_name).replace("'", "").replace("[", "").replace( "]", "") + '-' + str(config._fct_test) + '_' + timestamp + '_' + filename if Configuration().job_jenkins == None: context.browser.save_screenshot(os.path.join('test_results', 'screenshots', filename)) context.logger.info("Screenshot taken as " + filename) else: finale_path = "C:\jenkins\workspace\\" + Configuration().job_jenkins + "\Browser\\" + Context().browserName + "\Function\\" + Configuration().function_test + "\\" + Configuration().build_jenkins os.makedirs(finale_path, exist_ok=True) Context().browser.save_screenshot(os.path.join(finale_path, filename)) context.logger.info("Screenshot taken as " + finale_path + "\\" + filename)
def open_all_contoller(self): f = open("datasets/controllers.txt", "r") storename = "/" if Configuration().storename != None: storename = Configuration().storename + storename for l in f: if Configuration().vm == None: url = Context().environment.url.replace( 'str(i)', storename).replace( 'str(j)', 'localhost') + "?controller=" + l else: url = Context().environment.url.replace( 'str(i)', storename).replace( 'str(j)', Configuration().vm) + "?controller=" + l Context().goto_url(url) time.sleep(3) if (ui.is_visible(self._objects["Error_alert"])): if (ui.is_existant(self._objects["Error_message"])): if (ui.get_text(self._objects["Error_message"]) == "The controller %s is missing or invalid." % (l.strip())): Context().logger.info("%s controller is OK" % (l.strip())) else: Context().logger.error("%s controller is broken" % (l.strip())) else: Context().logger.error("%s controller is broken" % (l.strip())) else: if (not ui.is_visible(self._objects["General_loginHeader"]) and not ui.is_visible( self._objects["General_logoPrestaShop"]) and not ui.is_visible( self._objects["General_logoPrestaShopModules"])): Context().logger.error("%s controller is broken" % (l.strip())) else: Context().logger.info("%s controller is OK" % (l.strip()))
def add_employees(self, var_test): if ui.get_text(self._objects['employees_table_number']) == "1": max_id = ui.get_text( self._objects['employees_table_check']).split(" ")[0] else: ui.click(self._objects['employees_table_id_desc']) time.sleep(3) max_id = ui.get_text( self._objects['employees_table_check']).split(" ")[0] ui.click(self._objects['add_employees']) ui.wait_until(self._objects['add_employee_firstname'][1], 60, 1, self._objects['add_employee_firstname'][0]) ui.set_text(self._objects['add_employee_firstname'], var_test.get("firstname")) ui.set_text(self._objects['add_employee_lastname'], var_test.get("lastname")) false_random = int(max_id) + 1 my_email = (Context().browser.name + str(false_random) + var_test.get("email")).replace(" ", "") ui.set_text(self._objects['add_employee_email'], my_email) ui.set_text(self._objects['add_employee_password'], var_test.get("password")) if var_test.get("prestanl") == "yes": ui.click(self._objects['add_employee_nl_on']) if var_test.get("prestanl") == "no": ui.click(self._objects['add_employee_nl_off']) if var_test.get("active") == "yes": ui.click(self._objects['add_employee_active_on']) if var_test.get("active") == "no": ui.click(self._objects['add_employee_active_off']) my_profile = ("xpath", "//*[@id = 'id_profile']/option[text()='" + var_test.get("profile") + "']") ui.click(my_profile) ui.click(self._objects['add_employee_save']) time.sleep(3) my_employee = {} my_employee.update({'old_max_id': max_id}) my_employee.update({'my_email': my_email}) my_employee.update({'firstname': var_test.get("firstname")}) my_employee.update({'lastname': var_test.get("lastname")}) my_employee.update({'profil': var_test.get("profile")}) my_employee.update({'active': var_test.get("active")}) return my_employee
def assert_equals(expected, actual, error_message, debug_message=None): """ Giving objects that implement the __eq__ method, expected == actual. If not raising an exception. @param expected: any object that implements __eq__ that will act as a point of reference @param actual: any object that implements __eq__ that will compared against "expected" @param error_message: str, the message that will be contained in the exception, if such is thrown @return None @throws Test.TestAssertException """ try: Test.assert_that(expected == actual, error_message, debug_message) except Test.TestAssertException as e: padding = lambda x=0: " " * (len("TestAssertException:") + x) e.message = e.message + "\n" \ + "\n" \ + padding() \ + " Expected: '{e}'\n {p1}vs\n{p2}Actual: '{a}'".format(e=expected, a=actual, p1=padding(), p2=padding(1)) Context().logger.error(str(e)) raise e
def main_function(): """ @summary: function to run the test specified in the command line wioth the good parameters """ config = Configuration( ) # va lire le fichier global.cfg dans dossier conf et les variable passees dans la ligne de commande) for file_name in config.datasets_file_name: # parcours les dataset pour trouver le bon et recuperer les donnees if file_name != "": json_data = open("datasets/" + file_name + ".json") datas = json.load(json_data) relaunch = [] final_status = True for data in datas: if data['function'] == config.function_test or config.function_test == None: test_status = False my_line = (data['page'] + "||" + data['function'] + "||" + data['log']).split('||') if config.function_test == None: config._fct_test = my_line[1] my_test = __import__('tests.' + my_line[0]) test_file = getattr(my_test, my_line[0]) test_class = getattr(test_file, my_line[0]) test_fct = getattr(test_class(), my_line[1]) var_exist = 0 if data['variables'] is not None: my_var_test = {} try: for my_key, my_value in data['variables'][0].items( ): my_var_test[my_key] = my_value var_exist = 1 except: Context().logger.failure( "Issue store variables for the test") try: if config.back == False: Context().launch_browser2(clean_session=True) try: if config.back == False: storename = "/" if Configuration().storename != None: storename = Configuration( ).storename + storename if Configuration().vm == None: url = Context().environment.url.replace( 'str(i)', storename).replace( 'str(j)', 'localhost/') else: url = Context().environment.url.replace( 'str(i)', storename).replace( 'str(j)', Configuration().vm + '/') Context().goto_url(url) if var_exist == 1: test_status_save = test_status test_status = test_fct(my_var_test) else: test_status_save = test_status test_status = test_fct() except: pass except: Context().logger.error( "Issue to find the specified browser") Context().quit_browser() if test_status == True: Context().logger.success("Test OK for ({0})".format( my_line[2])) else: Context().logger.failure("Test KO for ({0})".format( my_line[2])) if data not in relaunch: datas.append(data) relaunch.append(data) test_status = test_status_save Context().logger.failure( "Test ({0}) failed for the first time, we will relaunch it" .format(my_line[2])) else: final_status = False if final_status == False: import sys sys.exit(1)