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>]))<...
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. ...
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.ser...
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. ti...
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><DE...
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...
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><...
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. ...
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_...
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.Test...
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(modul...
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 ...
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 ba...
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 ter...
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...
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...
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.ipe...
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 = i...
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>',...
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>".forma...
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>)))...
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...
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 i...
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 + <...
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 i...
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...
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...
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...
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>')<EO...
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>resu...
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><DE...
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...
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.u...
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_valu...
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 instanc...
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....
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 ...
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...
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. ...
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>ret...
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 fi...
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...
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...
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:...
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 tim...
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....
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 subproc...
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:<E...
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: ...
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 term...
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:...
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.Controlle...
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 i...
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...
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 excepti...
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_mod...
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_...
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 ...
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>...
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 c...
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,...
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 val...
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)<...
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. ...
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 th...
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 _InstrumentationStatusCodeCate...
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 ...
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