""" F248_US38249 feature """ # pylint: disable=E0401,E0602 from robot.libraries.BuiltIn import BuiltIn from dto import * from env_variables import * from copy import deepcopy try: TEST_RING = BuiltIn().get_variable_value("${X_TEST_RING}") except: # noqa TEST_RING = 'DCS' FUSION_IP = APPLIANCE_VIP CREDENTIALS = deepcopy(admin_credentials) FUSION_USERNAME = CREDENTIALS['userName'] # Fusion Appliance Username FUSION_PASSWORD = CREDENTIALS['password'] # Fusion Appliance Password FUSION_SSH_USERNAME = '******' # Fusion SSH Username FUSION_SSH_PASSWORD = '******' # Fusion SSH Password FUSION_PROMPT = '#' # Fusion Appliance Prompt FUSION_TIMEOUT = 180 # Timeout. Move this out??? FUSION_NIC = 'bond0' # Fusion Appliance Primary NIC FUSION_NIC_SUFFIX = '%' + FUSION_NIC # ports DownLinkPort = 'd5' UpLinkPort = 'Q4:1'
# coding: utf-8 """Library to document and test correct default value escaping.""" from robot.libraries.BuiltIn import BuiltIn b = BuiltIn() def verify_backslash(current='c:\\windows\\system', expected='c:\\windows\\system'): b.should_be_equal(current, expected) def verify_internalvariables( current='first ${sca${lar}} @{list}[${4}] &{dict.key}[2] some env %{${somename}} and a \\${backslash}[${key}] ', expected='first ${sca${lar}} @{list}[${4}] &{dict.key}[2] some env %{${somename}} and a \\${backslash}[${key}] ' ): b.should_be_equal(current, expected) def verify_line_break(current='Hello\n World!\r\n End...\\n', expected='Hello\n World!\r\n End...\\n'): b.should_be_equal(current, expected) def verify_line_tab(current='Hello\tWorld!\t\t End\\t...', expected='Hello\tWorld!\t\t End\\t...'): b.should_be_equal(current, expected) def verify_spaces(current=' Hello\tW orld!\t \t En d\\t... ', expected=' Hello\tW orld!\t \t En d\\t... '):
def prepare_tender_data(): tender_file_path = BuiltIn().get_variable_value("${tender_file_path}") with open(tender_file_path) as tender_file: return json.load(tender_file)["data"]
# keywords to test composite commands in REST import json import sys import os import requests import RequestsLibrary from collections import OrderedDict from robot.libraries.BuiltIn import BuiltIn # variables.py file is imported from the VARIABLES_FILE_DIR path provided in the test case # if VARIABLES_FILE_DIR is not defined , variables.py under main/testcases/ directory is imported builtin = BuiltIn() variables_file_path = builtin.get_variable_value("${VARIABLES_FILE_DIR}") if variables_file_path: sys.path.append(os.path.abspath(variables_file_path)) else: sys.path.append( os.path.abspath( os.path.join(os.path.dirname(__file__), '../../testcases/'))) import variables def create_comp_session(session_user, session_password, session_alias='bscs'): """creates new HTTP session - not utilized yet in any test cases :param session_user: <user name for the session> :param session_password:<password for the session> :param session_alias:<alias name of the session> """
def _log_dir(self): variables = BuiltIn().get_variables() outdir = variables['${OUTPUTDIR}'] log = variables['${LOGFILE}'] log = os.path.dirname(log) if log != 'NONE' else '.' return self._norm_path(os.path.join(outdir, log))
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html """This file provides robot library functions for NVDA system tests. It contains helper methods for system tests, most specifically related to the setup for, starting of, quiting of, and cleanup of, NVDA. This is in contrast with the systemTestSpy.py file, which provides library functions related to monitoring / asserting NVDA output. """ # imported methods start with underscore (_) so they don't get imported into robot files as keywords from os.path import join as _pJoin, abspath as _abspath, expandvars as _expandvars import tempfile import sys from robotremoteserver import test_remote_server as _testRemoteServer, stop_remote_server as _stopRemoteServer from robot.libraries.BuiltIn import BuiltIn from robot.libraries.OperatingSystem import OperatingSystem from robot.libraries.Process import Process from systemTestUtils import _blockUntilConditionMet builtIn = BuiltIn() # type: BuiltIn process = builtIn.get_library_instance('Process') # type: Process opSys = builtIn.get_library_instance( 'OperatingSystem') # type: OperatingSystem spyServerPort = 8270 # is `registered by IANA` for remote server usage. Two ASCII values:'RF' spyServerURI = 'http://127.0.0.1:{}'.format(spyServerPort) spyAlias = "nvdaSpy" # robot is expected to be run from the NVDA repo root directory. We want all repo specific # paths to be relative to this. This would allow us to change where it is run from if we decided to. repoRoot = _abspath("./") whichNVDA = builtIn.get_variable_value("${whichNVDA}", "source") if whichNVDA == "source": NVDACommandPathToCheckExists = _pJoin(repoRoot, "source/nvda.pyw") baseNVDACommandline = "pythonw " + NVDACommandPathToCheckExists
def check_test_case(self, testname, status=None, message=None): test = self._get_test_from_suite( BuiltIn().get_variable_value('${SUITE}'), testname) self._check_test_status(test, status=status, message=message) return test
def plug_in_setup(): r""" Initialize all changing plug-in environment variables for use by the plug-in programs. """ global LOG_LEVEL global test_really_running BuiltIn().set_log_level("NONE") boot_pass, boot_fail = boot_results.return_total_pass_fail() if boot_pass > 1: test_really_running = 1 else: test_really_running = 0 BuiltIn().set_global_variable("${test_really_running}", test_really_running) BuiltIn().set_global_variable("${boot_type_desc}", next_boot) BuiltIn().set_global_variable("${boot_pass}", boot_pass) BuiltIn().set_global_variable("${boot_fail}", boot_fail) BuiltIn().set_global_variable("${boot_success}", boot_success) BuiltIn().set_global_variable("${ffdc_prefix}", ffdc_prefix) BuiltIn().set_global_variable("${boot_start_time}", boot_start_time) BuiltIn().set_global_variable("${boot_end_time}", boot_end_time) # For each program parameter, set the corresponding AUTOBOOT_ environment # variable value. Also, set an AUTOBOOT_ environment variable for every # element in additional_values. additional_values = [ "boot_type_desc", "boot_success", "boot_pass", "boot_fail", "test_really_running", "ffdc_prefix", "boot_start_time", "boot_end_time" ] plug_in_vars = additional_values for var_name in plug_in_vars: var_value = BuiltIn().get_variable_value("${" + var_name + "}") var_name = var_name.upper() if var_value is None: var_value = "" os.environ["AUTOBOOT_" + var_name] = str(var_value) if debug: shell_rc, out_buf = \ gc.cmd_fnc_u("printenv | egrep AUTOBOOT_ | sort -u") BuiltIn().set_log_level(LOG_LEVEL)
def setup(): r""" Do general program setup tasks. """ global cp_setup_called global transitional_boot_selected gp.qprintn() set_default_siguser1() transitional_boot_selected = False robot_pgm_dir_path = os.path.dirname(__file__) + os.sep repo_bin_path = robot_pgm_dir_path.replace("/lib/", "/bin/") # If we can't find process_plug_in_packages.py, ssh_pw or # validate_plug_ins.py, then we don't have our repo bin in PATH. shell_rc, out_buf = gc.cmd_fnc_u("which process_plug_in_packages.py" + " ssh_pw validate_plug_ins.py", quiet=1, print_output=0, show_err=0) if shell_rc != 0: os.environ['PATH'] = repo_bin_path + ":" + os.environ.get('PATH', "") # Likewise, our repo lib subdir needs to be in sys.path and PYTHONPATH. if robot_pgm_dir_path not in sys.path: sys.path.append(robot_pgm_dir_path) PYTHONPATH = os.environ.get("PYTHONPATH", "") if PYTHONPATH == "": os.environ['PYTHONPATH'] = robot_pgm_dir_path else: os.environ['PYTHONPATH'] = robot_pgm_dir_path + ":" + PYTHONPATH validate_parms() gp.qprint_pgm_header() grk.run_key("Set BMC Power Policy ALWAYS_POWER_OFF") initial_plug_in_setup() plug_in_setup() rc, shell_rc, failed_plug_in_name = grpi.rprocess_plug_in_packages( call_point='setup') if rc != 0: error_message = "Plug-in setup failed.\n" gp.print_error_report(error_message) BuiltIn().fail(error_message) # Setting cp_setup_called lets our Teardown know that it needs to call # the cleanup plug-in call point. cp_setup_called = 1 # Keyword "FFDC" will fail if TEST_MESSAGE is not set. BuiltIn().set_global_variable("${TEST_MESSAGE}", "${EMPTY}") # FFDC_LOG_PATH is used by "FFDC" keyword. BuiltIn().set_global_variable("${FFDC_LOG_PATH}", ffdc_dir_path) # Also printed by FFDC. global host_name global host_ip host = socket.gethostname() host_name, host_ip = gm.get_host_name_ip(host) gp.dprint_var(boot_table, 1) gp.dprint_var(boot_lists)
def process_pgm_parms(): r""" Process the program parameters by assigning them all to corresponding globals. Also, set some global values that depend on program parameters. """ # Program parameter processing. # Assign all program parms to python variables which are global to this # module. global parm_list parm_list = BuiltIn().get_variable_value("${parm_list}") # The following subset of parms should be processed as integers. int_list = [ 'max_num_tests', 'boot_pass', 'boot_fail', 'ffdc_only', 'boot_fail_threshold', 'delete_errlogs', 'call_post_stack_plug', 'quiet', 'test_mode', 'debug' ] for parm in parm_list: if parm in int_list: sub_cmd = "int(BuiltIn().get_variable_value(\"${" + parm +\ "}\", \"0\"))" else: sub_cmd = "BuiltIn().get_variable_value(\"${" + parm + "}\")" cmd_buf = "global " + parm + " ; " + parm + " = " + sub_cmd gp.dpissuing(cmd_buf) exec(cmd_buf) if re.match(r".*_host$", parm): cmd_buf = "process_host(" + parm + ", '" + parm + "')" exec(cmd_buf) if re.match(r".*_password$", parm): # Register the value of any parm whose name ends in _password. # This will cause the print functions to replace passwords with # asterisks in the output. cmd_buf = "gp.register_passwords(" + parm + ")" exec(cmd_buf) global ffdc_dir_path_style global boot_list global boot_stack global boot_results_file_path global boot_results global last_ten global ffdc_list_file_path global ffdc_report_list_path global ffdc_summary_list_path if ffdc_dir_path_style == "": ffdc_dir_path_style = int(os.environ.get('FFDC_DIR_PATH_STYLE', '0')) # Convert these program parms to lists for easier processing.. boot_list = list(filter(None, boot_list.split(":"))) boot_stack = list(filter(None, boot_stack.split(":"))) cleanup_boot_results_file() boot_results_file_path = create_boot_results_file_path( pgm_name, openbmc_nickname, master_pid) if os.path.isfile(boot_results_file_path): # We've been called before in this run so we'll load the saved # boot_results and last_ten objects. boot_results, last_ten =\ pickle.load(open(boot_results_file_path, 'rb')) else: boot_results = boot_results(boot_table, boot_pass, boot_fail) ffdc_list_file_path = base_tool_dir_path + openbmc_nickname +\ "/FFDC_FILE_LIST" ffdc_report_list_path = base_tool_dir_path + openbmc_nickname +\ "/FFDC_REPORT_FILE_LIST" ffdc_summary_list_path = base_tool_dir_path + openbmc_nickname +\ "/FFDC_SUMMARY_FILE_LIST"
def initial_plug_in_setup(): r""" Initialize all plug-in environment variables which do not change for the duration of the program. """ global LOG_LEVEL BuiltIn().set_log_level("NONE") BuiltIn().set_global_variable("${master_pid}", master_pid) BuiltIn().set_global_variable("${FFDC_DIR_PATH}", ffdc_dir_path) BuiltIn().set_global_variable("${STATUS_DIR_PATH}", status_dir_path) BuiltIn().set_global_variable("${BASE_TOOL_DIR_PATH}", base_tool_dir_path) BuiltIn().set_global_variable("${FFDC_LIST_FILE_PATH}", ffdc_list_file_path) BuiltIn().set_global_variable("${FFDC_REPORT_LIST_PATH}", ffdc_report_list_path) BuiltIn().set_global_variable("${FFDC_SUMMARY_LIST_PATH}", ffdc_summary_list_path) BuiltIn().set_global_variable("${FFDC_DIR_PATH_STYLE}", ffdc_dir_path_style) BuiltIn().set_global_variable("${FFDC_CHECK}", ffdc_check) # For each program parameter, set the corresponding AUTOBOOT_ environment # variable value. Also, set an AUTOBOOT_ environment variable for every # element in additional_values. additional_values = [ "program_pid", "master_pid", "ffdc_dir_path", "status_dir_path", "base_tool_dir_path", "ffdc_list_file_path", "ffdc_report_list_path", "ffdc_summary_list_path", "execdir" ] plug_in_vars = parm_list + additional_values for var_name in plug_in_vars: var_value = BuiltIn().get_variable_value("${" + var_name + "}") var_name = var_name.upper() if var_value is None: var_value = "" os.environ["AUTOBOOT_" + var_name] = str(var_value) BuiltIn().set_log_level(LOG_LEVEL) # Make sure the ffdc list directory exists. ffdc_list_dir_path = os.path.dirname(ffdc_list_file_path) + os.sep if not os.path.exists(ffdc_list_dir_path): os.makedirs(ffdc_list_dir_path)
def obmc_boot_test_py(loc_boot_stack=None, loc_stack_mode=None, loc_quiet=None): r""" Do main program processing. """ global save_stack gp.dprintn() # Process function parms. for parm_name in main_func_parm_list: # Get parm's value. parm_value = eval("loc_" + parm_name) gp.dpvars(parm_name, parm_value) if parm_value is not None: # Save the global value on a stack. cmd_buf = "save_stack.push(BuiltIn().get_variable_value(\"${" +\ parm_name + "}\"), \"" + parm_name + "\")" gp.dpissuing(cmd_buf) exec(cmd_buf) # Set the global value to the passed value. cmd_buf = "BuiltIn().set_global_variable(\"${" + parm_name +\ "}\", loc_" + parm_name + ")" gp.dpissuing(cmd_buf) exec(cmd_buf) gp.dprintn(save_stack.sprint_obj()) setup() init_boot_pass, init_boot_fail = boot_results.return_total_pass_fail() if ffdc_only: gp.qprint_timen("Caller requested ffdc_only.") pre_boot_plug_in_setup() grk.run_key_u("my_ffdc") return # Process caller's boot_stack. while (len(boot_stack) > 0): test_loop_body() gp.qprint_timen("Finished processing stack.") post_stack() # Process caller's boot_list. if len(boot_list) > 0: for ix in range(1, max_num_tests + 1): test_loop_body() gp.qprint_timen("Completed all requested boot tests.") boot_pass, boot_fail = boot_results.return_total_pass_fail() new_fail = boot_fail - init_boot_fail if new_fail > boot_fail_threshold: error_message = "Boot failures exceed the boot failure" +\ " threshold:\n" +\ gp.sprint_var(new_fail) +\ gp.sprint_var(boot_fail_threshold) BuiltIn().fail(gp.sprint_error(error_message))
state = st.return_state_constant('default_state') cp_setup_called = 0 next_boot = "" base_tool_dir_path = os.path.normpath( os.environ.get('AUTOBOOT_BASE_TOOL_DIR_PATH', "/tmp")) + os.sep ffdc_dir_path = os.path.normpath(os.environ.get('FFDC_DIR_PATH', '')) + os.sep boot_success = 0 status_dir_path = os.environ.get('STATUS_DIR_PATH', "") if status_dir_path != "": status_dir_path = os.path.normpath(status_dir_path) + os.sep default_power_on = "REST Power On" default_power_off = "REST Power Off" boot_count = 0 LOG_LEVEL = BuiltIn().get_variable_value("${LOG_LEVEL}") ffdc_prefix = "" boot_start_time = "" boot_end_time = "" save_stack = vs.var_stack('save_stack') main_func_parm_list = ['boot_stack', 'stack_mode', 'quiet'] def dump_ffdc_rc(): r""" Return the constant dump ffdc test return code value. When a plug-in call point program returns this value, it indicates that this program should collect FFDC. """
def compare_screen_areas( self, x1: int, y1: int, x2: int, y2: int, path1: str, save_folder: str = save_folder_path, ssim: float = starts_ssim, image_format=starts_format_image, ): """Creates a cut-out from the screen that is on the screen and compares it to a previously created ``x1`` and ``y1`` = x and y coordinates for the upper left corner of the square ``x2`` and ``y2`` = x and y coordinates for the bottom right corner of the square ``path1`` = Path to an already created viewport with which we want to compare the viewport created by us Example: | Compare Screen Areas | 0 | 0 | 25 | 25 | ../cropped_image1.png | """ self._check_dir(save_folder) self._check_ssim(ssim) self._check_image_format(image_format) save_folder = self.save_folder self.seleniumlib.capture_page_screenshot(save_folder + "/test1.png") path2 = save_folder + "/test1.png" if os.path.exists(path1): if os.path.exists(path2): # load img img1 = cv.imread(path1, 1) # img from docu img2 = cv.imread(path2, 1) # img from screenshot # convert to grey gray_img1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY) gray_img2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY) # spliting area crop_img = gray_img2[int(x1):int( y2), int(y1):int( x2)] # Crop from {x, y, w, h } => {0, 0, 300, 400} # SSIM diff img (self.score, diff) = structural_similarity(gray_img1, crop_img, full=True) diff = (diff * 255).astype("uint8") # Threshold diff img thresh = cv.threshold(diff, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1] cnts = cv.findContours(thresh.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) crop_img_color = img2[int(x1):int(y2), int(y1):int(x2)] # Create frame in diff area for c in cnts: (x, y, w, h) = cv.boundingRect(c) cv.rectangle(img1, (x, y), (x + w, y + h), (0, 0, 255), 2) cv.rectangle(crop_img_color, (x, y), (x + w, y + h), (0, 0, 255), 2) # Show image if float(self.score) < self.ssim: self.robotlib = BuiltIn().get_library_instance("BuiltIn") img_diff = cv.hconcat([img1, crop_img_color]) time_ = str(time.time()) self.seleniumlib.capture_page_screenshot(save_folder + "/img" + time_ + ".png") cv.imwrite(save_folder + "/img" + time_ + self.format, img_diff) self.robotlib.fail("Image has diff: {} ".format( self.score)) score_percen = float(self.score) * +100 self.robotlib.fail( "Image has diff: {} %".format(score_percen)) else: img_diff = cv.hconcat([self.img1, self.img2]) time_ = str(time.time()) self.seleniumlib.capture_page_screenshot(save_folder + "/Img" + time_ + self.format) cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff) self.robotlib.log("Image has diff: {} ".format(self.score)) else: raise AssertionError("New screen does not exist anymore.") else: raise AssertionError( "The path1 to the image does not exist. Try a other path, than:" + path1) if os.path.exists(save_folder + "/test1.png"): os.remove(save_folder + "/test1.png")
def pause_for_debug(self): if self.__is_debug_mode: BuiltIn().run_keyword( "Pause Execution", "Paused execution for debugging, click OK to continu process")
def validate_parms(): r""" Validate all program parameters. """ process_pgm_parms() gp.qprintn() global openbmc_model grv.rvalid_value("openbmc_host") grv.rvalid_value("openbmc_username") grv.rvalid_value("openbmc_password") grv.rvalid_value("rest_username") grv.rvalid_value("rest_password") grv.rvalid_value("ipmi_username") grv.rvalid_value("ipmi_password") if os_host != "": grv.rvalid_value("os_username") grv.rvalid_value("os_password") if pdu_host != "": grv.rvalid_value("pdu_username") grv.rvalid_value("pdu_password") grv.rvalid_integer("pdu_slot_no") if openbmc_serial_host != "": grv.rvalid_integer("openbmc_serial_port") if openbmc_model == "": status, ret_values =\ grk.run_key_u("Get BMC System Model") openbmc_model = ret_values BuiltIn().set_global_variable("${openbmc_model}", openbmc_model) grv.rvalid_value("openbmc_model") grv.rvalid_integer("max_num_tests") grv.rvalid_integer("boot_pass") grv.rvalid_integer("boot_fail") plug_in_packages_list = grpi.rvalidate_plug_ins(plug_in_dir_paths) BuiltIn().set_global_variable("${plug_in_packages_list}", plug_in_packages_list) grv.rvalid_value("stack_mode", valid_values=['normal', 'skip']) if len(boot_list) == 0 and len(boot_stack) == 0 and not ffdc_only: error_message = "You must provide either a value for either the" +\ " boot_list or the boot_stack parm.\n" BuiltIn().fail(gp.sprint_error(error_message)) valid_boot_list(boot_list, valid_boot_types) valid_boot_list(boot_stack, valid_boot_types) selected_PDU_boots = list( set(boot_list + boot_stack) & set(boot_lists['PDU_reboot'])) if len(selected_PDU_boots) > 0 and pdu_host == "": error_message = "You have selected the following boots which" +\ " require a PDU host but no value for pdu_host:\n" error_message += gp.sprint_var(selected_PDU_boots) error_message += gp.sprint_var(pdu_host, 2) BuiltIn().fail(gp.sprint_error(error_message)) return
def show_variables(self): # TODO: Recursively dump the NormalizedDict and optionally hide secrets variables = {k: v for k, v in BuiltIn().get_variables().items()} pprint.pprint(variables)
def run_boot(boot): r""" Run the specified boot. Description of arguments: boot The name of the boot test to be performed. """ global state signal.signal(signal.SIGUSR1, stop_boot_test) gp.qprint_timen("stop_boot_test is armed.") print_test_start_message(boot) plug_in_setup() rc, shell_rc, failed_plug_in_name = \ grpi.rprocess_plug_in_packages(call_point="pre_boot") if rc != 0: error_message = "Plug-in failed with non-zero return code.\n" +\ gp.sprint_var(rc, 1) set_default_siguser1() BuiltIn().fail(gp.sprint_error(error_message)) if test_mode: # In test mode, we'll pretend the boot worked by assigning its # required end state to the default state value. state = st.strip_anchor_state(boot_table[boot]['end']) else: # Assertion: We trust that the state data was made fresh by the # caller. gp.qprintn() if boot_table[boot]['method_type'] == "keyword": rk.my_run_keywords(boot_table[boot].get('lib_file_path', ''), boot_table[boot]['method'], quiet=quiet) if boot_table[boot]['bmc_reboot']: st.wait_for_comm_cycle(int(state['epoch_seconds'])) plug_in_setup() rc, shell_rc, failed_plug_in_name = \ grpi.rprocess_plug_in_packages(call_point="post_reboot") if rc != 0: error_message = "Plug-in failed with non-zero return code.\n" error_message += gp.sprint_var(rc, 1) set_default_siguser1() BuiltIn().fail(gp.sprint_error(error_message)) else: match_state = st.anchor_state(state) del match_state['epoch_seconds'] # Wait for the state to change in any way. st.wait_state(match_state, wait_time=state_change_timeout, interval="10 seconds", invert=1) gp.qprintn() if boot_table[boot]['end']['chassis'] == "Off": boot_timeout = power_off_timeout else: boot_timeout = power_on_timeout st.wait_state(boot_table[boot]['end'], wait_time=boot_timeout, interval="10 seconds") plug_in_setup() rc, shell_rc, failed_plug_in_name = \ grpi.rprocess_plug_in_packages(call_point="post_boot") if rc != 0: error_message = "Plug-in failed with non-zero return code.\n" +\ gp.sprint_var(rc, 1) set_default_siguser1() BuiltIn().fail(gp.sprint_error(error_message)) # Restore original sigusr1 handler. set_default_siguser1()
def get_test_case(self, name): suite = BuiltIn().get_variable_value('${SUITE}') return self._get_test_from_suite(suite, name)
def test_loop_body(): r""" The main loop body for the loop in main_py. Description of arguments: boot_count The iteration number (starts at 1). """ global boot_count global state global next_boot global boot_success global boot_end_time gp.qprintn() next_boot = select_boot() if next_boot == "": return True boot_count += 1 gp.qprint_timen("Starting boot " + str(boot_count) + ".") pre_boot_plug_in_setup() cmd_buf = ["run_boot", next_boot] boot_status, msg = BuiltIn().run_keyword_and_ignore_error(*cmd_buf) if boot_status == "FAIL": gp.qprint(msg) gp.qprintn() if boot_status == "PASS": boot_success = 1 completion_msg = gp.sprint_timen("BOOT_SUCCESS: \"" + next_boot + "\" succeeded.") else: boot_success = 0 completion_msg = gp.sprint_timen("BOOT_FAILED: \"" + next_boot + "\" failed.") # Set boot_end_time for use by plug-ins. boot_end_time = completion_msg[1:33] gp.qprint_var(boot_end_time) gp.qprint(completion_msg) boot_results.update(next_boot, boot_status) plug_in_setup() # NOTE: A post_test_case call point failure is NOT counted as a boot # failure. rc, shell_rc, failed_plug_in_name = grpi.rprocess_plug_in_packages( call_point='post_test_case', stop_on_plug_in_failure=0) plug_in_setup() rc, shell_rc, failed_plug_in_name = grpi.rprocess_plug_in_packages( call_point='ffdc_check', shell_rc=dump_ffdc_rc(), stop_on_plug_in_failure=1, stop_on_non_zero_rc=1) if ffdc_check == "All" or\ shell_rc == dump_ffdc_rc(): status, ret_values = grk.run_key_u("my_ffdc", ignore=1) if status != 'PASS': gp.qprint_error("Call to my_ffdc failed.\n") # Leave a record for caller that "soft" errors occurred. soft_errors = 1 gpu.save_plug_in_value(soft_errors, pgm_name) if delete_errlogs: # We need to purge error logs between boots or they build up. grk.run_key("Delete Error logs", ignore=1) boot_results.print_report() gp.qprint_timen("Finished boot " + str(boot_count) + ".") plug_in_setup() rc, shell_rc, failed_plug_in_name = grpi.rprocess_plug_in_packages( call_point='stop_check', shell_rc=stop_test_rc(), stop_on_non_zero_rc=1) if shell_rc == stop_test_rc(): message = "Stopping as requested by user.\n" gp.print_time(message) BuiltIn().fail(message) # This should help prevent ConnectionErrors. grk.run_key_u("Close All Connections") return True
def __init__(self): self._element_finder = ElementFinder() self._bi = BuiltIn()
def chain_sleep(self, time_, reason=None): """ Add a sleep to the action chains """ self.__lazy_init_action_chains()._actions.append( lambda: BuiltIn().sleep(time_, reason))
def __init__(self): self._cache = robot.utils.ConnectionCache('No sessions created') self.builtin = BuiltIn() self.debug = 0
def s2l(self): return BuiltIn().get_library_instance('Selenium2Library')
def load_traffic(self, file_path): BuiltIn().log_to_console( 'WARNING: `Load Traffic` is deprecated. Using `Load Config` instead') self.load_config(file_path)
def __init__(self, name, console=False, level='INFO'): """ Logger class for Toby Logger class creates log files for Toby. The log filename will be of format <logFileName>.<pid>.log. By default log files gets created under current working directory. User can override this by setting ENV var TOBY_LOG_FOLDER or pass it with -d option in robot to full path. The logs are of the format [<date-timestamp>] [<methodName>:<lineNum>:<fileName>] [<level>] : <log message> The following sample code section illustrate the usage of Logger class:: -class Device(object): - def __init__(self, dev_name="test"): - self.logger = Logger(dev_name) # Logger object creation for device dev_name - - my_dev.log.info("Trying to connect to {0} using {1} ...". - format(self.host, kwargs['connect_mode'])) - my_dev.log.info(message='In connect') - Toby will create logger object by default and it can be used like below. t.log(level='INFO', message='In connect') # Sample log statement: [2016-07-22 15:02:13] [<module>():123:toby_logger.py] INFO: Log name...myDevice.0 :param name: *MANDATORY* mandatory Logger name variable. :return: Logger object to log data """ self.robot_log_level = None try: from robot.libraries.BuiltIn import BuiltIn _builtin = BuiltIn() self.robot_log_level = _builtin.get_variable_value("${LOG_LEVEL}") except: pass if "TOBY_LOG_LEVEL" in os.environ: level = os.environ['TOBY_LOG_LEVEL'] self._level = getattr(logging, level.upper(), logging.INFO) self.log = logging.getLogger(name) self._script_name = get_script_name() if name != self._script_name: name = '.'.join([self._script_name, name]) try: self._log_dir = get_log_dir() if not os.path.exists(self._log_dir): os.makedirs(self._log_dir) self._log_filename = os.path.join(self._log_dir, '.'.join([name, 'log'])) file_handler = logging.FileHandler(self._log_filename) formatter = logging.Formatter( '[%(asctime)s] [%(levelname)s] [%(funcName)s():%(lineno)d:%(filename)s] %(message)s',\ '%Y-%m-%d %H:%M:%S') file_handler.setFormatter(formatter) super(Logger, self).__init__(name) super(Logger, self).addHandler(file_handler) super(Logger, self).setLevel(self._level) if console: # Add console handler to print logs to console console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(formatter) super(Logger, self).addHandler(console_handler) except Exception as error: message = "Cannot get log directory due to the following error: {}".format(error.__str__()) raise TobyFileIOException(message=message)
from robot.libraries.BuiltIn import BuiltIn bi = BuiltIn() sl = BuiltIn().get_library_instance("SeleniumLibrary") # LINKS # 14. Check user can navigate to "Instagram" page def navigate_to_inst_page(): sl.maximize_browser_window() sl.scroll_element_into_view('css = #shopify-section-1583924377266 > div') sl.click_element('css = div.feature-row__item.feature-row__text.feature-row__text--left > a') sl.wait_until_page_contains('Mónteza Official (@montezaofficial)') # 15. Check user can navigate to "Terms, Conditions, and Policies" page def navigate_to_terms_page(): sl.click_link('css = a[href="https://monteza.shop/pages/refund-policy"]') sl.wait_until_page_contains('Terms, Conditions, and Policies') # OTHER # 16. Check "Youtube" video block functionality def youtube_block(): sl.maximize_browser_window() sl.scroll_element_into_view('css = #shopify-section-1583925646832') sl.select_frame('css = div.video-wrapper iframe') sl.click_button('css = button.ytp-large-play-button.ytp-button') sl.wait_until_page_contains_element('css = div.playing-mode')
def pause_on_failure(self): has_failed = BuiltIn().get_variable_value("${SUITE_STATUS}") == 'FAIL' if self.__is_debug_mode and has_failed: BuiltIn().run_keyword( "Pause Execution", "Paused due to task failure, click OK to continue teardown")
def Clear_Highlight_Element(locator): seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary') element = seleniumlib._element_finder.find(locator, None, True, True) seleniumlib._current_browser().execute_script( "arguments[0].style['outline'] = '';", element)
def input_select_logical_interconnect_group(cls, bay, logical_interconnect_group, timeout=5): logger.debug("choose LIG '%s' for bay '%s'" % (logical_interconnect_group, bay)) ui_lib.wait_for_element_and_input_text(CreateEnclosureGroupElements.ID_INPUT_C7000_CHOOSE_LIG % bay, "", timeout, fail_if_false=True) ui_lib.wait_for_element_and_input_text(CreateEnclosureGroupElements.ID_INPUT_C7000_CHOOSE_LIG % bay, logical_interconnect_group, timeout, fail_if_false=True) BuiltIn().sleep(3) ui_lib.wait_for_element_and_click(CreateEnclosureGroupElements.ID_COMBO_C7000_OPTION_LIG % (bay, logical_interconnect_group), timeout, fail_if_false=True)