def __init__(self, dev_tty=None, baudrate=115200, **kwargs): self.PROMPT = PROMPT_swi_qct self.LOGIN = LOGIN_swi_qct self.dev_tty = dev_tty swilog.debug("Serial init %s %s" % (dev_tty, baudrate)) self.target = self
def is_port_accessible(self, port_type=com.ComPortType.CLI.name): """Check if specified port is accessible.""" link = self.get_link(port_type) if not link: return False link_obj = link.obj if not link_obj: return False if not hasattr(link_obj, "fd") or link_obj.fd == -1: return False if link_obj.closed: return False # if CLI was pre-defined with a valid fd but device name has been changed re_opened_port = com.SerialPort.open(link_obj.dev_tty) if not re_opened_port: return False try: re_opened_port.close() except Exception as e: swilog.debug(e) return self.is_port_responsive(port_type)
def close(self): """Close the opened fd.""" if hasattr(self, "fd"): try: os.close(self.fd) except Exception as e: swilog.debug(e)
def check_communication(self, timeout=1): """Check that is possible to connect with the communication link. Args: timeout: timeout in second """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) rsp = 1 try: sock.connect((self.target_ip, self.ssh_port)) data = sock.recv(64) sock.close() if not data or len(data) == 0: rsp = 1 else: swilog.debug("Connected to %s %d" % (self.target_ip, self.ssh_port)) rsp = 0 except Exception: rsp = 1 if rsp == 1: swilog.debug("Impossible to connect to %s %d" % (self.target_ip, self.ssh_port)) return rsp
def close(self): """Close the fd.""" try: os.close(self.fd) super().close() except OSError as e: swilog.debug(e)
def restart_syslog(target, legato): """Restart syslog and try to re-mount the log socket. Since sandbox is persistent May 2016. :param target: fixture to communicate with the target :param legato: fixture to call useful functions regarding legato """ # Restart syslogd to have a clean slate of logs legato.clear_target_log() # (May 2016) Since sandbox is now persistent, # the log socket has to be re-mounted. # If an app has already started, doing the above without re-mounting # the log socket will cause the app's logs not showing up in syslog. # Consider putting this in common.sh. # Another solution is, instead of restarting syslogd, # do "logread -f > logfile &" at the point where log needs to be captured # (typically before test app start), and kill that process # and grep logfile when test app finishes. It's less convenient. test_app_log_socket = "/legato/systems/current/appsWriteable/%s/dev/log" % APP_NAME exit_status, rsp = target.run( "umount %s" % test_app_log_socket, withexitstatus=True ) swilog.debug(rsp) assert exit_status == 0, "[FAILED] Unmount failed." exit_status, rsp = target.run( "mount --bind /dev/log %s" % test_app_log_socket, withexitstatus=True ) swilog.debug(rsp) assert exit_status == 0, "[FAILED] Mount failed."
def teardown(self): """Tear down link.""" for link in self.links.values(): try: link.close() except Exception as e: swilog.debug(e)
def handle(self): """Handle the TCP connection. Echo back data sent to server from client. """ swilog.debug( "[TCP SERVER] Call TCP handle and wait for {} bytes".format( self.server.max_size)) # self.server.timeout is used to set the socket timeout timeout = self.server.timeout if self.server.timeout is not None else 15 self.request.settimeout(timeout) while 1: try: self.data = self.request.recv(self.server.max_size).strip() if len(self.data) != 0: swilog.debug("[TCP SERVER] {} received {} bytes:".format( self.client_address[0], len(self.data))) swilog.debug(self.data) if self.server.responder and len(self.data) != 0: swilog.debug("[TCP SERVER] Send data") self.request.sendall(self.data) self.server.cur_data += self.data if self.server._BaseServer__shutdown_request or len( self.data) == 0: break except Exception as e: # Usually due to timeout swilog.debug("[TCP SERVER] %s" % (e)) if (hasattr(self.server, "_BaseServer__shutdown_request") and self.server._BaseServer__shutdown_request): break # Do not close the socket too early time.sleep(self.server.wait_after_transaction)
def run_at_cmd(self, at_cmd, timeout=20, expect_rsp=None, check=True, eol="\r"): """Run and check AT commands.""" if self.links[2].info.is_used() and self.link2: return super().run_at_cmd(at_cmd, timeout, expect_rsp, check, eol) cmd = "/usr/bin/microcom /dev/ttyAT" self.sendline(cmd) time.sleep(1) try: rsp = com.run_at_cmd_and_check(self, at_cmd, timeout, expect_rsp, check, eol) except Exception as e: # Exit from microcom if exception self.sendcontrol("x") raise TargetException(e) try: self.sendcontrol("x") self.prompt() except pexpect.EOF: swilog.debug("pexpect eof") return rsp
def get_marker_config(item): """Get the marker configs pytest.mark.""" marker = item.get_closest_marker("config") marker_configs = [] if marker is not None: swilog.debug("use extra config file %s " % marker.args[0]) marker_configs = [item.get_closest_marker("config").args[0]] return TestConfigsParser(marker_configs)
def wait_for_device_up(self, timeout): """Wait for promp or login.""" clear_buffer(self) swilog.debug("wait for up") self.sendline("") status = self.expect([pexpect.TIMEOUT, self.LOGIN, self.PROMPT], timeout) return 0 if status == 1 or status == 2 else 1
def tcp_server(read_config_default): """Create up to 4 TCP servers. It is possible to create up to 4 UDP and 4 TCP servers with LeTP. The servers will be created at startup and deleted at the end of the LeTP session. In host.xml, fill the port and IP address of each servers and indicates used="1". The IP address is optional because by default it takes "host/ip_address". Use the fixture tcp_server or udp_server in your test to get the list of the TCP/UDP servers you declared. .. code-block:: python def test_tcp_server(tcp_server, read_config): for i, serv in enumerate(tcp_server): swilog.step("server %d" % i) ip = read_config.findtext( "host/socket_server/tcp_%d/addr" % (i+1)) port = int(read_config.findtext( "host/socket_server/tcp_%d/port" % (i+1))) """ # Fixture based on default configuration # Do not use read_config which is function scope assert isinstance(read_config_default, ET.ElementTree) serv_list = [] swilog.debug("start TCP servers") for i in range(1, 5): if read_config_default.find("host/socket_server/tcp_%d" % i).get("used") == "1": ip = read_config_default.findtext( "host/socket_server/tcp_%d/addr" % i) if ip == "": # Take the Ip address of the host ip = read_config_default.findtext("host/ip_address") if ip == "": assert 0, "Set the ip address of your host or of your server" port = int( read_config_default.findtext("host/socket_server/tcp_%d/port" % i)) assert port != "", "TCP/UDP IP server is set but no port" serv = socket_server.get_tcp_server(ip, port, responder=True, max_size=1000000) serv_list.append(serv) if len(serv_list) == 0: assert 0, ("Set the ip address of your host or of " "your server or set the used attribute to 1") yield serv_list swilog.debug("TCP servers shutdown!") for serv in serv_list: serv.shutdown() serv.server_close()
def L_AtomicFile_Stream_0023(target, legato, init_atomicFile): """Purpose: Verify that le_atomFile_TryOpenStream can successfully. acquire a file lock to the target file Initial condition: 1. Test app is unsandboxed Verification: This test case will mark as "failed" when 1. The second process who calls le_atomFile_OpenStream does not block after the first process of the test app held the file lock This script will 1. Transfer a file to the target 1. Make and install the test app 2. Run the test app 3. Check the second process does block after the first process successfully acquired the lock == 0: :param target: fixture to communicate with the target :param legato: fixture to call useful functions regarding legato :param app_leg: fixture regarding to build, install and remove app :param init_atomicFile: fixture to initialize and clean up environment """ test_app_name = "atomTryOpenStream" test_app_proc_name = "atomTryOpenStreamProc" hw_file_path = os.path.join(TEST_TOOLS, "testFile.txt") test_file_path = "/home/root/testFile.txt" test_description = "acquireFlock" swilog.debug(init_atomicFile) # Wait for the occurrence of the specified message in the target's log # Pre: # Param: $1 - message to be expected from the log; $2 - wait time period # Post: return 0 when the message has been found; 1 otherwise files.scp([hw_file_path], test_file_path, target.target_ip) legato.clear_target_log() legato.runProc(test_app_name, test_app_proc_name, test_file_path, test_description) assert legato.wait_for_log_msg("first process is holding a file lock", 5) is True, ("[FAILED] the first process " "can't acquire a file lock " "when it calls " "le_atomFile_TryOpenStream") assert (legato.wait_for_log_msg("second process is holding a file lock", 120) is True), ("[FAILED] " "le_atomFile_TryOpenStream" " can't successfully " "acquire a file lock to the" " target file")
def L_UpdateCtrl_Defer_0006(target, legato): """Verify that the deferral will be released after. stopping the client (process) who called le_updateCtrl_Defer() Testing Procedures: 1. Install the app that invokes le_updateCtrl_Defer() onto the target device 2. Run the app 3. Stop the app 4. Install the helloWorld app 5. Check 4. is successful :param target: fixture to communicate with the target :param legato: fixture to call useful functions regarding legato :param install_and_clean_app: fixture to clean up environment and build app """ swilog.step("Test L_UpdateCtrl_Defer_0006") # Begin of the this TC # Set the parameter of the testUpdateCtrl app to # "defer" "4" to run this test case target.run( "config set apps/%s/procs/%s/args/1 defer" % (UPDATE_CTRL_APP, UPDATE_CTRL_APP) ) target.run( "config set apps/%s/procs/%s/args/2 6" % (UPDATE_CTRL_APP, UPDATE_CTRL_APP) ) # Run the testUpdateCtrl app that will invoke le_updateCtrl_Defer() status, rsp = target.run("app start %s" % UPDATE_CTRL_APP, withexitstatus=True) swilog.debug(rsp) assert status == 0, "[FAILED] App could not be started." # Stop the testUPdateCtrl app which is holding a defer lock status, rsp = target.run("app stop %s" % UPDATE_CTRL_APP, withexitstatus=True) swilog.debug(rsp) assert status == 0, "[FAILED] App could not be stopped." # Clean environment legato.clean(UPDATE_CTRL_APP, remove_app=False) # Check whether defer lock is released so that # any system update is allowed by installing # The helloWorld app when when the client (process) # who called le_updateCtrl_Defer() is stopped legato.make_install(UPDATE_CTRL_APP, UPDATE_CTRL_PATH) # If the target device is not shutting down then, # killing the process who holds the defer lock # Won't cause reboot. Marked this test case failed swilog.info( "[PASSED] defer lock was released after a" " process which called Defer() is stopped" ) swilog.info("[PASSED] Test L_UpdateCtrl_Defer_0006")
def test_debug_level(): """Test debug values in different levels.""" print("test debug starts") swilog.debug("debug level message") swilog.info("info level message") swilog.warning("warning level message") swilog.error("error level message") swilog.critical("critical level message") print("test debug ends")
def L_UpdateCtrl_Defer_0002(target, legato): """Verify that le_updateCtrl_Defer() prevents all updates. (install an app) Initial Condition: 1. Current system index is "N" Test Procedures: 1. Install the app that invokes le_updateCtrl_Defer() onto the target device 2. Check the current system index is "N + 1"and run the app 3. Install an app (e.g. helloWorld) onto the target device 4. Check "Updates are currently deferred" is shown from log 5. Check the app is not installed on the target device (verified by the command line "app list") 6. Check the current system index is "N + 1" (Notes: the current system index, the current system state and the current system status can be verified by the command line "legato status") :param target: fixture to communicate with the target :param legato: fixture to call useful functions regarding legato :param install_and_clean_app: fixture to clean up environment and build app """ swilog.step("Test L_UpdateCtrl_Defer_0002") # Set the parameter of the testUpdateCtrl app to # "defer" "2" to run this test case target.run( "config set apps/%s/procs/%s/args/1 defer" % (UPDATE_CTRL_APP, UPDATE_CTRL_APP) ) target.run( "config set apps/%s/procs/%s/args/2 2" % (UPDATE_CTRL_APP, UPDATE_CTRL_APP) ) # Run the testUpdateCtrl app that will invoke le_updateCtrl_Defer() status, rsp = target.run("app start %s" % UPDATE_CTRL_APP, withexitstatus=True) swilog.debug(rsp) assert status == 0, "[FAILED] App could not be started." # Perform an update to the system by installing the new helloWorld app # If the installation was successful then, # the system update attempt is proceed legato.make(HELLO_WORLD_APP, HELLO_WORLD_PATH) legato.install(HELLO_WORLD_APP, HELLO_WORLD_PATH, should_fail=True) # If the system update was successful, # the update was allowed and mark this TC failed swilog.info( "[PASSED] Defer() doesn't allow update to \ happen when attempting to install an app" ) swilog.info("[PASSED] Test L_UpdateCtrl_Defer_0002")
def set_test_app_repeat_cycle(target, test_cycle): """Set test cycle for test app. :param target: fixture to communicate with the target :param test_cycle: cycle of test is set in config tree """ cmd = 'config set "/apps/%s/procs/%s/args/2" %s' % (APP_NAME, APP_NAME, test_cycle) exit_status, rsp = target.run(cmd, withexitstatus=True) swilog.debug(rsp) assert exit_status == 0
def _run_test_define_target_with_only_at(letp_cmd, module_name): cmd = ("{} run --dbg-lvl 0 ".format(letp_cmd) + "scenario/command/test_target_fixtures_stub.py::" "test_define_target_with_only_at " "--config module/slink2(used)=1 " "--config host/ip_address=10.1.4.59 " "--config module/ssh(used)=0 " "--config module/name={} ".format(module_name)) output = run_python_with_command(cmd) swilog.debug(output) check_letp_nb_tests(output, number_of_passed=1)
def init(self): """Provide a generic way to initialize a link.""" swilog.debug("[Link %s] init" % self.name) if callable(self.init_cb): try: return self.init_cb(self) except Exception as e: swilog.debug(e) raise SlinkException(e) swilog.warning("No init function has been provided for link %s" % self.name) return None
def set_test_app_test_type(target, test_type): """Set test type for test app. :param target: fixture to communicate with the target :param test_type: type of test is set in config tree (read, write, delete, writeread, writedeleteread...) """ cmd = 'config set "/apps/%s/procs/%s/args/1" %s' % (APP_NAME, APP_NAME, test_type) exit_status, rsp = target.run(cmd, withexitstatus=True) swilog.debug(rsp) assert exit_status == 0
def get_mtd_name(self, mtd_logical_name): """Get the targets mtd name.""" rsp = self.run("cat /proc/mtd") match = re.search(r"(mtd\d+):.+%s" % mtd_logical_name, rsp) if match: mtd_nb = match.group(1) swilog.debug("mtd name: %s, mtd nb: %s" % (mtd_logical_name, mtd_nb)) return mtd_nb else: raise TargetException("Mtd number was not found for %s" % mtd_logical_name)
def get_version(cmd, pattern, console, full=True, target=None): """Return target version.""" pattern = pattern["full"] if full else pattern["parsed"] cmd = cmd[console] if not cmd or not target: return None swilog.debug("command: {}".format(cmd)) swilog.debug("console: {}".format(console)) return target.get_version(cmd, pattern, console)
def is_ssh_connection_accessible(self): """Return True if the ssh connection is accessible.""" if not hasattr(self, "ssh") or not self.ssh: swilog.debug("ssh link wasn't created before") return False if self.ssh.closed: return False if self.ssh.check_communication() != 0: return False return self.ssh.prompt()
def _set_target_alias(self): """Assign every methods from the link object to the module.""" for fn in dir(self.__obj): if not hasattr(self.module, fn): # A method can be already implemented in the upper class. try: setattr(self.module, fn, getattr(self.__obj, fn)) if fn not in self.list_attr: self.list_attr.append(fn) except Exception as e: swilog.debug(e) swilog.warning("Warning: Impossible to set attribute")
def __init__(self, device, baudrate, rtscts=False): """Instantiate serial port wrapper. :param device Device name. :param baudrate Initial baud rate to set. Defaults to port's default if None. """ self._device = device self._baudrate = None swilog.debug("Init of %s" % str(self._device)) device_stat = None try: device_stat = os.stat(device) except OSError: pass if self._device and stat.S_ISCHR(device_stat.st_mode): self.fd = os.open(self._device, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) else: assert 0, "%s not a valid port" % self._device self._tty_attr = termios.tcgetattr(self.fd) self._tty_attr[self.IFLAG] = termios.IGNBRK self._tty_attr[self.OFLAG] = 0 self._tty_attr[self.LFLAG] = 0 self._tty_attr[self.CC] = [0] * 32 if not baudrate: self._tty_attr[self.CFLAG] = termios.CS8 | ( self._tty_attr[self.CFLAG] & termios.CBAUD) else: self._tty_attr[self.CFLAG] = termios.CS8 | self.BAUD[baudrate] self._tty_attr[self.ISPEED] = self._tty_attr[ self.OSPEED] = self.BAUD[baudrate] # Enable receiver, ignore modem control lines self._tty_attr[self.CFLAG] |= termios.CREAD | termios.CLOCAL # Flow control if rtscts: swilog.debug("Hardware flow control is activated") self._tty_attr[self.CFLAG] |= termios.CRTSCTS else: self._tty_attr[self.CFLAG] &= ~termios.CRTSCTS termios.tcsetattr(self.fd, termios.TCSADRAIN, self._tty_attr) self._tty_attr = termios.tcgetattr(self.fd) if not baudrate: baud_value = self._tty_attr[self.CFLAG] & termios.CBAUD for b, v in self.BAUD.items(): if v == baud_value: baudrate = b break self._baudrate = baudrate assert self._baudrate in self.BAUD
def wait_for_app_presence(legato, app_name): """Check application is listed. :param legato: fixture to call useful functions regarding legato :param app_name: name of an application want to check """ swilog.info("Checking application is listed...") timer = 30 while not legato.is_app_exist(app_name): timer = timer - 1 if timer < 0: swilog.debug("Unable to found application in the list") break time.sleep(1)
def test_swilog_call(): """Activate the debug level to see all the messages. Usage:: "letp run --dbg-lvl 0 test/host/scenario/test_swilog.py" """ swilog.debug("debug message") swilog.info("info message") # to highlight a particular step in the test swilog.step("step message") swilog.warning("warning message") swilog.error("error message") swilog.critical("critical message")
def wait_for_app_running(legato, app_name): """Check application is running. :param legato: fixture to call useful functions regarding legato :param app_name: application name needs to be checked """ swilog.info("Checking application is running...") timer = 30 while not legato.is_app_running(app_name): timer = timer - 1 if timer < 0: swilog.debug("The application is not running") break time.sleep(1)
def L_Tools_Kmod_0007(target, legato, create_temp_workspace): """Verify kmod cmd should not be able to unload kernel module. 1. Create an update package with a dependence to an other module (load:auto) and update the target with it 2. Verify loading of both modules 3. Try to unload the required module: it must fail 4. Try to unload the primary module: it must fail 5. Compile the default package and update the target with it :param target: fixture to communicate with the target :param legato: fixture to call useful functions regarding legato :param create_temp_workspace: fixture to create a temporary folder """ # Initialisation: # Verify existence of environment variables and files needed. # Prepare compilation test_name = "L_Tools_Kmod_0007" test_passed = True # Compile and update target swilog.step("Step 1: Compiling...") install_system(target, legato, create_temp_workspace, test_name) swilog.step("Step 2: Verify mods have been loaded...") check_presence_0004 = check_presence(legato, "L_Tools_Kmod_0004") check_presence_0007 = check_presence(legato, test_name) if (not check_presence_0007) or (not check_presence_0004): test_passed = False swilog.error("Step 2: Kernel module have not been properly loaded") # Unloading required module swilog.step("Step 3: Unloading required module...") (returned_value, returned_index) = check_unloading(target, "L_Tools_Kmod_0004", RESULT_BUSY) if not returned_value: test_passed = False swilog.error("Step 3: Unloading should have been forbidden.") # Unloading primary module swilog.step("Step 5: Unloading primary module...") (returned_value, returned_index) = check_unloading(target, test_name, RESULT_OK) if not returned_value: test_passed = False swilog.error("Step 5: Unloading should have been forbidden.") swilog.debug(returned_index) # End of script: Build the default package to reinitialise the target # And clean the LEGATO_ROOT directory assert test_passed, display_errors()
def reinit(self): """Link reconnection (for example after a reboot).""" if self.reinit_in_progress: raise ComException("A reinit is already in progress") self.reinit_in_progress = True swilog.debug("Reinit the ssh connection with %s" % (self.target_ip)) self.pid = None swilog.debug("%s %s" % (self.target_ip, self.ssh_port)) self.__init__(self.target_ip, self.ssh_port, self.config_target, *self.save_args, **self.save_kwargs) self.PROMPT = PROMPT_swi_qct time.sleep(2) self.login() self.reinit_in_progress = False