signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def list_occupied_adb_ports():
out = AdbProxy().forward('<STR_LIT>')<EOL>clean_lines = str(out, '<STR_LIT:utf-8>').strip().split('<STR_LIT:\n>')<EOL>used_ports = []<EOL>for line in clean_lines:<EOL><INDENT>tokens = line.split('<STR_LIT>')<EOL>if len(tokens) != <NUM_LIT:3>:<EOL><INDENT>continue<EOL><DEDENT>used_ports.append(int(tokens[<NUM_LIT:1>]))<EOL><DEDENT>return used_ports<EOL>
Lists all the host ports occupied by adb forward. This is useful because adb will silently override the binding if an attempt to bind to a port already used by adb was made, instead of throwing binding error. So one should always check what ports adb is using before trying to bind to a port with adb. Returns: A list of integers representing occupied host ports.
f7513:m0
def _exec_cmd(self, args, shell, timeout, stderr):
if timeout and timeout <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % timeout)<EOL><DEDENT>try:<EOL><INDENT>(ret, out, err) = utils.run_command(<EOL>args, shell=shell, timeout=timeout)<EOL><DEDENT>except psutil.TimeoutExpired:<EOL><INDENT>raise AdbTimeoutError(<EOL>cmd=args, timeout=timeout, serial=self.serial)<EOL><DEDENT>if stderr:<EOL><INDENT>stderr.write(err)<EOL><DEDENT>logging.debug('<STR_LIT>',<EOL>utils.cli_cmd_to_string(args), out, err, ret)<EOL>if ret == <NUM_LIT:0>:<EOL><INDENT>return out<EOL><DEDENT>else:<EOL><INDENT>raise AdbError(<EOL>cmd=args,<EOL>stdout=out,<EOL>stderr=err,<EOL>ret_code=ret,<EOL>serial=self.serial)<EOL><DEDENT>
Executes adb commands. Args: args: string or list of strings, program arguments. See subprocess.Popen() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs. timeout: float, the number of seconds to wait before timing out. If not specified, no timeout takes effect. stderr: a Byte stream, like io.BytesIO, stderr of the command will be written to this object if provided. Returns: The output of the adb command run if exit code is 0. Raises: ValueError: timeout value is invalid. AdbError: The adb command exit code is not 0. AdbTimeoutError: The adb command timed out.
f7513:c3:m1
def _execute_and_process_stdout(self, args, shell, handler):
proc = subprocess.Popen(<EOL>args,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>shell=shell,<EOL>bufsize=<NUM_LIT:1>)<EOL>out = '<STR_LIT>'<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>line = proc.stdout.readline()<EOL>if line:<EOL><INDENT>handler(line)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>(unexpected_out, err) = proc.communicate()<EOL>if unexpected_out:<EOL><INDENT>out = '<STR_LIT>' % unexpected_out<EOL>for line in unexpected_out.splitlines():<EOL><INDENT>handler(line)<EOL><DEDENT><DEDENT><DEDENT>ret = proc.returncode<EOL>logging.debug('<STR_LIT>',<EOL>utils.cli_cmd_to_string(args), out, err, ret)<EOL>if ret == <NUM_LIT:0>:<EOL><INDENT>return err<EOL><DEDENT>else:<EOL><INDENT>raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret)<EOL><DEDENT>
Executes adb commands and processes the stdout with a handler. Args: args: string or list of strings, program arguments. See subprocess.Popen() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs. handler: func, a function to handle adb stdout line by line. Returns: The stderr of the adb command run if exit code is 0. Raises: AdbError: The adb command exit code is not 0.
f7513:c3:m2
def _construct_adb_cmd(self, raw_name, args, shell):
args = args or '<STR_LIT>'<EOL>name = raw_name.replace('<STR_LIT:_>', '<STR_LIT:->')<EOL>if shell:<EOL><INDENT>args = utils.cli_cmd_to_string(args)<EOL>if self.serial:<EOL><INDENT>adb_cmd = '<STR_LIT>' % (ADB, self.serial, name, args)<EOL><DEDENT>else:<EOL><INDENT>adb_cmd = '<STR_LIT>' % (ADB, name, args)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>adb_cmd = [ADB]<EOL>if self.serial:<EOL><INDENT>adb_cmd.extend(['<STR_LIT>', self.serial])<EOL><DEDENT>adb_cmd.append(name)<EOL>if args:<EOL><INDENT>if isinstance(args, basestring):<EOL><INDENT>adb_cmd.append(args)<EOL><DEDENT>else:<EOL><INDENT>adb_cmd.extend(args)<EOL><DEDENT><DEDENT><DEDENT>return adb_cmd<EOL>
Constructs an adb command with arguments for a subprocess call. Args: raw_name: string, the raw unsanitized name of the adb command to format. args: string or list of strings, arguments to the adb command. See subprocess.Proc() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Proc() docs. Returns: The adb command in a format appropriate for subprocess. If shell is True, then this is a string; otherwise, this is a list of strings.
f7513:c3:m3
def getprop(self, prop_name):
return self.shell(<EOL>['<STR_LIT>', prop_name],<EOL>timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('<STR_LIT:utf-8>').strip()<EOL>
Get a property of the device. This is a convenience wrapper for "adb shell getprop xxx". Args: prop_name: A string that is the name of the property to get. Returns: A string that is the value of the property, or None if the property doesn't exist.
f7513:c3:m6
def has_shell_command(self, command):
try:<EOL><INDENT>output = self.shell(['<STR_LIT>', '<STR_LIT>',<EOL>command]).decode('<STR_LIT:utf-8>').strip()<EOL>return command in output<EOL><DEDENT>except AdbError:<EOL><INDENT>return False<EOL><DEDENT>
Checks to see if a given check command exists on the device. Args: command: A string that is the name of the command to check. Returns: A boolean that is True if the command exists and False otherwise.
f7513:c3:m7
def instrument(self, package, options=None, runner=None, handler=None):
if runner is None:<EOL><INDENT>runner = DEFAULT_INSTRUMENTATION_RUNNER<EOL><DEDENT>if options is None:<EOL><INDENT>options = {}<EOL><DEDENT>options_list = []<EOL>for option_key, option_value in options.items():<EOL><INDENT>options_list.append('<STR_LIT>' % (option_key, option_value))<EOL><DEDENT>options_string = '<STR_LIT:U+0020>'.join(options_list)<EOL>instrumentation_command = '<STR_LIT>' % (<EOL>options_string, package, runner)<EOL>logging.info('<STR_LIT>', self.serial,<EOL>instrumentation_command)<EOL>if handler is None:<EOL><INDENT>self._exec_adb_cmd(<EOL>'<STR_LIT>',<EOL>instrumentation_command,<EOL>shell=False,<EOL>timeout=None,<EOL>stderr=None)<EOL><DEDENT>else:<EOL><INDENT>return self._execute_adb_and_process_stdout(<EOL>'<STR_LIT>', instrumentation_command, shell=False, handler=handler)<EOL><DEDENT>
Runs an instrumentation command on the device. This is a convenience wrapper to avoid parameter formatting. Example: .. code-block:: python device.instrument( 'com.my.package.test', options = { 'class': 'com.my.package.test.TestSuite', }, ) Args: package: string, the package of the instrumentation tests. options: dict, the instrumentation options including the test class. runner: string, the test runner name, which defaults to DEFAULT_INSTRUMENTATION_RUNNER. handler: optional func, when specified the function is used to parse the instrumentation stdout line by line as the output is generated; otherwise, the stdout is simply returned once the instrumentation is finished. Returns: The stdout of instrumentation command or the stderr if the handler is set.
f7513:c3:m9
def create(configs):
objs = []<EOL>for c in configs:<EOL><INDENT>sniffer_type = c["<STR_LIT>"]<EOL>sniffer_subtype = c["<STR_LIT>"]<EOL>interface = c["<STR_LIT>"]<EOL>base_configs = c["<STR_LIT>"]<EOL>module_name = "<STR_LIT>".format(<EOL>sniffer_type, sniffer_subtype)<EOL>module = importlib.import_module(module_name)<EOL>objs.append(module.Sniffer(interface,<EOL>logging.getLogger(),<EOL>base_configs=base_configs))<EOL><DEDENT>return objs<EOL>
Initializes the sniffer structures based on the JSON configuration. The expected keys are: * Type: A first-level type of sniffer. Planned to be 'local' for sniffers running on the local machine, or 'remote' for sniffers running remotely. * SubType: The specific sniffer type to be used. * Interface: The WLAN interface used to configure the sniffer. * BaseConfigs: A dictionary specifying baseline configurations of the sniffer. Configurations can be overridden when starting a capture. The keys must be one of the Sniffer.CONFIG_KEY_* values.
f7514:m0
def destroy(objs):
for sniffer in objs:<EOL><INDENT>try:<EOL><INDENT>sniffer.stop_capture()<EOL><DEDENT>except SnifferError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Destroys the sniffers and terminates any ongoing capture sessions.
f7514:m1
def __init__(self, interface, logger, base_configs=None):
raise NotImplementedError("<STR_LIT>")<EOL>
The constructor for the Sniffer. It constructs a sniffer and configures it to be ready for capture. Args: interface: A string specifying the interface used to configure the sniffer. logger: Mobly logger object. base_configs: A dictionary containing baseline configurations of the sniffer. These can be overridden when staring a capture. The keys are specified by Sniffer.CONFIG_KEY_*. Returns: self: A configured sniffer. Raises: InvalidDataError: if the config_path is invalid. NoPermissionError: if an error occurs while configuring the sniffer.
f7514:c4:m0
def get_descriptor(self):
raise NotImplementedError("<STR_LIT>")<EOL>
This function returns a string describing the sniffer. The specific string (and its format) is up to each derived sniffer type. Returns: A string describing the sniffer.
f7514:c4:m1
def get_type(self):
raise NotImplementedError("<STR_LIT>")<EOL>
This function returns the type of the sniffer. Returns: The type (string) of the sniffer. Corresponds to the 'Type' key of the sniffer configuration.
f7514:c4:m2
def get_subtype(self):
raise NotImplementedError("<STR_LIT>")<EOL>
This function returns the sub-type of the sniffer. Returns: The sub-type (string) of the sniffer. Corresponds to the 'SubType' key of the sniffer configuration.
f7514:c4:m3
def get_interface(self):
raise NotImplementedError("<STR_LIT>")<EOL>
This function returns The interface used to configure the sniffer, e.g. 'wlan0'. Returns: The interface (string) used to configure the sniffer. Corresponds to the 'Interface' key of the sniffer configuration.
f7514:c4:m4
def get_capture_file(self):
raise NotImplementedError("<STR_LIT>")<EOL>
The sniffer places a capture in the logger directory. This function enables the caller to obtain the path of that capture. Returns: The full path of the current or last capture.
f7514:c4:m5
def start_capture(self,<EOL>override_configs=None,<EOL>additional_args=None,<EOL>duration=None,<EOL>packet_count=None):
raise NotImplementedError("<STR_LIT>")<EOL>
This function starts a capture which is saved to the specified file path. Depending on the type/subtype and configuration of the sniffer the capture may terminate on its own or may require an explicit call to the stop_capture() function. This is a non-blocking function so a terminating function must be called either explicitly or implicitly: * Explicitly: call either stop_capture() or wait_for_capture() * Implicitly: use with a with clause. The wait_for_capture() function will be called if a duration is specified (i.e. is not None), otherwise a stop_capture() will be called. The capture is saved to a file in the log path of the logger. Use the get_capture_file() to get the full path to the current or most recent capture. Args: override_configs: A dictionary which is combined with the base_configs ("BaseConfigs" in the sniffer configuration). The keys (specified by Sniffer.CONFIG_KEY_*) determine the configuration of the sniffer for this specific capture. additional_args: A string specifying additional raw command-line arguments to pass to the underlying sniffer. The interpretation of these flags is sniffer-dependent. duration: An integer specifying the number of seconds over which to capture packets. The sniffer will be terminated after this duration. Used in implicit mode when using a 'with' clause. In explicit control cases may have to be performed using a sleep+stop or as the timeout argument to the wait function. packet_count: An integer specifying the number of packets to capture before terminating. Should be used with duration to guarantee that capture terminates at some point (even if did not capture the specified number of packets). Returns: An ActiveCaptureContext process which can be used with a 'with' clause. Raises: InvalidDataError: for invalid configurations NoPermissionError: if an error occurs while configuring and running the sniffer.
f7514:c4:m6
def stop_capture(self):
raise NotImplementedError("<STR_LIT>")<EOL>
This function stops a capture and guarantees that the capture is saved to the capture file configured during the start_capture() method. Depending on the type of the sniffer the file may previously contain partial results (e.g. for a local sniffer) or may not exist until the stop_capture() method is executed (e.g. for a remote sniffer). Depending on the type/subtype and configuration of the sniffer the capture may terminate on its own without requiring a call to this function. In such a case it is still necessary to call either this function or the wait_for_capture() function to make sure that the capture file is moved to the correct location. Raises: NoPermissionError: No permission when trying to stop a capture and save the capture file.
f7514:c4:m7
def wait_for_capture(self, timeout=None):
raise NotImplementedError("<STR_LIT>")<EOL>
This function waits for a capture to terminate and guarantees that the capture is saved to the capture file configured during the start_capture() method. Depending on the type of the sniffer the file may previously contain partial results (e.g. for a local sniffer) or may not exist until the stop_capture() method is executed (e.g. for a remote sniffer). Depending on the type/subtype and configuration of the sniffer the capture may terminate on its own without requiring a call to this function. In such a case it is still necessary to call either this function or the stop_capture() function to make sure that the capture file is moved to the correct location. Args: timeout: An integer specifying the number of seconds to wait for the capture to terminate on its own. On expiration of the timeout the sniffer is stopped explicitly using the stop_capture() function. Raises: NoPermissionError: No permission when trying to stop a capture and save the capture file.
f7514:c4:m8
def _validate_config(config):
required_keys = [KEY_ADDRESS, KEY_MODEL, KEY_PORT, KEY_PATHS]<EOL>for key in required_keys:<EOL><INDENT>if key not in config:<EOL><INDENT>raise Error("<STR_LIT>",<EOL>(key, config))<EOL><DEDENT><DEDENT>
Verifies that a config dict for an attenuator device is valid. Args: config: A dict that is the configuration for an attenuator device. Raises: attenuator.Error: A config is not valid.
f7515:m2
def set_atten(self, value):
self.attenuation_device.set_atten(self.idx, value)<EOL>
This function sets the attenuation of Attenuator. Args: value: This is a floating point value for nominal attenuation to be set. Unit is db.
f7515:c1:m1
def get_atten(self):
return self.attenuation_device.get_atten(self.idx)<EOL>
Gets the current attenuation setting of Attenuator. Returns: A float that is the current attenuation value. Unit is db.
f7515:c1:m2
def get_max_atten(self):
return self.attenuation_device.max_atten<EOL>
Gets the max attenuation supported by the Attenuator. Returns: A float that is the max attenuation value.
f7515:c1:m3
def _has_data(self):
return ('<STR_LIT:end>' in self.result) and ('<STR_LIT>' in self.result["<STR_LIT:end>"])<EOL>
Checks if the iperf result has valid throughput data. Returns: True if the result contains throughput data. False otherwise.
f7516:c0:m1
def get_json(self):
return self.result<EOL>
Returns: The raw json output from iPerf.
f7516:c0:m2
@property<EOL><INDENT>def avg_rate(self):<DEDENT>
if not self._has_data or '<STR_LIT>' not in self.result['<STR_LIT:end>']:<EOL><INDENT>return None<EOL><DEDENT>bps = self.result['<STR_LIT:end>']['<STR_LIT>']['<STR_LIT>']<EOL>return bps / <NUM_LIT:8> / <NUM_LIT> / <NUM_LIT><EOL>
Average receiving rate in MB/s over the entire run. If the result is not from a success run, this property is None.
f7516:c0:m4
@property<EOL><INDENT>def avg_receive_rate(self):<DEDENT>
if not self._has_data or '<STR_LIT>' not in self.result['<STR_LIT:end>']:<EOL><INDENT>return None<EOL><DEDENT>bps = self.result['<STR_LIT:end>']['<STR_LIT>']['<STR_LIT>']<EOL>return bps / <NUM_LIT:8> / <NUM_LIT> / <NUM_LIT><EOL>
Average receiving rate in MB/s over the entire run. This data may not exist if iperf was interrupted. If the result is not from a success run, this property is None.
f7516:c0:m5
@property<EOL><INDENT>def avg_send_rate(self):<DEDENT>
if not self._has_data or '<STR_LIT>' not in self.result['<STR_LIT:end>']:<EOL><INDENT>return None<EOL><DEDENT>bps = self.result['<STR_LIT:end>']['<STR_LIT>']['<STR_LIT>']<EOL>return bps / <NUM_LIT:8> / <NUM_LIT> / <NUM_LIT><EOL>
Average sending rate in MB/s over the entire run. This data may not exist if iperf was interrupted. If the result is not from a success run, this property is None.
f7516:c0:m6
def start(self, extra_args="<STR_LIT>", tag="<STR_LIT>"):
if self.started:<EOL><INDENT>return<EOL><DEDENT>utils.create_dir(self.log_path)<EOL>if tag:<EOL><INDENT>tag = tag + '<STR_LIT:U+002C>'<EOL><DEDENT>out_file_name = "<STR_LIT>".format(<EOL>self.port, tag, len(self.log_files))<EOL>full_out_path = os.path.join(self.log_path, out_file_name)<EOL>cmd = '<STR_LIT>' % (self.iperf_str, extra_args, full_out_path)<EOL>self.iperf_process = utils.start_standing_subprocess(cmd, shell=True)<EOL>self.log_files.append(full_out_path)<EOL>self.started = True<EOL>
Starts iperf server on specified port. Args: extra_args: A string representing extra arguments to start iperf server with. tag: Appended to log file name to identify logs from different iperf runs.
f7516:c1:m1
def __init__(self, config_path, logger, base_configs=None):
self._executable_path = None<EOL>super().__init__(config_path, logger, base_configs=base_configs)<EOL>self._executable_path = (shutil.which("<STR_LIT>")<EOL>or shutil.which("<STR_LIT>"))<EOL>if self._executable_path is None:<EOL><INDENT>raise sniffer.SnifferError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>
See base class documentation
f7517:c0:m0
def get_descriptor(self):
return "<STR_LIT>".format(self._interface)<EOL>
See base class documentation
f7517:c0:m1
def get_subtype(self):
return "<STR_LIT>"<EOL>
See base class documentation
f7517:c0:m2
def __init__(self, config_path, logger, base_configs=None):
self._executable_path = None<EOL>super().__init__(config_path, logger, base_configs=base_configs)<EOL>self._executable_path = shutil.which("<STR_LIT>")<EOL>if self._executable_path is None:<EOL><INDENT>raise sniffer.SnifferError(<EOL>"<STR_LIT>")<EOL><DEDENT>
See base class documentation
f7518:c0:m0
def get_descriptor(self):
return "<STR_LIT>".format(self._interface)<EOL>
See base class documentation
f7518:c0:m1
def get_subtype(self):
return "<STR_LIT>"<EOL>
See base class documentation
f7518:c0:m2
def __init__(self, interface, logger, base_configs=None):
self._base_configs = None<EOL>self._capture_file_path = "<STR_LIT>"<EOL>self._interface = "<STR_LIT>"<EOL>self._logger = logger<EOL>self._process = None<EOL>self._temp_capture_file_path = "<STR_LIT>"<EOL>if interface == "<STR_LIT>":<EOL><INDENT>raise sniffer.InvalidDataError("<STR_LIT>")<EOL><DEDENT>self._interface = interface<EOL>self._base_configs = base_configs<EOL>try:<EOL><INDENT>subprocess.check_call(['<STR_LIT>', self._interface, '<STR_LIT>'])<EOL>subprocess.check_call(<EOL>['<STR_LIT>', self._interface, '<STR_LIT>', '<STR_LIT>'])<EOL>subprocess.check_call(['<STR_LIT>', self._interface, '<STR_LIT>'])<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise sniffer.ExecutionError(err)<EOL><DEDENT>
See base class documentation
f7519:c0:m0
def get_interface(self):
return self._interface<EOL>
See base class documentation
f7519:c0:m1
def get_type(self):
return "<STR_LIT>"<EOL>
See base class documentation
f7519:c0:m2
def _pre_capture_config(self, override_configs=None):
final_configs = {}<EOL>if self._base_configs:<EOL><INDENT>final_configs.update(self._base_configs)<EOL><DEDENT>if override_configs:<EOL><INDENT>final_configs.update(override_configs)<EOL><DEDENT>if sniffer.Sniffer.CONFIG_KEY_CHANNEL in final_configs:<EOL><INDENT>try:<EOL><INDENT>subprocess.check_call([<EOL>'<STR_LIT>',<EOL>self._interface,<EOL>'<STR_LIT>',<EOL>str(final_configs[sniffer.Sniffer.CONFIG_KEY_CHANNEL])])<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise sniffer.ExecutionError(err)<EOL><DEDENT><DEDENT>
Utility function which configures the wireless interface per the specified configurations. Operation is performed before every capture start using baseline configurations (specified when sniffer initialized) and override configurations specified here.
f7519:c0:m4
def _get_command_line(self, additional_args=None, duration=None,<EOL>packet_count=None):
raise NotImplementedError("<STR_LIT>")<EOL>
Utility function to be implemented by every child class - which are the concrete sniffer classes. Each sniffer-specific class should derive the command line to execute its sniffer based on the specified arguments.
f7519:c0:m5
def _post_process(self):
self._process = None<EOL>shutil.move(self._temp_capture_file_path, self._capture_file_path)<EOL>
Utility function which is executed after a capture is done. It moves the capture file to the requested location.
f7519:c0:m6
def start_capture(self, override_configs=None,<EOL>additional_args=None, duration=None,<EOL>packet_count=None):
if self._process is not None:<EOL><INDENT>raise sniffer.InvalidOperationError(<EOL>"<STR_LIT>")<EOL><DEDENT>capture_dir = os.path.join(self._logger.log_path,<EOL>"<STR_LIT>".format(self._interface))<EOL>os.makedirs(capture_dir, exist_ok=True)<EOL>self._capture_file_path = os.path.join(capture_dir,<EOL>"<STR_LIT>".format(logger.get_log_file_timestamp()))<EOL>self._pre_capture_config(override_configs)<EOL>_, self._temp_capture_file_path = tempfile.mkstemp(suffix="<STR_LIT>")<EOL>cmd = self._get_command_line(additional_args=additional_args,<EOL>duration=duration, packet_count=packet_count)<EOL>self._process = utils.start_standing_subprocess(cmd)<EOL>return sniffer.ActiveCaptureContext(self, duration)<EOL>
See base class documentation
f7519:c0:m7
def stop_capture(self):
if self._process is None:<EOL><INDENT>raise sniffer.InvalidOperationError(<EOL>"<STR_LIT>")<EOL><DEDENT>utils.stop_standing_subprocess(self._process, kill_signal=signal.SIGINT)<EOL>self._post_process()<EOL>
See base class documentation
f7519:c0:m8
def wait_for_capture(self, timeout=None):
if self._process is None:<EOL><INDENT>raise sniffer.InvalidOperationError(<EOL>"<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>utils.wait_for_standing_subprocess(self._process, timeout)<EOL>self._post_process()<EOL><DEDENT>except subprocess.TimeoutExpired:<EOL><INDENT>self.stop_capture()<EOL><DEDENT>
See base class documentation
f7519:c0:m9
@property<EOL><INDENT>def is_open(self):<DEDENT>
return bool(self._telnet_client.is_open)<EOL>
This function returns the state of the telnet connection to the underlying AttenuatorDevice. Returns: True if there is a successfully open connection to the AttenuatorDevice.
f7520:c0:m1
def open(self, host, port=<NUM_LIT>):
self._telnet_client.open(host, port)<EOL>config_str = self._telnet_client.cmd("<STR_LIT>")<EOL>if config_str.startswith("<STR_LIT>"):<EOL><INDENT>config_str = config_str[len("<STR_LIT>"):]<EOL><DEDENT>self.properties = dict(<EOL>zip(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'], config_str.split("<STR_LIT:->", <NUM_LIT:2>)))<EOL>self.max_atten = float(self.properties['<STR_LIT>'])<EOL>
Opens a telnet connection to the desired AttenuatorDevice and queries basic information. Args: host: A valid hostname (IP address or DNS-resolvable name) to an MC-DAT attenuator instrument. port: An optional port number (defaults to telnet default 23)
f7520:c0:m2
def close(self):
if self.is_open:<EOL><INDENT>self._telnet_client.close()<EOL><DEDENT>
Closes a telnet connection to the desired attenuator device. This should be called as part of any teardown procedure prior to the attenuator instrument leaving scope.
f7520:c0:m3
def set_atten(self, idx, value):
if not self.is_open:<EOL><INDENT>raise attenuator.Error(<EOL>"<STR_LIT>" %<EOL>self._telnet_client.host)<EOL><DEDENT>if idx + <NUM_LIT:1> > self.path_count:<EOL><INDENT>raise IndexError("<STR_LIT>", self.path_count,<EOL>idx)<EOL><DEDENT>if value > self.max_atten:<EOL><INDENT>raise ValueError("<STR_LIT>", self.max_atten,<EOL>value)<EOL><DEDENT>self._telnet_client.cmd("<STR_LIT>" % (idx + <NUM_LIT:1>, value))<EOL>
Sets the attenuation value for a particular signal path. Args: idx: Zero-based index int which is the identifier for a particular signal path in an instrument. For instruments that only has one channel, this is ignored by the device. value: A float that is the attenuation value to set. Raises: Error: The underlying telnet connection to the instrument is not open. IndexError: The index of the attenuator is greater than the maximum index of the underlying instrument. ValueError: The requested set value is greater than the maximum attenuation value.
f7520:c0:m4
def get_atten(self, idx=<NUM_LIT:0>):
if not self.is_open:<EOL><INDENT>raise attenuator.Error(<EOL>"<STR_LIT>" %<EOL>self._telnet_client.host)<EOL><DEDENT>if idx + <NUM_LIT:1> > self.path_count or idx < <NUM_LIT:0>:<EOL><INDENT>raise IndexError("<STR_LIT>", self.path_count,<EOL>idx)<EOL><DEDENT>atten_val_str = self._telnet_client.cmd("<STR_LIT>" % (idx + <NUM_LIT:1>))<EOL>atten_val = float(atten_val_str)<EOL>return atten_val<EOL>
This function returns the current attenuation from an attenuator at a given index in the instrument. Args: idx: This zero-based index is the identifier for a particular attenuator in an instrument. Raises: Error: The underlying telnet connection to the instrument is not open. Returns: A float that is the current attenuation value.
f7520:c0:m5
def uid(uid):
if uid is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>def decorate(test_func):<EOL><INDENT>@functools.wraps(test_func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>return test_func(*args, **kwargs)<EOL><DEDENT>setattr(wrapper, '<STR_LIT>', uid)<EOL>return wrapper<EOL><DEDENT>return decorate<EOL>
Decorator specifying the unique identifier (UID) of a test case. The UID will be recorded in the test's record when executed by Mobly. If you use any other decorator for the test method, you may want to use this as the outer-most one. Note a common UID system is the Universal Unitque Identifier (UUID), but we are not limiting people to use UUID, hence the more generic name `UID`. Args: uid: string, the uid for the decorated test function.
f7523:m0
def __copy__(self):
return self<EOL>
Make a "copy" of the object. The writer is merely a wrapper object for a path with a global lock for write operation. So we simply return the object itself for copy operations.
f7523:c3:m1
def dump(self, content, entry_type):
new_content = copy.deepcopy(content)<EOL>new_content['<STR_LIT>'] = entry_type.value<EOL>with self._lock:<EOL><INDENT>with io.open(self._path, '<STR_LIT:a>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>yaml.safe_dump(<EOL>new_content,<EOL>f,<EOL>explicit_start=True,<EOL>allow_unicode=True,<EOL>indent=<NUM_LIT:4>)<EOL><DEDENT><DEDENT>
Dumps a dictionary as a yaml document to the summary file. Each call to this method dumps a separate yaml document to the same summary file associated with a test run. The content of the dumped dictionary has an extra field `TYPE` that specifies the type of each yaml document, which is the flag for parsers to identify each document. Args: content: dictionary, the content to serialize and write. entry_type: a member of enum TestSummaryEntryType. Raises: recoreds.Error: An invalid entry type is passed in.
f7523:c3:m3
def _set_details(self, content):
try:<EOL><INDENT>self.details = str(content)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>self.details = unicode(content)<EOL><DEDENT>else:<EOL><INDENT>logging.error(<EOL>'<STR_LIT>',<EOL>content)<EOL>self.details = content.encode('<STR_LIT:utf-8>')<EOL><DEDENT><DEDENT>
Sets the `details` field. Args: content: the content to extract details from.
f7523:c6:m1
def __deepcopy__(self, memo):
try:<EOL><INDENT>exception = copy.deepcopy(self.exception)<EOL><DEDENT>except TypeError:<EOL><INDENT>exception = self.exception<EOL><DEDENT>result = ExceptionRecord(exception, self.position)<EOL>result.stacktrace = self.stacktrace<EOL>result.details = self.details<EOL>result.extras = copy.deepcopy(self.extras)<EOL>result.position = self.position<EOL>return result<EOL>
Overrides deepcopy for the class. If the exception object has a constructor that takes extra args, deep copy won't work. So we need to have a custom logic for deepcopy.
f7523:c6:m3
@property<EOL><INDENT>def details(self):<DEDENT>
if self.termination_signal:<EOL><INDENT>return self.termination_signal.details<EOL><DEDENT>
String description of the cause of the test's termination. Note a passed test can have this as well due to the explicit pass signal. If the test passed implicitly, this field would be None.
f7523:c7:m1
@property<EOL><INDENT>def stacktrace(self):<DEDENT>
if self.termination_signal:<EOL><INDENT>return self.termination_signal.stacktrace<EOL><DEDENT>
The stacktrace string for the exception that terminated the test.
f7523:c7:m2
@property<EOL><INDENT>def extras(self):<DEDENT>
if self.termination_signal:<EOL><INDENT>return self.termination_signal.extras<EOL><DEDENT>
User defined extra information of the test result. Must be serializable.
f7523:c7:m3
def update_record(self):
if self.extra_errors:<EOL><INDENT>if self.result != TestResultEnums.TEST_RESULT_FAIL:<EOL><INDENT>self.result = TestResultEnums.TEST_RESULT_ERROR<EOL><DEDENT><DEDENT>if not self.termination_signal and self.extra_errors:<EOL><INDENT>_, self.termination_signal = self.extra_errors.popitem(last=False)<EOL><DEDENT>
Updates the content of a record. Several display fields like "details" and "stacktrace" need to be updated based on the content of the record object. As the content of the record change, call this method to update all the appropirate fields.
f7523:c7:m6
def add_error(self, position, e):
if self.result != TestResultEnums.TEST_RESULT_FAIL:<EOL><INDENT>self.result = TestResultEnums.TEST_RESULT_ERROR<EOL><DEDENT>if position in self.extra_errors:<EOL><INDENT>raise Error('<STR_LIT>'<EOL>'<STR_LIT>' % position)<EOL><DEDENT>if isinstance(e, ExceptionRecord):<EOL><INDENT>self.extra_errors[position] = e<EOL><DEDENT>else:<EOL><INDENT>self.extra_errors[position] = ExceptionRecord(e, position=position)<EOL><DEDENT>
Add extra error happened during a test. If the test has passed or skipped, this will mark the test result as ERROR. If an error is added the test record, the record's result is equivalent to the case where an uncaught exception happened. If the test record has not recorded any error, the newly added error would be the main error of the test record. Otherwise the newly added error is added to the record's extra errors. Args: position: string, where this error occurred, e.g. 'teardown_test'. e: An exception or a `signals.ExceptionRecord` object.
f7523:c7:m11
def __repr__(self):
t = utils.epoch_to_human_time(self.begin_time)<EOL>return '<STR_LIT>' % (t, self.test_name, self.result)<EOL>
This returns a short string representation of the test record.
f7523:c7:m13
def to_dict(self):
d = {}<EOL>d[TestResultEnums.RECORD_NAME] = self.test_name<EOL>d[TestResultEnums.RECORD_CLASS] = self.test_class<EOL>d[TestResultEnums.RECORD_BEGIN_TIME] = self.begin_time<EOL>d[TestResultEnums.RECORD_END_TIME] = self.end_time<EOL>d[TestResultEnums.RECORD_RESULT] = self.result<EOL>d[TestResultEnums.RECORD_UID] = self.uid<EOL>d[TestResultEnums.RECORD_EXTRAS] = self.extras<EOL>d[TestResultEnums.RECORD_DETAILS] = self.details<EOL>d[TestResultEnums.RECORD_EXTRA_ERRORS] = {<EOL>key: value.to_dict()<EOL>for (key, value) in self.extra_errors.items()<EOL>}<EOL>d[TestResultEnums.RECORD_STACKTRACE] = self.stacktrace<EOL>return d<EOL>
Gets a dictionary representating the content of this class. Returns: A dictionary representating the content of this class.
f7523:c7:m14
def __add__(self, r):
if not isinstance(r, TestResult):<EOL><INDENT>raise TypeError('<STR_LIT>' %<EOL>(r, type(r)))<EOL><DEDENT>sum_result = TestResult()<EOL>for name in sum_result.__dict__:<EOL><INDENT>r_value = getattr(r, name)<EOL>l_value = getattr(self, name)<EOL>if isinstance(r_value, list):<EOL><INDENT>setattr(sum_result, name, l_value + r_value)<EOL><DEDENT><DEDENT>return sum_result<EOL>
Overrides '+' operator for TestResult class. The add operator merges two TestResult objects by concatenating all of their lists together. Args: r: another instance of TestResult to be added Returns: A TestResult instance that's the sum of two TestResult instances.
f7523:c8:m1
def add_record(self, record):
record.update_record()<EOL>if record.result == TestResultEnums.TEST_RESULT_SKIP:<EOL><INDENT>self.skipped.append(record)<EOL>return<EOL><DEDENT>self.executed.append(record)<EOL>if record.result == TestResultEnums.TEST_RESULT_FAIL:<EOL><INDENT>self.failed.append(record)<EOL><DEDENT>elif record.result == TestResultEnums.TEST_RESULT_PASS:<EOL><INDENT>self.passed.append(record)<EOL><DEDENT>else:<EOL><INDENT>self.error.append(record)<EOL><DEDENT>
Adds a test record to test result. A record is considered executed once it's added to the test result. Adding the record finalizes the content of a record, so no change should be made to the record afterwards. Args: record: A test record object to add.
f7523:c8:m2
def add_controller_info_record(self, controller_info_record):
self.controller_info.append(controller_info_record)<EOL>
Adds a controller info record to results. This can be called multiple times for each test class. Args: controller_info_record: ControllerInfoRecord object to be added to the result.
f7523:c8:m3
@property<EOL><INDENT>def is_all_pass(self):<DEDENT>
num_of_failures = len(self.failed) + len(self.error)<EOL>if num_of_failures == <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
True if no tests failed or threw errors, False otherwise.
f7523:c8:m6
def summary_str(self):
l = ['<STR_LIT>' % (k, v) for k, v in self.summary_dict().items()]<EOL>msg = '<STR_LIT:U+002CU+0020>'.join(sorted(l))<EOL>return msg<EOL>
Gets a string that summarizes the stats of this test result. The summary provides the counts of how many tests fall into each category, like 'Passed', 'Failed' etc. Format of the string is: Requested <int>, Executed <int>, ... Returns: A summary string of this test result.
f7523:c8:m8
def summary_dict(self):
d = {}<EOL>d['<STR_LIT>'] = len(self.requested)<EOL>d['<STR_LIT>'] = len(self.executed)<EOL>d['<STR_LIT>'] = len(self.passed)<EOL>d['<STR_LIT>'] = len(self.failed)<EOL>d['<STR_LIT>'] = len(self.skipped)<EOL>d['<STR_LIT>'] = len(self.error)<EOL>return d<EOL>
Gets a dictionary that summarizes the stats of this test result. The summary provides the counts of how many tests fall into each category, like 'Passed', 'Failed' etc. Returns: A dictionary with the stats of this test result.
f7523:c8:m9
def abs_path(path):
return os.path.abspath(os.path.expanduser(path))<EOL>
Resolve the '.' and '~' in a path to get the absolute path. Args: path: The path to expand. Returns: The absolute path of the input path.
f7526:m0
def create_dir(path):
full_path = abs_path(path)<EOL>if not os.path.exists(full_path):<EOL><INDENT>try:<EOL><INDENT>os.makedirs(full_path)<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno != os.errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>
Creates a directory if it does not exist already. Args: path: The path of the directory to create.
f7526:m1
def create_alias(target_path, alias_path):
if platform.system() == '<STR_LIT>' and not alias_path.endswith('<STR_LIT>'):<EOL><INDENT>alias_path += '<STR_LIT>'<EOL><DEDENT>if os.path.lexists(alias_path):<EOL><INDENT>os.remove(alias_path)<EOL><DEDENT>if platform.system() == '<STR_LIT>':<EOL><INDENT>from win32com import client<EOL>shell = client.Dispatch('<STR_LIT>')<EOL>shortcut = shell.CreateShortCut(alias_path)<EOL>shortcut.Targetpath = target_path<EOL>shortcut.save()<EOL><DEDENT>else:<EOL><INDENT>os.symlink(target_path, alias_path)<EOL><DEDENT>
Creates an alias at 'alias_path' pointing to the file 'target_path'. On Unix, this is implemented via symlink. On Windows, this is done by creating a Windows shortcut file. Args: target_path: Destination path that the alias should point to. alias_path: Path at which to create the new alias.
f7526:m2
def get_current_epoch_time():
return int(round(time.time() * <NUM_LIT:1000>))<EOL>
Current epoch time in milliseconds. Returns: An integer representing the current epoch time in milliseconds.
f7526:m3
def get_current_human_time():
return time.strftime("<STR_LIT>")<EOL>
Returns the current time in human readable format. Returns: The current time stamp in Month-Day-Year Hour:Min:Sec format.
f7526:m4
def epoch_to_human_time(epoch_time):
if isinstance(epoch_time, int):<EOL><INDENT>try:<EOL><INDENT>d = datetime.datetime.fromtimestamp(epoch_time / <NUM_LIT:1000>)<EOL>return d.strftime("<STR_LIT>")<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>
Converts an epoch timestamp to human readable time. This essentially converts an output of get_current_epoch_time to an output of get_current_human_time Args: epoch_time: An integer representing an epoch timestamp in milliseconds. Returns: A time string representing the input time. None if input param is invalid.
f7526:m5
def get_timezone_olson_id():
tzoffset = int(time.timezone / <NUM_LIT>)<EOL>gmt = None<EOL>if tzoffset <= <NUM_LIT:0>:<EOL><INDENT>gmt = "<STR_LIT>".format(-tzoffset)<EOL><DEDENT>else:<EOL><INDENT>gmt = "<STR_LIT>".format(tzoffset)<EOL><DEDENT>return GMT_to_olson[gmt]<EOL>
Return the Olson ID of the local (non-DST) timezone. Returns: A string representing one of the Olson IDs of the local (non-DST) timezone.
f7526:m6
def find_files(paths, file_predicate):
file_list = []<EOL>for path in paths:<EOL><INDENT>p = abs_path(path)<EOL>for dirPath, _, fileList in os.walk(p):<EOL><INDENT>for fname in fileList:<EOL><INDENT>name, ext = os.path.splitext(fname)<EOL>if file_predicate(name, ext):<EOL><INDENT>file_list.append((dirPath, name, ext))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return file_list<EOL>
Locate files whose names and extensions match the given predicate in the specified directories. Args: paths: A list of directory paths where to find the files. file_predicate: A function that returns True if the file name and extension are desired. Returns: A list of files that match the predicate.
f7526:m7
def load_file_to_base64_str(f_path):
path = abs_path(f_path)<EOL>with io.open(path, '<STR_LIT:rb>') as f:<EOL><INDENT>f_bytes = f.read()<EOL>base64_str = base64.b64encode(f_bytes).decode("<STR_LIT:utf-8>")<EOL>return base64_str<EOL><DEDENT>
Loads the content of a file into a base64 string. Args: f_path: full path to the file including the file name. Returns: A base64 string representing the content of the file in utf-8 encoding.
f7526:m8
def find_field(item_list, cond, comparator, target_field):
for item in item_list:<EOL><INDENT>if comparator(item, cond) and target_field in item:<EOL><INDENT>return item[target_field]<EOL><DEDENT><DEDENT>return None<EOL>
Finds the value of a field in a dict object that satisfies certain conditions. Args: item_list: A list of dict objects. cond: A param that defines the condition. comparator: A function that checks if an dict satisfies the condition. target_field: Name of the field whose value to be returned if an item satisfies the condition. Returns: Target value or None if no item satisfies the condition.
f7526:m9
def rand_ascii_str(length):
letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]<EOL>return '<STR_LIT>'.join(letters)<EOL>
Generates a random string of specified length, composed of ascii letters and digits. Args: length: The number of characters in the string. Returns: The random string generated.
f7526:m10
def concurrent_exec(func, param_list):
with concurrent.futures.ThreadPoolExecutor(max_workers=<NUM_LIT:30>) as executor:<EOL><INDENT>future_to_params = {executor.submit(func, *p): p for p in param_list}<EOL>return_vals = []<EOL>for future in concurrent.futures.as_completed(future_to_params):<EOL><INDENT>params = future_to_params[future]<EOL>try:<EOL><INDENT>return_vals.append(future.result())<EOL><DEDENT>except Exception as exc:<EOL><INDENT>logging.exception("<STR_LIT>".format(<EOL>params, traceback.format_exc()))<EOL>return_vals.append(exc)<EOL><DEDENT><DEDENT>return return_vals<EOL><DEDENT>
Executes a function with different parameters pseudo-concurrently. This is basically a map function. Each element (should be an iterable) in the param_list is unpacked and passed into the function. Due to Python's GIL, there's no true concurrency. This is suited for IO-bound tasks. Args: func: The function that parforms a task. param_list: A list of iterables, each being a set of params to be passed into the function. Returns: A list of return values from each function execution. If an execution caused an exception, the exception object will be the corresponding result.
f7526:m11
def run_command(cmd,<EOL>stdout=None,<EOL>stderr=None,<EOL>shell=False,<EOL>timeout=None,<EOL>cwd=None,<EOL>env=None):
<EOL>import psutil<EOL>if stdout is None:<EOL><INDENT>stdout = subprocess.PIPE<EOL><DEDENT>if stderr is None:<EOL><INDENT>stderr = subprocess.PIPE<EOL><DEDENT>process = psutil.Popen(<EOL>cmd, stdout=stdout, stderr=stderr, shell=shell, cwd=cwd, env=env)<EOL>timer = None<EOL>timer_triggered = threading.Event()<EOL>if timeout and timeout > <NUM_LIT:0>:<EOL><INDENT>def timeout_expired():<EOL><INDENT>timer_triggered.set()<EOL>process.terminate()<EOL><DEDENT>timer = threading.Timer(timeout, timeout_expired)<EOL>timer.start()<EOL><DEDENT>(out, err) = process.communicate()<EOL>if timer is not None:<EOL><INDENT>timer.cancel()<EOL><DEDENT>if timer_triggered.is_set():<EOL><INDENT>raise psutil.TimeoutExpired(timeout, pid=process.pid)<EOL><DEDENT>return (process.returncode, out, err)<EOL>
Runs a command in a subprocess. This function is very similar to subprocess.check_output. The main difference is that it returns the return code and std error output as well as supporting a timeout parameter. Args: cmd: string or list of strings, the command to run. See subprocess.Popen() documentation. stdout: file handle, the file handle to write std out to. If None is given, then subprocess.PIPE is used. See subprocess.Popen() documentation. stdee: file handle, the file handle to write std err to. If None is given, then subprocess.PIPE is used. See subprocess.Popen() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs. timeout: float, the number of seconds to wait before timing out. If not specified, no timeout takes effect. cwd: string, the path to change the child's current directory to before it is executed. Note that this directory is not considered when searching the executable, so you can't specify the program's path relative to cwd. env: dict, a mapping that defines the environment variables for the new process. Default behavior is inheriting the current process' environment. Returns: A 3-tuple of the consisting of the return code, the std output, and the std error. Raises: psutil.TimeoutExpired: The command timed out.
f7526:m12
def start_standing_subprocess(cmd, shell=False, env=None):
logging.debug('<STR_LIT>', cmd)<EOL>proc = subprocess.Popen(<EOL>cmd,<EOL>stdin=subprocess.PIPE,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>shell=shell,<EOL>env=env)<EOL>proc.stdin.close()<EOL>proc.stdin = None<EOL>logging.debug('<STR_LIT>', proc.pid)<EOL>return proc<EOL>
Starts a long-running subprocess. This is not a blocking call and the subprocess started by it should be explicitly terminated with stop_standing_subprocess. For short-running commands, you should use subprocess.check_call, which blocks. Args: cmd: string, the command to start the subprocess with. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Proc() docs. env: dict, a custom environment to run the standing subprocess. If not specified, inherits the current environment. See subprocess.Popen() docs. Returns: The subprocess that was started.
f7526:m13
def stop_standing_subprocess(proc):
<EOL>import psutil<EOL>pid = proc.pid<EOL>logging.debug('<STR_LIT>', pid)<EOL>process = psutil.Process(pid)<EOL>failed = []<EOL>try:<EOL><INDENT>children = process.children(recursive=True)<EOL><DEDENT>except AttributeError:<EOL><INDENT>children = process.get_children(recursive=True)<EOL><DEDENT>for child in children:<EOL><INDENT>try:<EOL><INDENT>child.kill()<EOL>child.wait(timeout=<NUM_LIT:10>)<EOL><DEDENT>except psutil.NoSuchProcess:<EOL><INDENT>pass<EOL><DEDENT>except:<EOL><INDENT>failed.append(child.pid)<EOL>logging.exception('<STR_LIT>',<EOL>child.pid)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>process.kill()<EOL>process.wait(timeout=<NUM_LIT:10>)<EOL><DEDENT>except psutil.NoSuchProcess:<EOL><INDENT>pass<EOL><DEDENT>except:<EOL><INDENT>failed.append(pid)<EOL>logging.exception('<STR_LIT>', pid)<EOL><DEDENT>if failed:<EOL><INDENT>raise Error('<STR_LIT>' % failed)<EOL><DEDENT>if proc.stdout:<EOL><INDENT>proc.stdout.close()<EOL><DEDENT>if proc.stderr:<EOL><INDENT>proc.stderr.close()<EOL><DEDENT>proc.wait()<EOL>logging.debug('<STR_LIT>', pid)<EOL>
Stops a subprocess started by start_standing_subprocess. Before killing the process, we check if the process is running, if it has terminated, Error is raised. Catches and ignores the PermissionError which only happens on Macs. Args: proc: Subprocess to terminate. Raises: Error: if the subprocess could not be stopped.
f7526:m14
def wait_for_standing_subprocess(proc, timeout=None):
proc.wait(timeout)<EOL>
Waits for a subprocess started by start_standing_subprocess to finish or times out. Propagates the exception raised by the subprocess.wait(.) function. The subprocess.TimeoutExpired exception is raised if the process timed-out rather then terminating. If no exception is raised: the subprocess terminated on its own. No need to call stop_standing_subprocess() to kill it. If an exception is raised: the subprocess is still alive - it did not terminate. Either call stop_standing_subprocess() to kill it, or call wait_for_standing_subprocess() to keep waiting for it to terminate on its own. If the corresponding subprocess command generates a large amount of output and this method is called with a timeout value, then the command can hang indefinitely. See http://go/pylib/subprocess.html#subprocess.Popen.wait This function does not support Python 2. Args: p: Subprocess to wait for. timeout: An integer number of seconds to wait before timing out.
f7526:m15
def get_available_host_port():
<EOL>from mobly.controllers.android_device_lib import adb<EOL>for _ in range(MAX_PORT_ALLOCATION_RETRY):<EOL><INDENT>port = portpicker.PickUnusedPort()<EOL>if port not in adb.list_occupied_adb_ports():<EOL><INDENT>return port<EOL><DEDENT><DEDENT>raise Error('<STR_LIT>'.format(<EOL>MAX_PORT_ALLOCATION_RETRY))<EOL>
Gets a host port number available for adb forward. Returns: An integer representing a port number on the host available for adb forward. Raises: Error: when no port is found after MAX_PORT_ALLOCATION_RETRY times.
f7526:m16
def grep(regex, output):
lines = output.decode('<STR_LIT:utf-8>').strip().splitlines()<EOL>results = []<EOL>for line in lines:<EOL><INDENT>if re.search(regex, line):<EOL><INDENT>results.append(line.strip())<EOL><DEDENT><DEDENT>return results<EOL>
Similar to linux's `grep`, this returns the line in an output stream that matches a given regex pattern. It does not rely on the `grep` binary and is not sensitive to line endings, so it can be used cross-platform. Args: regex: string, a regex that matches the expected pattern. output: byte string, the raw output of the adb cmd. Returns: A list of strings, all of which are output lines that matches the regex pattern.
f7526:m17
def cli_cmd_to_string(args):
if isinstance(args, basestring):<EOL><INDENT>return args<EOL><DEDENT>return '<STR_LIT:U+0020>'.join([pipes.quote(arg) for arg in args])<EOL>
Converts a cmd arg list to string. Args: args: list of strings, the arguments of a command. Returns: String representation of the command.
f7526:m18
def _load_config_file(path):
with io.open(utils.abs_path(path), '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>conf = yaml.load(f)<EOL>return conf<EOL><DEDENT>
Loads a test config file. The test config file has to be in YAML format. Args: path: A string that is the full path to the config file, including the file name. Returns: A dict that represents info in the config file.
f7527:m4
def copy(self):
return copy.deepcopy(self)<EOL>
Returns a deep copy of the current config.
f7527:c1:m1
def verify_controller_module(module):
required_attributes = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>for attr in required_attributes:<EOL><INDENT>if not hasattr(module, attr):<EOL><INDENT>raise signals.ControllerError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (module.__name__, attr))<EOL><DEDENT>if not getattr(module, attr):<EOL><INDENT>raise signals.ControllerError(<EOL>'<STR_LIT>' %<EOL>(attr, module.__name__))<EOL><DEDENT><DEDENT>
Verifies a module object follows the required interface for controllers. The interface is explained in the docstring of `base_test.BaseTestClass.register_controller`. Args: module: An object that is a controller module. This is usually imported with import statements or loaded by importlib. Raises: ControllerError: if the module does not match the Mobly controller interface, or one of the required members is null.
f7528:m0
def register_controller(self, module, required=True, min_number=<NUM_LIT:1>):
verify_controller_module(module)<EOL>module_ref_name = module.__name__.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL>if module_ref_name in self._controller_objects:<EOL><INDENT>raise signals.ControllerError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % module_ref_name)<EOL><DEDENT>module_config_name = module.MOBLY_CONTROLLER_CONFIG_NAME<EOL>if module_config_name not in self.controller_configs:<EOL><INDENT>if required:<EOL><INDENT>raise signals.ControllerError(<EOL>'<STR_LIT>' %<EOL>module_config_name)<EOL><DEDENT>logging.warning(<EOL>'<STR_LIT>',<EOL>module_config_name)<EOL>return None<EOL><DEDENT>try:<EOL><INDENT>original_config = self.controller_configs[module_config_name]<EOL>controller_config = copy.deepcopy(original_config)<EOL>objects = module.create(controller_config)<EOL><DEDENT>except:<EOL><INDENT>logging.exception(<EOL>'<STR_LIT>',<EOL>module_config_name)<EOL>raise<EOL><DEDENT>if not isinstance(objects, list):<EOL><INDENT>raise signals.ControllerError(<EOL>'<STR_LIT>'<EOL>% module_ref_name)<EOL><DEDENT>actual_number = len(objects)<EOL>if actual_number < min_number:<EOL><INDENT>module.destroy(objects)<EOL>raise signals.ControllerError(<EOL>'<STR_LIT>' %<EOL>(min_number, actual_number))<EOL><DEDENT>self._controller_objects[module_ref_name] = copy.copy(objects)<EOL>logging.debug('<STR_LIT>', len(objects),<EOL>module_config_name)<EOL>self._controller_modules[module_ref_name] = module<EOL>return objects<EOL>
Loads a controller module and returns its loaded devices. This is to be used in a mobly test class. Args: module: A module that follows the controller module interface. required: A bool. If True, failing to register the specified controller module raises exceptions. If False, the objects failed to instantiate will be skipped. min_number: An integer that is the minimum number of controller objects to be created. Default is one, since you should not register a controller module without expecting at least one object. Returns: A list of controller objects instantiated from controller_module, or None if no config existed for this controller and it was not a required controller. Raises: ControllerError: * The controller module has already been registered. * The actual number of objects instantiated is less than the * `min_number`. * `required` is True and no corresponding config can be found. * Any other error occurred in the registration process.
f7528:c0:m1
def unregister_controllers(self):
<EOL>for name, module in self._controller_modules.items():<EOL><INDENT>logging.debug('<STR_LIT>', name)<EOL>with expects.expect_no_raises(<EOL>'<STR_LIT>' % name):<EOL><INDENT>module.destroy(self._controller_objects[name])<EOL><DEDENT><DEDENT>self._controller_objects = collections.OrderedDict()<EOL>self._controller_modules = {}<EOL>
Destroy controller objects and clear internal registry. This will be called after each test class.
f7528:c0:m2
def _create_controller_info_record(self, controller_module_name):
module = self._controller_modules[controller_module_name]<EOL>controller_info = None<EOL>try:<EOL><INDENT>controller_info = module.get_info(<EOL>copy.copy(self._controller_objects[controller_module_name]))<EOL><DEDENT>except AttributeError:<EOL><INDENT>logging.warning('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>controller_module_name)<EOL><DEDENT>try:<EOL><INDENT>yaml.dump(controller_info)<EOL><DEDENT>except TypeError:<EOL><INDENT>logging.warning('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>controller_module_name, self._class_name)<EOL>controller_info = str(controller_info)<EOL><DEDENT>return records.ControllerInfoRecord(<EOL>self._class_name, module.MOBLY_CONTROLLER_CONFIG_NAME,<EOL>controller_info)<EOL>
Creates controller info record for a particular controller type. Info is retrieved from all the controller objects spawned from the specified module, using the controller module's `get_info` function. Args: controller_module_name: string, the name of the controller module to retrieve info from. Returns: A records.ControllerInfoRecord object.
f7528:c0:m3
def get_controller_info_records(self):
info_records = []<EOL>for controller_module_name in self._controller_objects.keys():<EOL><INDENT>with expects.expect_no_raises(<EOL>'<STR_LIT>' %<EOL>controller_module_name):<EOL><INDENT>record = self._create_controller_info_record(<EOL>controller_module_name)<EOL>if record:<EOL><INDENT>info_records.append(record)<EOL><DEDENT><DEDENT><DEDENT>return info_records<EOL>
Get the info records for all the controller objects in the manager. New info records for each controller object are created for every call so the latest info is included. Returns: List of records.ControllerInfoRecord objects. Each opject conatins the info of a type of controller
f7528:c0:m4
@property<EOL><INDENT>def is_empty(self):<DEDENT>
return self._empty<EOL>
Deteremines whether or not anything has been parsed with this instrumentation block. Returns: A boolean indicating whether or not the this instrumentation block has parsed and contains any output.
f7529:c7:m1
def set_error_message(self, error_message):
self._empty = False<EOL>self.error_message = error_message<EOL>
Sets an error message on an instrumentation block. This method is used exclusively to indicate that a test method failed to complete, which is usually cause by a crash of some sort such that the test method is marked as error instead of ignored. Args: error_message: string, an error message to be added to the TestResultRecord to explain that something wrong happened.
f7529:c7:m2
def _remove_structure_prefix(self, prefix, line):
return line[len(prefix):].strip()<EOL>
Helper function for removing the structure prefix for parsing. Args: prefix: string, a _InstrumentationStructurePrefixes to remove from the raw output. line: string, the raw line from the instrumentation output. Returns: A string containing a key value pair descripting some property of the current instrumentation test method.
f7529:c7:m3
def set_status_code(self, status_code_line):
self._empty = False<EOL>self.status_code = self._remove_structure_prefix(<EOL>_InstrumentationStructurePrefixes.STATUS_CODE,<EOL>status_code_line,<EOL>)<EOL>if self.status_code == _InstrumentationStatusCodes.START:<EOL><INDENT>self.begin_time = utils.get_current_epoch_time()<EOL><DEDENT>
Sets the status code for the instrumentation test method, used in determining the test result. Args: status_code_line: string, the raw instrumentation output line that contains the status code of the instrumentation block.
f7529:c7:m4
def set_key(self, structure_prefix, key_line):
self._empty = False<EOL>key_value = self._remove_structure_prefix(<EOL>structure_prefix,<EOL>key_line,<EOL>)<EOL>if '<STR_LIT:=>' in key_value:<EOL><INDENT>(key, value) = key_value.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>self.current_key = key<EOL>if key in self.known_keys:<EOL><INDENT>self.known_keys[key].append(value)<EOL><DEDENT>else:<EOL><INDENT>self.unknown_keys[key].append(key_value)<EOL><DEDENT><DEDENT>
Sets the current key for the instrumentation block. For unknown keys, the key is added to the value list in order to better contextualize the value in the output. Args: structure_prefix: string, the structure prefix that was matched and that needs to be removed. key_line: string, the raw instrumentation ouput line that contains the key-value pair.
f7529:c7:m5
def add_value(self, line):
<EOL>if line.strip():<EOL><INDENT>self._empty = False<EOL><DEDENT>if self.current_key in self.known_keys:<EOL><INDENT>self.known_keys[self.current_key].append(line)<EOL><DEDENT>else:<EOL><INDENT>self.unknown_keys[self.current_key].append(line)<EOL><DEDENT>
Adds unstructured or multi-line value output to the current parsed instrumentation block for outputting later. Usually, this will add extra lines to the value list for the current key-value pair. However, sometimes, such as when instrumentation failed to start, output does not follow the structured prefix format. In this case, adding all of the output is still useful so that a user can debug the issue. Args: line: string, the raw instrumentation line to append to the value list.
f7529:c7:m6
def transition_state(self, new_state):
if self.state == _InstrumentationBlockStates.UNKNOWN:<EOL><INDENT>self.state = new_state<EOL>return self<EOL><DEDENT>else:<EOL><INDENT>next_block = _InstrumentationBlock(<EOL>state=new_state,<EOL>prefix=self.prefix,<EOL>previous_instrumentation_block=self,<EOL>)<EOL>if self.status_code in _InstrumentationStatusCodeCategories.TIMING:<EOL><INDENT>next_block.begin_time = self.begin_time<EOL><DEDENT>return next_block<EOL><DEDENT>
Transitions or sets the current instrumentation block to the new parser state. Args: new_state: _InstrumentationBlockStates, the state that the parser should transition to. Returns: A new instrumentation block set to the new state, representing the start of parsing a new instrumentation test method. Alternatively, if the current instrumentation block represents the start of parsing a new instrumentation block (state UKNOWN), then this returns the current instrumentation block set to the now known parsing state.
f7529:c7:m7
def _get_name(self):
if self._known_keys[_InstrumentationKnownStatusKeys.TEST]:<EOL><INDENT>return self._known_keys[_InstrumentationKnownStatusKeys.TEST]<EOL><DEDENT>else:<EOL><INDENT>return self.DEFAULT_INSTRUMENTATION_METHOD_NAME<EOL><DEDENT>
Gets the method name of the test method for the instrumentation method block. Returns: A string containing the name of the instrumentation test method's test or a default name if no name was parsed.
f7529:c8:m1