def post_exec(self, url): success_response = [200, 201] status = None endtime = time.time() + 120 error = None id_error = time.strftime("%Y%m%d%H%M%S") while (time.time() < endtime and status not in success_response): try: status = self.send_request(url) except Exception as e: error = str(e) time.sleep(12) response = str( f"STATUS: {status} Url: {url} ID: {id_error} Error: {error}") logger().debug(response) if status not in success_response: with open(f"{self.log_folder}\{id_error}_json_data_response.txt", "w") as json_log: json_log.write(response) return status in success_response
def send_request(self, server_address, json_data): """ Send a post request to server """ success = False response = None headers = {'content-type': 'application/json'} try: response = requests.post(server_address.strip(), data=json_data, headers=headers) except: pass if response is not None: if response.status_code == 200: logger().debug("Log de execucao enviado com sucesso!") success = True elif response.status_code == 201 or response.status_code == 204: logger().debug("Log de execucao enviado com sucesso!") success = True else: self.save_response_log(response, server_address, json_data) return False else: return False return success
def select_combo(self, element, option): """ Selects the option on the combobox. :param element: Combobox element :type element: Beautiful Soup object :param option: Option to be selected :type option: str Usage: >>> #Calling the method: >>> self.select_combo(element, "Chosen option") """ combo = Select(self.driver.find_element_by_xpath(xpath_soup(element))) value = next( iter( filter(lambda x: x.text[0:len(option)] == option, combo.options)), None) if value: time.sleep(1) text_value = value.text combo.select_by_visible_text(text_value) logger().info(f"Selected value for combo is: {text_value}")
def save_json_file(self, json_data): """ Writes the log file to the file system. Usage: >>> # Calling the method: >>> self.log.save_json_file() """ try: if self.folder: path = Path(self.folder, "new_log", self.station) os.makedirs(path) else: path = Path("Log", self.station) os.makedirs(path) except OSError: pass log_file = f"{self.user}_{uuid.uuid4().hex}.json" if self.config.smart_test: open("log_exec_file.txt", "w") with open( Path(path, log_file), mode="w", encoding="utf-8") as json_file: json_file.write(json_data) logger().debug(f"Log file created successfully: {Path(path, log_file)}")
def get_element_value(self, element): """ [Internal] Gets element value. :param element: Selenium element :type element: Selenium object :return: Element value :rtype: str Usage: >>> #Defining the element: >>> element = lambda: self.driver.find_element_by_id("example_id") >>> #Calling the method >>> text = self.get_element_value(element()) """ try: return self.driver.execute_script("return arguments[0].value", element) except StaleElementReferenceException: logger().exception( "********Element Stale get_element_value*********") pass
def cursor_execute(self, query, connection): cursor = connection.cursor() try: rowcount = cursor.execute(query).rowcount except Exception as error: self.webapp_internal.log_error(str(error)) logger().info(f'{rowcount} row(s) affected') connection.commit()
def connect_database(self, query="", database_driver="", dbq_oracle_server="", database_server="", database_port=1521, database_name="", database_user="", database_password=""): connection = self.odbc_connect(database_driver, dbq_oracle_server, database_server, database_port, database_name, database_user, database_password) if self.test_odbc_connection(connection): logger().info('DataBase connection started') else: logger().info('DataBase connection is stopped') return connection
def disconnect_database(self, connection): if not connection: connection = self.odbc_connect() cursor = self.test_odbc_connection(connection) if cursor: cursor.close() connection.close() if not self.test_odbc_connection(connection): logger().info('DataBase connection stopped') else: logger().info('DataBase connection already stopped')
def start_testcase(self): """ Method that starts testcase time and testcase info. :return: """ self.log.testcase_initial_time = datetime.today() self.test_case.append(self.log.get_testcase_stack()) self.last_test_case = self.log.get_testcase_stack() self.log.ct_method, self.log.ct_number = self.log.ident_test() logger().info( f"Starting TestCase: {self.log.ct_method} CT: {self.log.ct_number}" )
def double_click(self, element, click_type=enum.ClickType.SELENIUM): """ [Internal] Clicks two times on the Selenium element. :param element: Selenium element :type element: Selenium object Usage: >>> #Defining the element: >>> element = lambda: self.driver.find_element_by_id("example_id") >>> #Calling the method >>> self.double_click(element()) """ try: if click_type == enum.ClickType.SELENIUM: self.scroll_to_element(element) element.click() element.click() elif click_type == enum.ClickType.ACTIONCHAINS: self.scroll_to_element(element) actions = ActionChains(self.driver) actions.move_to_element(element) actions.double_click() actions.perform() elif click_type == enum.ClickType.JS: self.driver.execute_script("arguments[0].click()", element) self.driver.execute_script("arguments[0].click()", element) return True except Exception as e: try: logger().warning( f"Warning double_click method Exception: {str(e)}") self.scroll_to_element(element) actions = ActionChains(self.driver) actions.move_to_element(element) actions.double_click() actions.perform() return True except Exception as x: logger().exception( f"Error double_click method Exception: {str(x)}") return False
def assert_result(self, expected): """ [Internal] Asserts the result based on the expected value. :param expected: Expected value :type expected: bool Usage : >>> #Calling the method: >>> self.assert_result(True) """ expected_assert = expected msg = "Passed" stack_item = next( iter( list( map( lambda x: x.function, filter(lambda x: re.search('test_', x.function), inspect.stack())))), None) test_number = f"{stack_item.split('_')[-1]} -" if stack_item else "" log_message = f"{test_number}" self.log.set_seconds() if self.errors: expected = not expected for field_msg in self.errors: log_message += (" " + field_msg) msg = log_message self.log.new_line(False, log_message) else: self.log.new_line(True, "") self.log.save_file() self.errors = [] logger().info(msg) if expected_assert: self.assertTrue(expected, msg) else: self.assertFalse(expected, msg)
def click(self, element, click_type=enum.ClickType.JS, right_click=False): """ [Internal] Clicks on the Selenium element. Supports three types of clicking: JavaScript, pure Selenium and Selenium's ActionChains. Default is JavaScript clicking. :param element: Selenium element :type element: Selenium object :param click_type: ClickType enum. - **Default:** enum.ClickType.JS :type click_type: enum.ClickType :param right_click: Clicks with the right button of the mouse in the last element of the tree. :type string: bool Usage: >>> #Defining the element: >>> element = lambda: self.driver.find_element_by_id("example_id") >>> #Calling the method >>> self.click(element(), click_type=enum.ClickType.JS) """ try: if right_click: ActionChains(self.driver).context_click(element).perform() else: self.scroll_to_element(element) if click_type == enum.ClickType.JS: self.driver.execute_script("arguments[0].click()", element) elif click_type == enum.ClickType.SELENIUM: element.click() elif click_type == enum.ClickType.ACTIONCHAINS: ActionChains(self.driver).move_to_element( element).click().perform() return True except StaleElementReferenceException: logger().exception("********Element Stale click*********") return False except Exception as e: logger().exception(f"Warning click method Exception: {str(e)}") return False
def finish_testcase(self): """ Method that is responsable to finish testcase and send the log and execution time of testcase. :return: """ if self.last_test_case not in self.log.finish_testcase: logger().info( f"Finishing TestCase: {self.log.ct_method} CT: {self.log.ct_number}" ) self.log.testcase_seconds = self.log.set_seconds( self.log.testcase_initial_time) self.log.generate_result(self.expected, self.message) self.log.finish_testcase.append( self.last_test_case if not self.log.get_testcase_stack() == "setUpClass" else self.log.get_testcase_stack()) logger().info(self.log.testcase_seconds)
def SetTIRConfig(self, config_name, value): """ Changes a value of a TIR internal config during runtime. This could be useful for TestCases that must use a different set of configs than the ones defined at **config.json** Available configs: - Url - str - Environment - str - User - str - Password - str - Language - str - DebugLog - str - TimeOut - int - InitialProgram - str - Routine - str - Date - str - Group - str - Branch - str - Module - str :param config_name: The config to be changed. :type config_name: str :param value: The value that would be set. :type value: str Usage: >>> # Calling the method: >>> oHelper.SetTIRConfig(config_name="date", value="30/10/2018") """ if 'TimeOut' in config_name: logger().info('TimeOut setting has been disabled in SetTirConfig') else: logger().info(f"Setting config: {config_name} = {value}") normalized_config = self.normalize_config_name(config_name) setattr(self.config, normalized_config, value)
def save_file(self): """ Writes the log file to the file system. Usage: >>> # Calling the method: >>> self.log.save_file() """ log_file = f"{self.user}_{uuid.uuid4().hex}_auto.csv" if len(self.table_rows) > 0: try: if self.folder: path = Path(self.folder, self.station+"_v6") os.makedirs(path) else: path = Path("Log", self.station) os.makedirs(path) except OSError: pass if self.config.smart_test: open("log_exec_file.txt", "w") if ((len(self.table_rows[1:]) == len(self.test_case) and self.get_testcase_stack() not in self.csv_log) or (self.get_testcase_stack() == "setUpClass") and self.checks_empty_line()) : with open( Path(path, log_file), mode="w", newline="", encoding="windows-1252") as csv_file: csv_writer_header = csv.writer(csv_file, delimiter=';', quoting=csv.QUOTE_NONE) csv_writer_header.writerow(self.table_rows[0]) csv_writer = csv.writer(csv_file, delimiter=';', quotechar='"', quoting=csv.QUOTE_NONNUMERIC) for line in self.table_rows[1:]: csv_writer.writerow(line) logger().debug(f"Log file created successfully: {os.path.join(path, log_file)}") self.csv_log.append(self.get_testcase_stack())
def set_element_focus(self, element): """ [Internal] Sets focus on element. :param element: Selenium element :type element: Selenium object Usage: >>> #Defining the element: >>> element = lambda: self.driver.find_element_by_id("example_id") >>> #Calling the method >>> text = self.set_element_focus(element()) """ try: self.driver.execute_script("window.focus(); arguments[0].focus();", element) except StaleElementReferenceException: logger().exception( "********Element Stale set_element_focus*********") pass
def scroll_to_element(self, element): """ [Internal] Scroll to element on the screen. :param element: Selenium element :type element: Selenium object Usage: >>> #Defining an element: >>> element = lambda: self.driver.find_element_by_id("example_id") >>> #Calling the method >>> self.scroll_to_element(element()) """ try: self.driver.execute_script("return arguments[0].scrollIntoView();", element) except StaleElementReferenceException: logger().exception( "********Element Stale scroll_to_element*********") pass
def Start(self): """ Opens the browser maximized and goes to defined URL. Usage: >>> # Calling the method: >>> oHelper.Start() """ logger().info(f'TIR Version: {__version__}') logger().info("Starting the browser") if self.config.browser.lower() == "firefox": if sys.platform == 'linux': driver_path = os.path.join(os.path.dirname(__file__), r'drivers/linux64/geckodriver') else: driver_path = os.path.join( os.path.dirname(__file__), r'drivers\\windows\\geckodriver.exe') log_path = os.devnull firefox_options = FirefoxOpt() firefox_options.set_headless(self.config.headless) self.driver = webdriver.Firefox(options=firefox_options, executable_path=driver_path, log_path=log_path) elif self.config.browser.lower() == "chrome": driver_path = os.path.join(os.path.dirname(__file__), r'drivers\\windows\\chromedriver.exe') chrome_options = ChromeOpt() chrome_options.set_headless(self.config.headless) chrome_options.add_argument('--log-level=3') if self.config.headless: chrome_options.add_argument('force-device-scale-factor=0.77') self.driver = webdriver.Chrome(options=chrome_options, executable_path=driver_path) elif self.config.browser.lower() == "electron": driver_path = os.path.join( os.path.dirname(__file__), r'drivers\\windows\\electron\\chromedriver.exe') chrome_options = ChromeOpt() chrome_options.add_argument('--log-level=3') chrome_options.add_argument( f'--environment="{self.config.environment}"') chrome_options.add_argument(f'--url="{self.config.url}"') chrome_options.add_argument( f'--program="{self.config.start_program}"') chrome_options.add_argument('--quiet') chrome_options.binary_location = self.config.electron_binary_path self.driver = webdriver.Chrome(options=chrome_options, executable_path=driver_path) if not self.config.browser.lower() == "electron": if self.config.headless: self.driver.set_window_position(0, 0) self.driver.set_window_size(1366, 768) else: self.driver.maximize_window() self.driver.get(self.config.url) self.wait = WebDriverWait(self.driver, self.config.time_out)
def take_screenshot_log(self, driver, stack_item="", test_number=""): """ [Internal] Takes a screenshot and saves on the log screenshot folder defined in config. :param driver: The selenium driver. :type: Selenium Driver :param stack_item: test case stack :type: str :param test_number: test case number :type: str Usage: >>> # Calling the method: >>> self.log.take_screenshot_log() """ if not stack_item: stack_item = self.get_testcase_stack() if stack_item == "setUpClass": stack_item = self.get_file_name("testsuite") if not test_number: test_number = f"{stack_item.split('_')[-1]} -" if stack_item else "" if not self.release: self.release = self.config.release testsuite = self.get_file_name("testsuite") today = datetime.today() if self.search_stack("log_error"): screenshot_file = self.screenshot_file_name("error", stack_item) elif self.search_stack("CheckResult"): screenshot_file = self.screenshot_file_name("CheckResult_result_divergence", stack_item) else: screenshot_file = self.screenshot_file_name(stack_item) if self.config.debug_log: logger().debug(f"take_screenshot_log in:{datetime.now()}\n") try: if self.config.log_http: folder_path = Path(self.config.log_http, self.config.country, self.release, self.config.issue, self.config.execution_id, testsuite) path = Path(folder_path, screenshot_file) os.makedirs(Path(folder_path)) else: path = Path("Log", self.station, screenshot_file) os.makedirs(Path("Log", self.station)) except OSError: pass try: driver.save_screenshot(str(path)) logger().debug(f"Screenshot file created successfully: {path}") except Exception as e: logger().exception(f"Warning Log Error save_screenshot exception {str(e)}")
def element_exists(self, term, scrap_type=enum.ScrapType.TEXT, position=0, optional_term="", main_container=".tmodaldialog,.ui-dialog"): """ [Internal] Returns a boolean if element exists on the screen. :param term: The first term to use on a search of element :type term: str :param scrap_type: Type of element search. - **Default:** enum.ScrapType.TEXT :type scrap_type: enum.ScrapType :param position: Position which element is located. - **Default:** 0 :type position: int :param optional_term: Second term to use on a search of element. Used in MIXED search. - **Default:** "" (empty string) :type optional_term: str :return: True if element is present. False if element is not present. :rtype: bool Usage: >>> element_is_present = element_exists(term=".ui-dialog", scrap_type=enum.ScrapType.CSS_SELECTOR) >>> element_is_present = element_exists(term=".tmodaldialog.twidget", scrap_type=enum.ScrapType.CSS_SELECTOR, position=initial_layer+1) >>> element_is_present = element_exists(term=text, scrap_type=enum.ScrapType.MIXED, optional_term=".tsay") """ if self.config.debug_log: logger().info( f"term={term}, scrap_type={scrap_type}, position={position}, optional_term={optional_term}" ) if scrap_type == enum.ScrapType.SCRIPT: return bool(self.driver.execute_script(term)) elif (scrap_type != enum.ScrapType.MIXED and scrap_type != enum.ScrapType.TEXT): selector = term if scrap_type == enum.ScrapType.CSS_SELECTOR: by = By.CSS_SELECTOR elif scrap_type == enum.ScrapType.XPATH: by = By.XPATH if scrap_type != enum.ScrapType.XPATH: soup = self.get_current_DOM() container_selector = self.base_container if (main_container is not None): container_selector = main_container containers = self.zindex_sort(soup.select(container_selector), reverse=True) container = next(iter(containers), None) if not container: return False try: container_element = self.driver.find_element_by_xpath( xpath_soup(container)) except: return False else: container_element = self.driver element_list = container_element.find_elements(by, selector) else: if scrap_type == enum.ScrapType.MIXED: selector = optional_term else: selector = "div" element_list = self.web_scrap(term=term, scrap_type=scrap_type, optional_term=optional_term, main_container=main_container) if position == 0: return len(element_list) > 0 else: return len(element_list) >= position