signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def _on_pass(self, record):
|
msg = record.details<EOL>if msg:<EOL><INDENT>logging.info(msg)<EOL><DEDENT>self.on_pass(record)<EOL>
|
Proxy function to guarantee the base implementation of on_pass is
called.
Args:
record: records.TestResultRecord, a copy of the test record for
this test, containing all information of the test execution
including exception objects.
|
f7490:c1:m19
|
def on_pass(self, record):
|
A function that is executed upon a test passing.
Implementation is optional.
Args:
record: records.TestResultRecord, a copy of the test record for
this test, containing all information of the test execution
including exception objects.
|
f7490:c1:m20
|
|
def _on_skip(self, record):
|
logging.info('<STR_LIT>', record.details)<EOL>logging.info(RESULT_LINE_TEMPLATE, record.test_name, record.result)<EOL>self.on_skip(record)<EOL>
|
Proxy function to guarantee the base implementation of on_skip is
called.
Args:
record: records.TestResultRecord, a copy of the test record for
this test, containing all information of the test execution
including exception objects.
|
f7490:c1:m21
|
def on_skip(self, record):
|
A function that is executed upon a test being skipped.
Implementation is optional.
Args:
record: records.TestResultRecord, a copy of the test record for
this test, containing all information of the test execution
including exception objects.
|
f7490:c1:m22
|
|
def _exec_procedure_func(self, func, tr_record):
|
func_name = func.__name__<EOL>procedure_name = func_name[<NUM_LIT:1>:] if func_name[<NUM_LIT:0>] == '<STR_LIT:_>' else func_name<EOL>with self._log_test_stage(procedure_name):<EOL><INDENT>try:<EOL><INDENT>func(copy.deepcopy(tr_record))<EOL><DEDENT>except signals.TestAbortSignal:<EOL><INDENT>raise<EOL><DEDENT>except Exception as e:<EOL><INDENT>logging.exception(<EOL>'<STR_LIT>',<EOL>procedure_name, self.current_test_name)<EOL>tr_record.add_error(procedure_name, e)<EOL><DEDENT><DEDENT>
|
Executes a procedure function like on_pass, on_fail etc.
This function will alter the 'Result' of the test's record if
exceptions happened when executing the procedure function, but
prevents procedure functions from altering test records themselves
by only passing in a copy.
This will let signals.TestAbortAll through so abort_all works in all
procedure functions.
Args:
func: The procedure function to be executed.
tr_record: The TestResultRecord object associated with the test
executed.
|
f7490:c1:m23
|
def record_data(self, content):
|
if '<STR_LIT>' not in content:<EOL><INDENT>content['<STR_LIT>'] = utils.get_current_epoch_time()<EOL><DEDENT>self.summary_writer.dump(content,<EOL>records.TestSummaryEntryType.USER_DATA)<EOL>
|
Record an entry in test summary file.
Sometimes additional data need to be recorded in summary file for
debugging or post-test analysis.
Each call adds a new entry to the summary file, with no guarantee of
its position among the summary file entries.
The content should be a dict. If absent, timestamp field is added for
ease of parsing later.
Args:
content: dict, the data to add to summary file.
|
f7490:c1:m24
|
def _assert_function_name_in_stack(self, expected_func_name):
|
current_frame = inspect.currentframe()<EOL>caller_frames = inspect.getouterframes(current_frame, <NUM_LIT:2>)<EOL>for caller_frame in caller_frames[<NUM_LIT:2>:]:<EOL><INDENT>if caller_frame[<NUM_LIT:3>] == expected_func_name:<EOL><INDENT>return<EOL><DEDENT><DEDENT>raise Error('<STR_LIT>' %<EOL>(caller_frames[<NUM_LIT:1>][<NUM_LIT:3>], expected_func_name))<EOL>
|
Asserts that the current stack contains the given function name.
|
f7490:c1:m26
|
def _safe_exec_func(self, func, *args):
|
try:<EOL><INDENT>return func(*args)<EOL><DEDENT>except signals.TestAbortAll:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>logging.exception('<STR_LIT>',<EOL>func.__name__, self.TAG)<EOL><DEDENT>
|
Executes a function with exception safeguard.
This will let signals.TestAbortAll through so abort_all works in all
procedure functions.
Args:
func: Function to be executed.
args: Arguments to be passed to the function.
Returns:
Whatever the function returns.
|
f7490:c1:m28
|
def _clean_up(self):
|
stage_name = STAGE_NAME_CLEAN_UP<EOL>record = records.TestResultRecord(stage_name, self.TAG)<EOL>record.test_begin()<EOL>self.current_test_info = runtime_test_info.RuntimeTestInfo(<EOL>stage_name, self.log_path, record)<EOL>expects.recorder.reset_internal_states(record)<EOL>with self._log_test_stage(stage_name):<EOL><INDENT>self._record_controller_info()<EOL>self._controller_manager.unregister_controllers()<EOL>if expects.recorder.has_error:<EOL><INDENT>record.test_error()<EOL>record.update_record()<EOL>self.results.add_class_error(record)<EOL>self.summary_writer.dump(record.to_dict(),<EOL>records.TestSummaryEntryType.RECORD)<EOL><DEDENT><DEDENT>
|
The final stage of a test class execution.
|
f7490:c1:m33
|
def clean_up(self):
|
.. deprecated:: 1.8.1
Use `teardown_class` instead.
A function that is executed upon completion of all tests selected in
the test class.
This function should clean up objects initialized in the constructor by
user.
Generally this should not be used as nothing should be instantiated
from the constructor of a test class.
|
f7490:c1:m34
|
|
def expect_true(condition, msg, extras=None):
|
try:<EOL><INDENT>asserts.assert_true(condition, msg, extras)<EOL><DEDENT>except signals.TestSignal as e:<EOL><INDENT>logging.exception('<STR_LIT>')<EOL>recorder.add_error(e)<EOL><DEDENT>
|
Expects an expression evaluates to True.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result.
|
f7491:m0
|
def expect_false(condition, msg, extras=None):
|
try:<EOL><INDENT>asserts.assert_false(condition, msg, extras)<EOL><DEDENT>except signals.TestSignal as e:<EOL><INDENT>logging.exception('<STR_LIT>')<EOL>recorder.add_error(e)<EOL><DEDENT>
|
Expects an expression evaluates to False.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in test
result.
|
f7491:m1
|
def expect_equal(first, second, msg=None, extras=None):
|
try:<EOL><INDENT>asserts.assert_equal(first, second, msg, extras)<EOL><DEDENT>except signals.TestSignal as e:<EOL><INDENT>logging.exception('<STR_LIT>', first,<EOL>second)<EOL>recorder.add_error(e)<EOL><DEDENT>
|
Expects the equality of objects, otherwise fail the test.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in test
result.
|
f7491:m2
|
@contextlib.contextmanager<EOL>def expect_no_raises(message=None, extras=None):
|
try:<EOL><INDENT>yield<EOL><DEDENT>except Exception as e:<EOL><INDENT>e_record = records.ExceptionRecord(e)<EOL>if extras:<EOL><INDENT>e_record.extras = extras<EOL><DEDENT>msg = message or '<STR_LIT>'<EOL>details = '<STR_LIT>' % (msg, e_record.details)<EOL>logging.exception(details)<EOL>e_record.details = details<EOL>recorder.add_error(e_record)<EOL><DEDENT>
|
Expects no exception is raised in a context.
If the expectation is not met, the test is marked as fail after its
execution finishes.
A default message is added to the exception `details`.
Args:
message: string, custom message to add to exception's `details`.
extras: An optional field for extra information to be included in test
result.
|
f7491:m3
|
def reset_internal_states(self, record=None):
|
self._record = None<EOL>self._count = <NUM_LIT:0><EOL>self._record = record<EOL>
|
Resets the internal state of the recorder.
Args:
record: records.TestResultRecord, the test record for a test.
|
f7491:c0:m1
|
@property<EOL><INDENT>def has_error(self):<DEDENT>
|
return self._count > <NUM_LIT:0><EOL>
|
If any error has been recorded since the last reset.
|
f7491:c0:m2
|
@property<EOL><INDENT>def error_count(self):<DEDENT>
|
return self._count<EOL>
|
The number of errors that have been recorded since last reset.
|
f7491:c0:m3
|
def add_error(self, error):
|
self._count += <NUM_LIT:1><EOL>self._record.add_error('<STR_LIT>' % (time.time(), self._count),<EOL>error)<EOL>
|
Record an error from expect APIs.
This method generates a position stamp for the expect. The stamp is
composed of a timestamp and the number of errors recorded so far.
Args:
error: Exception or signals.ExceptionRecord, the error to add.
|
f7491:c0:m4
|
def main(argv=None):
|
args = parse_mobly_cli_args(argv)<EOL>test_class = _find_test_class()<EOL>if args.list_tests:<EOL><INDENT>_print_test_names(test_class)<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>test_configs = config_parser.load_test_config_file(args.config[<NUM_LIT:0>],<EOL>args.test_bed)<EOL>tests = None<EOL>if args.tests:<EOL><INDENT>tests = args.tests<EOL><DEDENT>ok = True<EOL>for config in test_configs:<EOL><INDENT>runner = TestRunner(<EOL>log_dir=config.log_path, test_bed_name=config.test_bed_name)<EOL>runner.add_test_class(config, test_class, tests)<EOL>try:<EOL><INDENT>runner.run()<EOL>ok = runner.results.is_all_pass and ok<EOL><DEDENT>except signals.TestAbortAll:<EOL><INDENT>pass<EOL><DEDENT>except:<EOL><INDENT>logging.exception('<STR_LIT>',<EOL>config.test_bed_name)<EOL>ok = False<EOL><DEDENT><DEDENT>if not ok:<EOL><INDENT>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>
|
Execute the test class in a test module.
This is the default entry point for running a test script file directly.
In this case, only one test class in a test script is allowed.
To make your test script executable, add the following to your file:
.. code-block:: python
from mobly import test_runner
...
if __name__ == '__main__':
test_runner.main()
If you want to implement your own cli entry point, you could use function
execute_one_test_class(test_class, test_config, test_identifier)
Args:
argv: A list that is then parsed as cli args. If None, defaults to cli
input.
|
f7493:m0
|
def parse_mobly_cli_args(argv):
|
parser = argparse.ArgumentParser(description='<STR_LIT>')<EOL>group = parser.add_mutually_exclusive_group(required=True)<EOL>group.add_argument(<EOL>'<STR_LIT:-c>',<EOL>'<STR_LIT>',<EOL>nargs=<NUM_LIT:1>,<EOL>type=str,<EOL>metavar='<STR_LIT>',<EOL>help='<STR_LIT>')<EOL>group.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>nargs='<STR_LIT:+>',<EOL>type=str,<EOL>metavar='<STR_LIT>',<EOL>help='<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>nargs='<STR_LIT:+>',<EOL>type=str,<EOL>metavar='<STR_LIT>',<EOL>help='<STR_LIT>')<EOL>if not argv:<EOL><INDENT>argv = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>return parser.parse_known_args(argv)[<NUM_LIT:0>]<EOL>
|
Parses cli args that are consumed by Mobly.
This is the arg parsing logic for the default test_runner.main entry point.
Multiple arg parsers can be applied to the same set of cli input. So you
can use this logic in addition to any other args you want to parse. This
function ignores the args that don't apply to default `test_runner.main`.
Args:
argv: A list that is then parsed as cli args. If None, defaults to cli
input.
Returns:
Namespace containing the parsed args.
|
f7493:m1
|
def setup_logger(self):
|
if self._log_path is not None:<EOL><INDENT>return<EOL><DEDENT>self._start_time = logger.get_log_file_timestamp()<EOL>self._log_path = os.path.join(self._log_dir, self._test_bed_name,<EOL>self._start_time)<EOL>logger.setup_test_logger(self._log_path, self._test_bed_name)<EOL>
|
Sets up logging for the next test run.
This is called automatically in 'run', so normally, this method doesn't
need to be called. Only use this method if you want to use Mobly's
logger before the test run starts.
.. code-block:: python
tr = TestRunner(...)
tr.setup_logger()
logging.info(...)
tr.run()
|
f7493:c1:m1
|
def _teardown_logger(self):
|
if self._log_path is None:<EOL><INDENT>raise Error('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>logger.kill_test_logger(logging.getLogger())<EOL>self._log_path = None<EOL>
|
Tears down logging at the end of the test run.
This is called automatically in 'run', so normally, this method doesn't
need to be called. Only use this to change the logger teardown
behaviour.
Raises:
Error: if this is called before the logger is setup.
|
f7493:c1:m2
|
def run(self):
|
if not self._test_run_infos:<EOL><INDENT>raise Error('<STR_LIT>')<EOL><DEDENT>self.setup_logger()<EOL>summary_writer = records.TestSummaryWriter(<EOL>os.path.join(self._log_path, records.OUTPUT_FILE_SUMMARY))<EOL>try:<EOL><INDENT>for test_run_info in self._test_run_infos:<EOL><INDENT>test_config = test_run_info.config.copy()<EOL>test_config.log_path = self._log_path<EOL>test_config.summary_writer = summary_writer<EOL>test_config.test_class_name_suffix = test_run_info.test_class_name_suffix<EOL>try:<EOL><INDENT>self._run_test_class(<EOL>config=test_config,<EOL>test_class=test_run_info.test_class,<EOL>tests=test_run_info.tests)<EOL><DEDENT>except signals.TestAbortAll as e:<EOL><INDENT>logging.warning(<EOL>'<STR_LIT>', e)<EOL>raise<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>summary_writer.dump(self.results.summary_dict(),<EOL>records.TestSummaryEntryType.SUMMARY)<EOL>msg = '<STR_LIT>' % (<EOL>self._test_bed_name, self._start_time,<EOL>self.results.summary_str())<EOL>logging.info(msg.strip())<EOL>self._teardown_logger()<EOL><DEDENT>
|
Executes tests.
This will instantiate controller and test classes, execute tests, and
print a summary.
Raises:
Error: if no tests have previously been added to this runner using
add_test_class(...).
|
f7493:c1:m5
|
def assert_equal(first, second, msg=None, extras=None):
|
my_msg = None<EOL>try:<EOL><INDENT>_pyunit_proxy.assertEqual(first, second)<EOL><DEDENT>except AssertionError as e:<EOL><INDENT>my_msg = str(e)<EOL>if msg:<EOL><INDENT>my_msg = "<STR_LIT>" % (my_msg, msg)<EOL><DEDENT><DEDENT>if my_msg is not None:<EOL><INDENT>raise signals.TestFailure(my_msg, extras=extras)<EOL><DEDENT>
|
Assert the equality of objects, otherwise fail the test.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in
test result.
|
f7494:m0
|
def assert_raises(expected_exception, extras=None, *args, **kwargs):
|
context = _AssertRaisesContext(expected_exception, extras=extras)<EOL>return context<EOL>
|
Assert that an exception is raised when a function is called.
If no exception is raised, test fail. If an exception is raised but not
of the expected type, the exception is let through.
This should only be used as a context manager:
with assert_raises(Exception):
func()
Args:
expected_exception: An exception class that is expected to be
raised.
extras: An optional field for extra information to be included in
test result.
|
f7494:m1
|
def assert_raises_regex(expected_exception,<EOL>expected_regex,<EOL>extras=None,<EOL>*args,<EOL>**kwargs):
|
context = _AssertRaisesContext(<EOL>expected_exception, expected_regex, extras=extras)<EOL>return context<EOL>
|
Assert that an exception is raised when a function is called.
If no exception is raised, test fail. If an exception is raised but not
of the expected type, the exception is let through. If an exception of the
expected type is raised but the error message does not match the
expected_regex, test fail.
This should only be used as a context manager:
with assert_raises(Exception):
func()
Args:
expected_exception: An exception class that is expected to be
raised.
extras: An optional field for extra information to be included in
test result.
|
f7494:m2
|
def assert_true(expr, msg, extras=None):
|
if not expr:<EOL><INDENT>fail(msg, extras)<EOL><DEDENT>
|
Assert an expression evaluates to true, otherwise fail the test.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in
test result.
|
f7494:m3
|
def assert_false(expr, msg, extras=None):
|
if expr:<EOL><INDENT>fail(msg, extras)<EOL><DEDENT>
|
Assert an expression evaluates to false, otherwise fail the test.
Args:
expr: The expression that is evaluated.
msg: A string explaining the details in case of failure.
extras: An optional field for extra information to be included in
test result.
|
f7494:m4
|
def skip(reason, extras=None):
|
raise signals.TestSkip(reason, extras)<EOL>
|
Skip a test.
Args:
reason: The reason this test is skipped.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestSkip: Mark a test as skipped.
|
f7494:m5
|
def skip_if(expr, reason, extras=None):
|
if expr:<EOL><INDENT>skip(reason, extras)<EOL><DEDENT>
|
Skip a test if expression evaluates to True.
Args:
expr: The expression that is evaluated.
reason: The reason this test is skipped.
extras: An optional field for extra information to be included in
test result.
|
f7494:m6
|
def abort_class(reason, extras=None):
|
raise signals.TestAbortClass(reason, extras)<EOL>
|
Abort all subsequent tests within the same test class in one iteration.
If one test class is requested multiple times in a test run, this can
only abort one of the requested executions, NOT all.
Args:
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestAbortClass: Abort all subsequent tests in a test class.
|
f7494:m7
|
def abort_class_if(expr, reason, extras=None):
|
if expr:<EOL><INDENT>abort_class(reason, extras)<EOL><DEDENT>
|
Abort all subsequent tests within the same test class in one iteration,
if expression evaluates to True.
If one test class is requested multiple times in a test run, this can
only abort one of the requested executions, NOT all.
Args:
expr: The expression that is evaluated.
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestAbortClass: Abort all subsequent tests in a test class.
|
f7494:m8
|
def abort_all(reason, extras=None):
|
raise signals.TestAbortAll(reason, extras)<EOL>
|
Abort all subsequent tests, including the ones not in this test class or
iteration.
Args:
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestAbortAll: Abort all subsequent tests.
|
f7494:m9
|
def abort_all_if(expr, reason, extras=None):
|
if expr:<EOL><INDENT>abort_all(reason, extras)<EOL><DEDENT>
|
Abort all subsequent tests, if the expression evaluates to True.
Args:
expr: The expression that is evaluated.
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestAbortAll: Abort all subsequent tests.
|
f7494:m10
|
def fail(msg, extras=None):
|
raise signals.TestFailure(msg, extras)<EOL>
|
Explicitly fail a test.
Args:
msg: A string explaining the details of the failure.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestFailure: Mark a test as failed.
|
f7494:m11
|
def explicit_pass(msg, extras=None):
|
raise signals.TestPass(msg, extras)<EOL>
|
Explicitly pass a test.
This will pass the test explicitly regardless of any other error happened
in the test body. E.g. even if errors have been recorded with `expects`,
the test will still be marked pass if this is called.
A test without uncaught exception will pass implicitly so this should be
used scarcely.
Args:
msg: A string explaining the details of the passed test.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestPass: Mark a test as passed.
|
f7494:m12
|
def get_instances_with_configs(configs):
|
return get_instances([c['<STR_LIT>'] for c in configs])<EOL>
|
Create Monsoon instances from a list of dict configs.
Each config should have the required key-value pair
'serial': <an integer id>.
Args:
configs: A list of dicts each representing the configuration of one
Monsoon.
Returns:
A list of Monsoon objects.
|
f7495:m1
|
def get_instances(serials):
|
objs = []<EOL>for s in serials:<EOL><INDENT>objs.append(Monsoon(serial=s))<EOL><DEDENT>return objs<EOL>
|
Create Monsoon instances from a list of serials.
Args:
serials: A list of Monsoon (integer) serials.
Returns:
A list of Monsoon objects.
|
f7495:m2
|
def __init__(self, device=None, serialno=None, wait=<NUM_LIT:1>):
|
self._coarse_ref = self._fine_ref = self._coarse_zero = <NUM_LIT:0><EOL>self._fine_zero = self._coarse_scale = self._fine_scale = <NUM_LIT:0><EOL>self._last_seq = <NUM_LIT:0><EOL>self.start_voltage = <NUM_LIT:0><EOL>self.serial = serialno<EOL>if device:<EOL><INDENT>self.ser = serial.Serial(device, timeout=<NUM_LIT:1>)<EOL>return<EOL><DEDENT>while True:<EOL><INDENT>for dev in os.listdir("<STR_LIT>"):<EOL><INDENT>prefix = "<STR_LIT>"<EOL>if sys.platform == "<STR_LIT>":<EOL><INDENT>prefix = "<STR_LIT>"<EOL><DEDENT>if not dev.startswith(prefix):<EOL><INDENT>continue<EOL><DEDENT>tmpname = "<STR_LIT>" % (os.uname()[<NUM_LIT:0>], dev)<EOL>self._tempfile = io.open(tmpname, "<STR_LIT:w>", encoding='<STR_LIT:utf-8>')<EOL>try:<EOL><INDENT>os.chmod(tmpname, <NUM_LIT>)<EOL><DEDENT>except OSError as e:<EOL><INDENT>pass<EOL><DEDENT>try: <EOL><INDENT>fcntl.lockf(self._tempfile, fcntl.LOCK_EX | fcntl.LOCK_NB)<EOL><DEDENT>except IOError as e:<EOL><INDENT>logging.error("<STR_LIT>", dev)<EOL>continue<EOL><DEDENT>try: <EOL><INDENT>self.ser = serial.Serial("<STR_LIT>" % dev, timeout=<NUM_LIT:1>)<EOL>self.StopDataCollection() <EOL>self._FlushInput() <EOL>status = self.GetStatus()<EOL><DEDENT>except Exception as e:<EOL><INDENT>logging.exception("<STR_LIT>", dev, e)<EOL>continue<EOL><DEDENT>if not status:<EOL><INDENT>logging.error("<STR_LIT>", dev)<EOL><DEDENT>elif serialno and status["<STR_LIT>"] != serialno:<EOL><INDENT>logging.error("<STR_LIT>",<EOL>status["<STR_LIT>"], dev)<EOL><DEDENT>else:<EOL><INDENT>self.start_voltage = status["<STR_LIT>"]<EOL>return<EOL><DEDENT><DEDENT>self._tempfile = None<EOL>if not wait: raise IOError("<STR_LIT>")<EOL>logging.info("<STR_LIT>")<EOL>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>
|
Establish a connection to a Monsoon.
By default, opens the first available port, waiting if none are ready.
A particular port can be specified with "device", or a particular
Monsoon can be specified with "serialno" (using the number printed on
its back). With wait=0, IOError is thrown if a device is not
immediately available.
|
f7495:c1:m0
|
def GetStatus(self):
|
<EOL>STATUS_FORMAT = "<STR_LIT>"<EOL>STATUS_FIELDS = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT:status>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>]<EOL>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)<EOL>while <NUM_LIT:1>: <EOL><INDENT>read_bytes = self._ReadPacket()<EOL>if not read_bytes:<EOL><INDENT>return None<EOL><DEDENT>calsize = struct.calcsize(STATUS_FORMAT)<EOL>if len(read_bytes) != calsize or read_bytes[<NUM_LIT:0>] != <NUM_LIT>:<EOL><INDENT>logging.warning("<STR_LIT>",<EOL>read_bytes[<NUM_LIT:0>], len(read_bytes))<EOL>continue<EOL><DEDENT>status = dict(<EOL>zip(STATUS_FIELDS, struct.unpack(STATUS_FORMAT, read_bytes)))<EOL>p_type = status["<STR_LIT>"]<EOL>if p_type != <NUM_LIT>:<EOL><INDENT>raise MonsoonError("<STR_LIT>" % p_type)<EOL><DEDENT>for k in status.keys():<EOL><INDENT>if k.endswith("<STR_LIT>"):<EOL><INDENT>status[k] = <NUM_LIT> + status[k] * <NUM_LIT><EOL><DEDENT>elif k.endswith("<STR_LIT>"):<EOL><INDENT>pass <EOL><DEDENT>elif k.endswith("<STR_LIT>"):<EOL><INDENT>pass <EOL><DEDENT>elif k.startswith("<STR_LIT>") or k.endswith("<STR_LIT>"):<EOL><INDENT>status[k] = status[k] * <NUM_LIT><EOL><DEDENT>elif k.endswith("<STR_LIT>"):<EOL><INDENT>status[k] = <NUM_LIT> + status[k] * <NUM_LIT><EOL>if k.startswith("<STR_LIT>") or k.startswith("<STR_LIT>"):<EOL><INDENT>status[k] += <NUM_LIT><EOL><DEDENT><DEDENT>elif k.endswith("<STR_LIT>"):<EOL><INDENT>status[k] = <NUM_LIT:8> * (<NUM_LIT> - status[k]) / <NUM_LIT><EOL><DEDENT><DEDENT>return status<EOL><DEDENT>
|
Requests and waits for status.
Returns:
status dictionary.
|
f7495:c1:m1
|
def SetVoltage(self, v):
|
if v == <NUM_LIT:0>:<EOL><INDENT>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, int((v - <NUM_LIT>) * <NUM_LIT:100>))<EOL><DEDENT>
|
Set the output voltage, 0 to disable.
|
f7495:c1:m3
|
def GetVoltage(self):
|
return self.GetStatus()["<STR_LIT>"]<EOL>
|
Get the output voltage.
Returns:
Current Output Voltage (in unit of v).
|
f7495:c1:m4
|
def SetMaxCurrent(self, i):
|
if i < <NUM_LIT:0> or i > <NUM_LIT:8>:<EOL><INDENT>raise MonsoonError(("<STR_LIT>"<EOL>"<STR_LIT>") % i)<EOL><DEDENT>val = <NUM_LIT> - int((i / <NUM_LIT:8>) * <NUM_LIT>)<EOL>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, val & <NUM_LIT>)<EOL>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, val >> <NUM_LIT:8>)<EOL>
|
Set the max output current.
|
f7495:c1:m5
|
def SetMaxPowerUpCurrent(self, i):
|
if i < <NUM_LIT:0> or i > <NUM_LIT:8>:<EOL><INDENT>raise MonsoonError(("<STR_LIT>"<EOL>"<STR_LIT>") % i)<EOL><DEDENT>val = <NUM_LIT> - int((i / <NUM_LIT:8>) * <NUM_LIT>)<EOL>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, val & <NUM_LIT>)<EOL>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, val >> <NUM_LIT:8>)<EOL>
|
Set the max power up current.
|
f7495:c1:m6
|
def SetUsbPassthrough(self, val):
|
self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, val)<EOL>
|
Set the USB passthrough mode: 0 = off, 1 = on, 2 = auto.
|
f7495:c1:m7
|
def GetUsbPassthrough(self):
|
return self.GetStatus()["<STR_LIT>"]<EOL>
|
Get the USB passthrough mode: 0 = off, 1 = on, 2 = auto.
Returns:
Current USB passthrough mode.
|
f7495:c1:m8
|
def StartDataCollection(self):
|
self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, <NUM_LIT>) <EOL>self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)<EOL>
|
Tell the device to start collecting and sending measurement data.
|
f7495:c1:m9
|
def StopDataCollection(self):
|
self._SendStruct("<STR_LIT>", <NUM_LIT>, <NUM_LIT>)<EOL>
|
Tell the device to stop collecting measurement data.
|
f7495:c1:m10
|
def CollectData(self):
|
while <NUM_LIT:1>: <EOL><INDENT>_bytes = self._ReadPacket()<EOL>if not _bytes:<EOL><INDENT>return None<EOL><DEDENT>if len(_bytes) < <NUM_LIT:4> + <NUM_LIT:8> + <NUM_LIT:1> or _bytes[<NUM_LIT:0>] < <NUM_LIT> or _bytes[<NUM_LIT:0>] > <NUM_LIT>:<EOL><INDENT>logging.warning("<STR_LIT>",<EOL>_bytes[<NUM_LIT:0>], len(_bytes))<EOL>continue<EOL><DEDENT>seq, _type, x, y = struct.unpack("<STR_LIT>", _bytes[:<NUM_LIT:4>])<EOL>data = [<EOL>struct.unpack("<STR_LIT>", _bytes[x:x + <NUM_LIT:8>])<EOL>for x in range(<NUM_LIT:4>,<EOL>len(_bytes) - <NUM_LIT:8>, <NUM_LIT:8>)<EOL>]<EOL>if self._last_seq and seq & <NUM_LIT> != (self._last_seq + <NUM_LIT:1>) & <NUM_LIT>:<EOL><INDENT>logging.warning("<STR_LIT>")<EOL><DEDENT>self._last_seq = seq<EOL>if _type == <NUM_LIT:0>:<EOL><INDENT>if not self._coarse_scale or not self._fine_scale:<EOL><INDENT>logging.warning(<EOL>"<STR_LIT>")<EOL>continue<EOL><DEDENT>out = []<EOL>for main, usb, aux, voltage in data:<EOL><INDENT>if main & <NUM_LIT:1>:<EOL><INDENT>coarse = ((main & ~<NUM_LIT:1>) - self._coarse_zero)<EOL>out.append(coarse * self._coarse_scale)<EOL><DEDENT>else:<EOL><INDENT>out.append((main - self._fine_zero) * self._fine_scale)<EOL><DEDENT><DEDENT>return out<EOL><DEDENT>elif _type == <NUM_LIT:1>:<EOL><INDENT>self._fine_zero = data[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>self._coarse_zero = data[<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>elif _type == <NUM_LIT:2>:<EOL><INDENT>self._fine_ref = data[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>self._coarse_ref = data[<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>logging.warning("<STR_LIT>", _type)<EOL>continue<EOL><DEDENT>if self._coarse_ref != self._coarse_zero:<EOL><INDENT>self._coarse_scale = <NUM_LIT> / (<EOL>self._coarse_ref - self._coarse_zero)<EOL><DEDENT>if self._fine_ref != self._fine_zero:<EOL><INDENT>self._fine_scale = <NUM_LIT> / (self._fine_ref - self._fine_zero)<EOL><DEDENT><DEDENT>
|
Return some current samples. Call StartDataCollection() first.
|
f7495:c1:m11
|
def _SendStruct(self, fmt, *args):
|
data = struct.pack(fmt, *args)<EOL>data_len = len(data) + <NUM_LIT:1><EOL>checksum = (data_len + sum(bytearray(data))) % <NUM_LIT><EOL>out = struct.pack("<STR_LIT:B>", data_len) + data + struct.pack("<STR_LIT:B>", checksum)<EOL>self.ser.write(out)<EOL>
|
Pack a struct (without length or checksum) and send it.
|
f7495:c1:m12
|
def _ReadPacket(self):
|
len_char = self.ser.read(<NUM_LIT:1>)<EOL>if not len_char:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>return None<EOL><DEDENT>data_len = ord(len_char)<EOL>if not data_len:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>result = self.ser.read(int(data_len))<EOL>result = bytearray(result)<EOL>if len(result) != data_len:<EOL><INDENT>logging.error("<STR_LIT>",<EOL>data_len, len(result))<EOL>return None<EOL><DEDENT>body = result[:-<NUM_LIT:1>]<EOL>checksum = (sum(struct.unpack("<STR_LIT:B>" * len(body), body)) + data_len) % <NUM_LIT><EOL>if result[-<NUM_LIT:1>] != checksum:<EOL><INDENT>logging.error(<EOL>"<STR_LIT>",<EOL>hex(checksum), hex(result[-<NUM_LIT:1>]))<EOL>return None<EOL><DEDENT>return result[:-<NUM_LIT:1>]<EOL>
|
Read a single data record as a string (without length or checksum).
|
f7495:c1:m13
|
def _FlushInput(self):
|
self.ser.flush()<EOL>flushed = <NUM_LIT:0><EOL>while True:<EOL><INDENT>ready_r, ready_w, ready_x = select.select([self.ser], [],<EOL>[self.ser], <NUM_LIT:0>)<EOL>if len(ready_x) > <NUM_LIT:0>:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>return None<EOL><DEDENT>elif len(ready_r) > <NUM_LIT:0>:<EOL><INDENT>flushed += <NUM_LIT:1><EOL>self.ser.read(<NUM_LIT:1>) <EOL>self.ser.flush() <EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>
|
Flush all read data until no more available.
|
f7495:c1:m14
|
def __init__(self, data_points, timestamps, hz, voltage, offset=<NUM_LIT:0>):
|
self._data_points = data_points<EOL>self._timestamps = timestamps<EOL>self.offset = offset<EOL>num_of_data_pt = len(self._data_points)<EOL>if self.offset >= num_of_data_pt:<EOL><INDENT>raise MonsoonError(<EOL>("<STR_LIT>"<EOL>"<STR_LIT>") % (offset, num_of_data_pt))<EOL><DEDENT>self.data_points = self._data_points[self.offset:]<EOL>self.timestamps = self._timestamps[self.offset:]<EOL>self.hz = hz<EOL>self.voltage = voltage<EOL>self.tag = None<EOL>self._validate_data()<EOL>
|
Instantiates a MonsoonData object.
Args:
data_points: A list of current values in Amp (float).
timestamps: A list of epoch timestamps (int).
hz: The hertz at which the data points are measured.
voltage: The voltage at which the data points are measured.
offset: The number of initial data points to discard
in calculations.
|
f7495:c2:m0
|
@property<EOL><INDENT>def average_current(self):<DEDENT>
|
len_data_pt = len(self.data_points)<EOL>if len_data_pt == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>cur = sum(self.data_points) * <NUM_LIT:1000> / len_data_pt<EOL>return round(cur, self.sr)<EOL>
|
Average current in the unit of mA.
|
f7495:c2:m1
|
@property<EOL><INDENT>def total_charge(self):<DEDENT>
|
charge = (sum(self.data_points) / self.hz) * <NUM_LIT:1000> / <NUM_LIT><EOL>return round(charge, self.sr)<EOL>
|
Total charged used in the unit of mAh.
|
f7495:c2:m2
|
@property<EOL><INDENT>def total_power(self):<DEDENT>
|
power = self.average_current * self.voltage<EOL>return round(power, self.sr)<EOL>
|
Total power used.
|
f7495:c2:m3
|
@staticmethod<EOL><INDENT>def from_string(data_str):<DEDENT>
|
lines = data_str.strip().split('<STR_LIT:\n>')<EOL>err_msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>conditions = [<EOL>len(lines) <= <NUM_LIT:4>, "<STR_LIT>" not in lines[<NUM_LIT:1>],<EOL>"<STR_LIT>" not in lines[<NUM_LIT:2>], "<STR_LIT>" not in lines[<NUM_LIT:3>],<EOL>"<STR_LIT>" not in lines[<NUM_LIT:4>],<EOL>lines[<NUM_LIT:5>] != "<STR_LIT>" + '<STR_LIT:U+0020>' * <NUM_LIT:7> + "<STR_LIT>"<EOL>]<EOL>if any(conditions):<EOL><INDENT>raise MonsoonError(err_msg)<EOL><DEDENT>hz_str = lines[<NUM_LIT:4>].split()[<NUM_LIT:2>]<EOL>hz = int(hz_str[:-<NUM_LIT:2>])<EOL>voltage_str = lines[<NUM_LIT:2>].split()[<NUM_LIT:1>]<EOL>voltage = int(voltage_str[:-<NUM_LIT:1>])<EOL>lines = lines[<NUM_LIT:6>:]<EOL>t = []<EOL>v = []<EOL>for l in lines:<EOL><INDENT>try:<EOL><INDENT>timestamp, value = l.split('<STR_LIT:U+0020>')<EOL>t.append(int(timestamp))<EOL>v.append(float(value))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise MonsoonError(err_msg)<EOL><DEDENT><DEDENT>return MonsoonData(v, t, hz, voltage)<EOL>
|
Creates a MonsoonData object from a string representation generated
by __str__.
Args:
str: The string representation of a MonsoonData.
Returns:
A MonsoonData object.
|
f7495:c2:m4
|
@staticmethod<EOL><INDENT>def save_to_text_file(monsoon_data, file_path):<DEDENT>
|
if not monsoon_data:<EOL><INDENT>raise MonsoonError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>utils.create_dir(os.path.dirname(file_path))<EOL>with io.open(file_path, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>for md in monsoon_data:<EOL><INDENT>f.write(str(md))<EOL>f.write(MonsoonData.delimiter)<EOL><DEDENT><DEDENT>
|
Save multiple MonsoonData objects to a text file.
Args:
monsoon_data: A list of MonsoonData objects to write to a text
file.
file_path: The full path of the file to save to, including the file
name.
|
f7495:c2:m5
|
@staticmethod<EOL><INDENT>def from_text_file(file_path):<DEDENT>
|
results = []<EOL>with io.open(file_path, '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>data_strs = f.read().split(MonsoonData.delimiter)<EOL>for data_str in data_strs:<EOL><INDENT>results.append(MonsoonData.from_string(data_str))<EOL><DEDENT><DEDENT>return results<EOL>
|
Load MonsoonData objects from a text file generated by
MonsoonData.save_to_text_file.
Args:
file_path: The full path of the file load from, including the file
name.
Returns:
A list of MonsoonData objects.
|
f7495:c2:m6
|
def _validate_data(self):
|
msg = "<STR_LIT>".format(<EOL>len(self._data_points), len(self._timestamps))<EOL>if len(self._data_points) != len(self._timestamps):<EOL><INDENT>raise MonsoonError(msg)<EOL><DEDENT>
|
Verifies that the data points contained in the class are valid.
|
f7495:c2:m7
|
def update_offset(self, new_offset):
|
self.offset = new_offset<EOL>self.data_points = self._data_points[self.offset:]<EOL>self.timestamps = self._timestamps[self.offset:]<EOL>
|
Updates how many data points to skip in caculations.
Always use this function to update offset instead of directly setting
self.offset.
Args:
new_offset: The new offset.
|
f7495:c2:m8
|
def get_data_with_timestamps(self):
|
result = []<EOL>for t, d in zip(self.timestamps, self.data_points):<EOL><INDENT>result.append(t, round(d, self.lr))<EOL><DEDENT>return result<EOL>
|
Returns the data points with timestamps.
Returns:
A list of tuples in the format of (timestamp, data)
|
f7495:c2:m9
|
def get_average_record(self, n):
|
history_deque = collections.deque()<EOL>averages = []<EOL>for d in self.data_points:<EOL><INDENT>history_deque.appendleft(d)<EOL>if len(history_deque) > n:<EOL><INDENT>history_deque.pop()<EOL><DEDENT>avg = sum(history_deque) / len(history_deque)<EOL>averages.append(round(avg, self.lr))<EOL><DEDENT>return averages<EOL>
|
Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values.
|
f7495:c2:m10
|
def attach_device(self, dut):
|
self.dut = dut<EOL>
|
Attach the controller object for the Device Under Test (DUT)
physically attached to the Monsoon box.
Args:
dut: A controller object representing the device being powered by
this Monsoon box.
|
f7495:c3:m1
|
def set_voltage(self, volt, ramp=False):
|
if ramp:<EOL><INDENT>self.mon.RampVoltage(self.mon.start_voltage, volt)<EOL><DEDENT>else:<EOL><INDENT>self.mon.SetVoltage(volt)<EOL><DEDENT>
|
Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage.
|
f7495:c3:m2
|
def set_max_current(self, cur):
|
self.mon.SetMaxCurrent(cur)<EOL>
|
Sets monsoon's max output current.
Args:
cur: The max current in A.
|
f7495:c3:m3
|
def set_max_init_current(self, cur):
|
self.mon.SetMaxPowerUpCurrent(cur)<EOL>
|
Sets the max power-up/inital current.
Args:
cur: The max initial current allowed in mA.
|
f7495:c3:m4
|
@property<EOL><INDENT>def status(self):<DEDENT>
|
return self.mon.GetStatus()<EOL>
|
Gets the status params of monsoon.
Returns:
A dictionary where each key-value pair represents a monsoon status
param.
|
f7495:c3:m5
|
def take_samples(self, sample_hz, sample_num, sample_offset=<NUM_LIT:0>, live=False):
|
sys.stdout.flush()<EOL>voltage = self.mon.GetVoltage()<EOL>self.log.info("<STR_LIT>",<EOL>sample_hz, (sample_num / sample_hz), voltage)<EOL>sample_num += sample_offset<EOL>self.mon.StopDataCollection()<EOL>status = self.mon.GetStatus()<EOL>native_hz = status["<STR_LIT>"] * <NUM_LIT:1000><EOL>self.mon.StartDataCollection()<EOL>emitted = offset = <NUM_LIT:0><EOL>collected = []<EOL>history_deque = collections.deque()<EOL>current_values = []<EOL>timestamps = []<EOL>try:<EOL><INDENT>last_flush = time.time()<EOL>while emitted < sample_num or sample_num == -<NUM_LIT:1>:<EOL><INDENT>need = int((native_hz - offset + sample_hz - <NUM_LIT:1>) / sample_hz)<EOL>if need > len(collected): <EOL><INDENT>samples = self.mon.CollectData()<EOL>if not samples:<EOL><INDENT>break<EOL><DEDENT>collected.extend(samples)<EOL><DEDENT>else:<EOL><INDENT>offset += need * sample_hz<EOL>while offset >= native_hz:<EOL><INDENT>this_sample = sum(collected[:need]) / need<EOL>this_time = int(time.time())<EOL>timestamps.append(this_time)<EOL>if live:<EOL><INDENT>self.log.info("<STR_LIT>", this_time, this_sample)<EOL><DEDENT>current_values.append(this_sample)<EOL>sys.stdout.flush()<EOL>offset -= native_hz<EOL>emitted += <NUM_LIT:1> <EOL><DEDENT>collected = collected[need:]<EOL>now = time.time()<EOL>if now - last_flush >= <NUM_LIT>: <EOL><INDENT>sys.stdout.flush()<EOL>last_flush = now<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT>self.mon.StopDataCollection()<EOL>try:<EOL><INDENT>return MonsoonData(<EOL>current_values,<EOL>timestamps,<EOL>sample_hz,<EOL>voltage,<EOL>offset=sample_offset)<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>
|
Take samples of the current value supplied by monsoon.
This is the actual measurement for power consumption. This function
blocks until the number of samples requested has been fulfilled.
Args:
hz: Number of points to take for every second.
sample_num: Number of samples to take.
offset: The number of initial data points to discard in MonsoonData
calculations. sample_num is extended by offset to compensate.
live: Print each sample in console as measurement goes on.
Returns:
A MonsoonData object representing the data obtained in this
sampling. None if sampling is unsuccessful.
|
f7495:c3:m6
|
@timeout_decorator.timeout(<NUM_LIT>, use_signals=False)<EOL><INDENT>def usb(self, state):<DEDENT>
|
state_lookup = {"<STR_LIT>": <NUM_LIT:0>, "<STR_LIT>": <NUM_LIT:1>, "<STR_LIT>": <NUM_LIT:2>}<EOL>state = state.lower()<EOL>if state in state_lookup:<EOL><INDENT>current_state = self.mon.GetUsbPassthrough()<EOL>while (current_state != state_lookup[state]):<EOL><INDENT>self.mon.SetUsbPassthrough(state_lookup[state])<EOL>time.sleep(<NUM_LIT:1>)<EOL>current_state = self.mon.GetUsbPassthrough()<EOL><DEDENT>return True<EOL><DEDENT>return False<EOL>
|
Sets the monsoon's USB passthrough mode. This is specific to the
USB port in front of the monsoon box which connects to the powered
device, NOT the USB that is used to talk to the monsoon itself.
"Off" means USB always off.
"On" means USB always on.
"Auto" means USB is automatically turned off when sampling is going on,
and turned back on when sampling finishes.
Args:
stats: The state to set the USB passthrough to.
Returns:
True if the state is legal and set. False otherwise.
|
f7495:c3:m7
|
def _check_dut(self):
|
if not self.dut:<EOL><INDENT>raise MonsoonError("<STR_LIT>")<EOL><DEDENT>
|
Verifies there is a DUT attached to the monsoon.
This should be called in the functions that operate the DUT.
|
f7495:c3:m8
|
def measure_power(self, hz, duration, tag, offset=<NUM_LIT:30>):
|
num = duration * hz<EOL>oset = offset * hz<EOL>data = None<EOL>self.usb("<STR_LIT>")<EOL>time.sleep(<NUM_LIT:1>)<EOL>with self.dut.handle_usb_disconnect():<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL>try:<EOL><INDENT>data = self.take_samples(hz, num, sample_offset=oset)<EOL>if not data:<EOL><INDENT>raise MonsoonError(<EOL>"<STR_LIT>" % tag)<EOL><DEDENT>data.tag = tag<EOL>self.dut.log.info("<STR_LIT>", repr(data))<EOL>return data<EOL><DEDENT>finally:<EOL><INDENT>self.mon.StopDataCollection()<EOL>self.log.info("<STR_LIT>")<EOL>self.usb("<STR_LIT>")<EOL>self.dut.adb.wait_for_device(timeout=DEFAULT_TIMEOUT_USB_ON)<EOL>time.sleep(<NUM_LIT:10>)<EOL>self.dut.log.info("<STR_LIT>")<EOL><DEDENT><DEDENT>
|
Measure power consumption of the attached device.
Because it takes some time for the device to calm down after the usb
connection is cut, an offset is set for each measurement. The default
is 30s. The total time taken to measure will be (duration + offset).
Args:
hz: Number of samples to take per second.
duration: Number of seconds to take samples for in each step.
offset: The number of seconds of initial data to discard.
tag: A string that's the name of the collected data group.
Returns:
A MonsoonData object with the measured power data.
|
f7495:c3:m9
|
def create(configs):
|
if not configs:<EOL><INDENT>raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)<EOL><DEDENT>elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:<EOL><INDENT>ads = get_all_instances()<EOL><DEDENT>elif not isinstance(configs, list):<EOL><INDENT>raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)<EOL><DEDENT>elif isinstance(configs[<NUM_LIT:0>], dict):<EOL><INDENT>ads = get_instances_with_configs(configs)<EOL><DEDENT>elif isinstance(configs[<NUM_LIT:0>], basestring):<EOL><INDENT>ads = get_instances(configs)<EOL><DEDENT>else:<EOL><INDENT>raise Error('<STR_LIT>' % configs)<EOL><DEDENT>valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id()<EOL>for ad in ads:<EOL><INDENT>if ad.serial not in valid_ad_identifiers:<EOL><INDENT>raise DeviceError(ad, '<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>_start_services_on_ads(ads)<EOL>return ads<EOL>
|
Creates AndroidDevice controller objects.
Args:
configs: A list of dicts, each representing a configuration for an
Android device.
Returns:
A list of AndroidDevice objects.
|
f7496:m0
|
def destroy(ads):
|
for ad in ads:<EOL><INDENT>try:<EOL><INDENT>ad.services.stop_all()<EOL><DEDENT>except:<EOL><INDENT>ad.log.exception('<STR_LIT>')<EOL><DEDENT><DEDENT>
|
Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects.
|
f7496:m1
|
def get_info(ads):
|
return [ad.device_info for ad in ads]<EOL>
|
Get information on a list of AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects.
Returns:
A list of dict, each representing info for an AndroidDevice objects.
|
f7496:m2
|
def _start_services_on_ads(ads):
|
running_ads = []<EOL>for ad in ads:<EOL><INDENT>running_ads.append(ad)<EOL>start_logcat = not getattr(ad, KEY_SKIP_LOGCAT,<EOL>DEFAULT_VALUE_SKIP_LOGCAT)<EOL>try:<EOL><INDENT>ad.services.register(<EOL>SERVICE_NAME_LOGCAT, logcat.Logcat, start_service=start_logcat)<EOL><DEDENT>except Exception:<EOL><INDENT>is_required = getattr(ad, KEY_DEVICE_REQUIRED,<EOL>DEFAULT_VALUE_DEVICE_REQUIRED)<EOL>if is_required:<EOL><INDENT>ad.log.exception('<STR_LIT>')<EOL>destroy(running_ads)<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>ad.log.exception('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>
|
Starts long running services on multiple AndroidDevice objects.
If any one AndroidDevice object fails to start services, cleans up all
existing AndroidDevice objects and their services.
Args:
ads: A list of AndroidDevice objects whose services to start.
|
f7496:m3
|
def _parse_device_list(device_list_str, key):
|
return parse_device_list(device_list_str, key)<EOL>
|
Parses a byte string representing a list of devices.
Deprecated, use `parse_device_list(device_list_str, key)` instead.
This method will be removed in 1.9.
|
f7496:m4
|
def parse_device_list(device_list_str, key):
|
clean_lines = new_str(device_list_str, '<STR_LIT:utf-8>').strip().split('<STR_LIT:\n>')<EOL>results = []<EOL>for line in clean_lines:<EOL><INDENT>tokens = line.strip().split('<STR_LIT:\t>')<EOL>if len(tokens) == <NUM_LIT:2> and tokens[<NUM_LIT:1>] == key:<EOL><INDENT>results.append(tokens[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>return results<EOL>
|
Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a device in device_list_str.
Returns:
A list of android device serial numbers.
|
f7496:m5
|
def list_adb_devices():
|
out = adb.AdbProxy().devices()<EOL>return parse_device_list(out, '<STR_LIT>')<EOL>
|
List all android devices connected to the computer that are detected by
adb.
Returns:
A list of android device serials. Empty if there's none.
|
f7496:m6
|
def list_adb_devices_by_usb_id():
|
out = adb.AdbProxy().devices(['<STR_LIT>'])<EOL>clean_lines = new_str(out, '<STR_LIT:utf-8>').strip().split('<STR_LIT:\n>')<EOL>results = []<EOL>for line in clean_lines:<EOL><INDENT>tokens = line.strip().split()<EOL>if len(tokens) > <NUM_LIT:2> and tokens[<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>results.append(tokens[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>return results<EOL>
|
List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none.
|
f7496:m7
|
def list_fastboot_devices():
|
out = fastboot.FastbootProxy().devices()<EOL>return parse_device_list(out, '<STR_LIT>')<EOL>
|
List all android devices connected to the computer that are in in
fastboot mode. These are detected by fastboot.
Returns:
A list of android device serials. Empty if there's none.
|
f7496:m8
|
def get_instances(serials):
|
results = []<EOL>for s in serials:<EOL><INDENT>results.append(AndroidDevice(s))<EOL><DEDENT>return results<EOL>
|
Create AndroidDevice instances from a list of serials.
Args:
serials: A list of android device serials.
Returns:
A list of AndroidDevice objects.
|
f7496:m9
|
def get_instances_with_configs(configs):
|
results = []<EOL>for c in configs:<EOL><INDENT>try:<EOL><INDENT>serial = c.pop('<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>raise Error(<EOL>'<STR_LIT>'<EOL>% c)<EOL><DEDENT>is_required = c.get(KEY_DEVICE_REQUIRED, True)<EOL>try:<EOL><INDENT>ad = AndroidDevice(serial)<EOL>ad.load_config(c)<EOL><DEDENT>except Exception:<EOL><INDENT>if is_required:<EOL><INDENT>raise<EOL><DEDENT>ad.log.exception('<STR_LIT>')<EOL>continue<EOL><DEDENT>results.append(ad)<EOL><DEDENT>return results<EOL>
|
Create AndroidDevice instances from a list of dict configs.
Each config should have the required key-value pair 'serial'.
Args:
configs: A list of dicts each representing the configuration of one
android device.
Returns:
A list of AndroidDevice objects.
|
f7496:m10
|
def get_all_instances(include_fastboot=False):
|
if include_fastboot:<EOL><INDENT>serial_list = list_adb_devices() + list_fastboot_devices()<EOL>return get_instances(serial_list)<EOL><DEDENT>return get_instances(list_adb_devices())<EOL>
|
Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
attached to the computer.
|
f7496:m11
|
def filter_devices(ads, func):
|
results = []<EOL>for ad in ads:<EOL><INDENT>if func(ad):<EOL><INDENT>results.append(ad)<EOL><DEDENT><DEDENT>return results<EOL>
|
Finds the AndroidDevice instances from a list that match certain
conditions.
Args:
ads: A list of AndroidDevice instances.
func: A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition.
Returns:
A list of AndroidDevice instances that satisfy the filter condition.
|
f7496:m12
|
def get_devices(ads, **kwargs):
|
def _get_device_filter(ad):<EOL><INDENT>for k, v in kwargs.items():<EOL><INDENT>if not hasattr(ad, k):<EOL><INDENT>return False<EOL><DEDENT>elif getattr(ad, k) != v:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>filtered = filter_devices(ads, _get_device_filter)<EOL>if not filtered:<EOL><INDENT>raise Error(<EOL>'<STR_LIT>' %<EOL>kwargs)<EOL><DEDENT>else:<EOL><INDENT>return filtered<EOL><DEDENT>
|
Finds a list of AndroidDevice instance from a list that has specific
attributes of certain values.
Example:
get_devices(android_devices, label='foo', phone_number='1234567890')
get_devices(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
A list of target AndroidDevice instances.
Raises:
Error: No devices are matched.
|
f7496:m13
|
def get_device(ads, **kwargs):
|
filtered = get_devices(ads, **kwargs)<EOL>if len(filtered) == <NUM_LIT:1>:<EOL><INDENT>return filtered[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>serials = [ad.serial for ad in filtered]<EOL>raise Error('<STR_LIT>' % serials)<EOL><DEDENT>
|
Finds a unique AndroidDevice instance from a list that has specific
attributes of certain values.
Deprecated, use `get_devices(ads, **kwargs)[0]` instead.
This method will be removed in 1.8.
Example:
get_device(android_devices, label='foo', phone_number='1234567890')
get_device(android_devices, model='angler')
Args:
ads: A list of AndroidDevice instances.
kwargs: keyword arguments used to filter AndroidDevice instances.
Returns:
The target AndroidDevice instance.
Raises:
Error: None or more than one device is matched.
|
f7496:m14
|
@property<EOL><INDENT>def _normalized_serial(self):<DEDENT>
|
if self._serial is None:<EOL><INDENT>return None<EOL><DEDENT>normalized_serial = self._serial.replace('<STR_LIT:U+0020>', '<STR_LIT:_>')<EOL>normalized_serial = normalized_serial.replace('<STR_LIT::>', '<STR_LIT:->')<EOL>return normalized_serial<EOL>
|
Normalized serial name for usage in log filename.
Some Android emulators use ip:port as their serial names, while on
Windows `:` is not valid in filename, it should be sanitized first.
|
f7496:c0:m3
|
@property<EOL><INDENT>def device_info(self):<DEDENT>
|
info = {<EOL>'<STR_LIT>': self.serial,<EOL>'<STR_LIT>': self.model,<EOL>'<STR_LIT>': self.build_info,<EOL>'<STR_LIT>': self._user_added_device_info<EOL>}<EOL>return info<EOL>
|
Information to be pulled into controller info.
The latest serial, model, and build_info are included. Additional info
can be added via `add_device_info`.
|
f7496:c0:m4
|
def add_device_info(self, name, info):
|
self._user_added_device_info.update({name: info})<EOL>
|
Add information of the device to be pulled into controller info.
Adding the same info name the second time will override existing info.
Args:
name: string, name of this info.
info: serializable, content of the info.
|
f7496:c0:m5
|
@property<EOL><INDENT>def sl4a(self):<DEDENT>
|
if self.services.has_service_by_name('<STR_LIT>'):<EOL><INDENT>return self.services.sl4a<EOL><DEDENT>
|
Attribute for direct access of sl4a client.
Not recommended. This is here for backward compatibility reasons.
Preferred: directly access `ad.services.sl4a`.
|
f7496:c0:m6
|
@property<EOL><INDENT>def ed(self):<DEDENT>
|
if self.services.has_service_by_name('<STR_LIT>'):<EOL><INDENT>return self.services.sl4a.ed<EOL><DEDENT>
|
Attribute for direct access of sl4a's event dispatcher.
Not recommended. This is here for backward compatibility reasons.
Preferred: directly access `ad.services.sl4a.ed`.
|
f7496:c0:m7
|
@property<EOL><INDENT>def debug_tag(self):<DEDENT>
|
return self._debug_tag<EOL>
|
A string that represents a device object in debug info. Default value
is the device serial.
This will be used as part of the prefix of debugging messages emitted by
this device object, like log lines and the message of DeviceError.
|
f7496:c0:m8
|
@debug_tag.setter<EOL><INDENT>def debug_tag(self, tag):<DEDENT>
|
self.log.info('<STR_LIT>', tag)<EOL>self._debug_tag = tag<EOL>self.log.extra['<STR_LIT>'] = tag<EOL>
|
Setter for the debug tag.
By default, the tag is the serial of the device, but sometimes it may
be more descriptive to use a different tag of the user's choice.
Changing debug tag changes part of the prefix of debug info emitted by
this object, like log lines and the message of DeviceError.
Example:
By default, the device's serial number is used:
'INFO [AndroidDevice|abcdefg12345] One pending call ringing.'
The tag can be customized with `ad.debug_tag = 'Caller'`:
'INFO [AndroidDevice|Caller] One pending call ringing.'
|
f7496:c0:m9
|
@property<EOL><INDENT>def has_active_service(self):<DEDENT>
|
return self.services.is_any_alive<EOL>
|
True if any service is running on the device.
A service can be a snippet or logcat collection.
|
f7496:c0:m10
|
@property<EOL><INDENT>def log_path(self):<DEDENT>
|
return self._log_path<EOL>
|
A string that is the path for all logs collected from this device.
|
f7496:c0:m11
|
@log_path.setter<EOL><INDENT>def log_path(self, new_path):<DEDENT>
|
if self.has_active_service:<EOL><INDENT>raise DeviceError(<EOL>self,<EOL>'<STR_LIT>')<EOL><DEDENT>old_path = self._log_path<EOL>if new_path == old_path:<EOL><INDENT>return<EOL><DEDENT>if os.listdir(new_path):<EOL><INDENT>raise DeviceError(<EOL>self, '<STR_LIT>' % new_path)<EOL><DEDENT>if os.path.exists(old_path):<EOL><INDENT>shutil.rmtree(new_path, ignore_errors=True)<EOL>shutil.copytree(old_path, new_path)<EOL>shutil.rmtree(old_path, ignore_errors=True)<EOL><DEDENT>self._log_path = new_path<EOL>
|
Setter for `log_path`, use with caution.
|
f7496:c0:m12
|
@property<EOL><INDENT>def serial(self):<DEDENT>
|
return self._serial<EOL>
|
The serial number used to identify a device.
This is essentially the value used for adb's `-s` arg, which means it
can be a network address or USB bus number.
|
f7496:c0:m13
|
def update_serial(self, new_serial):
|
new_serial = str(new_serial)<EOL>if self.has_active_service:<EOL><INDENT>raise DeviceError(<EOL>self,<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if self._debug_tag == self.serial:<EOL><INDENT>self._debug_tag = new_serial<EOL><DEDENT>self._serial = new_serial<EOL>self.adb.serial = new_serial<EOL>self.fastboot.serial = new_serial<EOL>
|
Updates the serial number of a device.
The "serial number" used with adb's `-s` arg is not necessarily the
actual serial number. For remote devices, it could be a combination of
host names and port numbers.
This is used for when such identifier of remote devices changes during
a test. For example, when a remote device reboots, it may come back
with a different serial number.
This is NOT meant for switching the object to represent another device.
We intentionally did not make it a regular setter of the serial
property so people don't accidentally call this without understanding
the consequences.
Args:
new_serial: string, the new serial number for the same device.
Raises:
DeviceError: tries to update serial when any service is running.
|
f7496:c0:m14
|
@contextlib.contextmanager<EOL><INDENT>def handle_reboot(self):<DEDENT>
|
self.services.stop_all()<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>self.wait_for_boot_completion()<EOL>if self.is_rootable:<EOL><INDENT>self.root_adb()<EOL><DEDENT><DEDENT>self.services.start_all()<EOL>
|
Properly manage the service life cycle when the device needs to
temporarily disconnect.
The device can temporarily lose adb connection due to user-triggered
reboot. Use this function to make sure the services
started by Mobly are properly stopped and restored afterwards.
For sample usage, see self.reboot().
|
f7496:c0:m15
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.