code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
# if instance is known, return it
if instance_id in self._instances:
return self._instances[instance_id]
# else, check (cached) list from provider
if instance_id not in self._cached_instances:
self._cached_instances = self._build_cached_instances()
if instance_id in self._cached_instances:
inst = self._cached_instances[instance_id]
self._instances[instance_id] = inst
return inst
# If we reached this point, the instance was not found neither
# in the caches nor on the website.
raise InstanceNotFoundError(
"Instance `{instance_id}` not found"
.format(instance_id=instance_id)) | def _load_instance(self, instance_id) | Return instance with the given id.
For performance reasons, the instance ID is first searched for in the
collection of VM instances started by ElastiCluster
(`self._instances`), then in the list of all instances known to the
cloud provider at the time of the last update
(`self._cached_instances`), and finally the cloud provider is directly
queried.
:param str instance_id: instance identifier
:return: py:class:`boto.ec2.instance.Reservation` - instance
:raises: `InstanceError` is returned if the instance can't
be found in the local cache or in the cloud. | 3.210735 | 3.035847 | 1.057608 |
connection = self._connect()
reservations = connection.get_all_reservations()
cached_instances = {}
for rs in reservations:
for vm in rs.instances:
cached_instances[vm.id] = vm
return cached_instances | def _build_cached_instances(self) | Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object. | 3.623071 | 2.730761 | 1.326762 |
connection = self._connect()
keypairs = connection.get_all_key_pairs()
keypairs = dict((k.name, k) for k in keypairs)
# decide if dsa or rsa key is provided
pkey = None
is_dsa_key = False
try:
pkey = DSSKey.from_private_key_file(private_key_path)
is_dsa_key = True
except PasswordRequiredException:
warn("Unable to check key file `{0}` because it is encrypted with a "
"password. Please, ensure that you added it to the SSH agent "
"with `ssh-add {1}`"
.format(private_key_path, private_key_path))
except SSHException:
try:
pkey = RSAKey.from_private_key_file(private_key_path)
except PasswordRequiredException:
warn("Unable to check key file `{0}` because it is encrypted with a "
"password. Please, ensure that you added it to the SSH agent "
"with `ssh-add {1}`"
.format(private_key_path, private_key_path))
except SSHException:
raise KeypairError('File `%s` is neither a valid DSA key '
'or RSA key.' % private_key_path)
# create keys that don't exist yet
if name not in keypairs:
log.warning(
"Keypair `%s` not found on resource `%s`, Creating a new one",
name, self._url)
with open(os.path.expanduser(public_key_path)) as f:
key_material = f.read()
try:
# check for DSA on amazon
if "amazon" in self._ec2host and is_dsa_key:
log.error(
"Apparently, amazon does not support DSA keys. "
"Please specify a valid RSA key.")
raise KeypairError(
"Apparently, amazon does not support DSA keys."
"Please specify a valid RSA key.")
connection.import_key_pair(name, key_material)
except Exception as ex:
log.error(
"Could not import key `%s` with name `%s` to `%s`",
name, public_key_path, self._url)
raise KeypairError(
"could not create keypair `%s`: %s" % (name, ex))
else:
# check fingerprint
cloud_keypair = keypairs[name]
if pkey:
if "amazon" in self._ec2host:
# AWS takes the MD5 hash of the key's DER representation.
key = RSA.importKey(open(private_key_path).read())
der = key.publickey().exportKey('DER')
m = hashlib.md5()
m.update(der)
digest = m.hexdigest()
fingerprint = ':'.join(digest[i:(i + 2)]
for i in range(0, len(digest), 2))
else:
fingerprint = ':'.join(byte_to_hex(byte)
for byte in pkey.get_fingerprint())
if fingerprint != cloud_keypair.fingerprint:
if "amazon" in self._ec2host:
log.error(
"Apparently, Amazon does not compute the RSA key "
"fingerprint as we do! We cannot check if the "
"uploaded keypair is correct!")
else:
raise KeypairError(
"Keypair `%s` is present but has "
"different fingerprint. Aborting!" % name) | def _check_keypair(self, name, public_key_path, private_key_path) | First checks if the keypair is valid, then checks if the keypair
is registered with on the cloud. If not the keypair is added to the
users ssh keys.
:param str name: name of the ssh key
:param str public_key_path: path to the ssh public key file
:param str private_key_path: path to the ssh private key file
:raises: `KeypairError` if key is not a valid RSA or DSA key,
the key could not be uploaded or the fingerprint does not
match to the one uploaded to the cloud. | 3.006385 | 2.929654 | 1.026191 |
connection = self._connect()
filters = {}
if self._vpc:
filters = {'vpc-id': self._vpc_id}
security_groups = connection.get_all_security_groups(filters=filters)
matching_groups = [
group
for group
in security_groups
if name in [group.name, group.id]
]
if len(matching_groups) == 0:
raise SecurityGroupError(
"the specified security group %s does not exist" % name)
elif len(matching_groups) == 1:
return matching_groups[0].id
elif self._vpc and len(matching_groups) > 1:
raise SecurityGroupError(
"the specified security group name %s matches "
"more than one security group" % name) | def _check_security_group(self, name) | Checks if the security group exists.
:param str name: name of the security group
:return: str - security group id of the security group
:raises: `SecurityGroupError` if group does not exist | 2.467207 | 2.443385 | 1.00975 |
# Subnets only exist in VPCs, so we don't need to worry about
# the EC2 Classic case here.
subnets = self._vpc_connection.get_all_subnets(
filters={'vpcId': self._vpc_id})
matching_subnets = [
subnet
for subnet
in subnets
if name in [subnet.tags.get('Name'), subnet.id]
]
if len(matching_subnets) == 0:
raise SubnetError(
"the specified subnet %s does not exist" % name)
elif len(matching_subnets) == 1:
return matching_subnets[0].id
else:
raise SubnetError(
"the specified subnet name %s matches more than "
"one subnet" % name) | def _check_subnet(self, name) | Checks if the subnet exists.
:param str name: name of the subnet
:return: str - subnet id of the subnet
:raises: `SubnetError` if group does not exist | 3.008227 | 2.987951 | 1.006786 |
if not self._images:
connection = self._connect()
self._images = connection.get_all_images()
image_id_cloud = None
for i in self._images:
if i.id == image_id or i.name == image_id:
image_id_cloud = i.id
break
if image_id_cloud:
return image_id_cloud
else:
raise ImageError(
"Could not find given image id `%s`" % image_id) | def _find_image_id(self, image_id) | Finds an image id to a given id or name.
:param str image_id: name or id of image
:return: str - identifier of image | 2.758765 | 2.830486 | 0.974661 |
for old, new in [('_user_key_public', 'user_key_public'),
('_user_key_private', 'user_key_private'),
('_user_key_name', 'user_key_name'),]:
if hasattr(cluster, old):
setattr(cluster, new, getattr(cluster, old))
delattr(cluster, old)
for kind, nodes in cluster.nodes.items():
for node in nodes:
if hasattr(node, 'image'):
image_id = getattr(node, 'image_id', None) or node.image
setattr(node, 'image_id', image_id)
delattr(node, 'image')
# Possibly related to issue #129
if not hasattr(cluster, 'thread_pool_max_size'):
cluster.thread_pool_max_size = 10
return cluster | def migrate_cluster(cluster) | Called when loading a cluster when it comes from an older version
of elasticluster | 2.796541 | 2.807216 | 0.996197 |
if name not in self.clusters:
raise ClusterNotFound("Cluster %s not found." % name)
return self.clusters.get(name) | def get(self, name) | Retrieves the cluster by the given name.
:param str name: name of the cluster (identifier)
:return: instance of :py:class:`elasticluster.cluster.Cluster` that
matches the given name | 4.031376 | 4.085722 | 0.986698 |
if cluster.name not in self.clusters:
raise ClusterNotFound(
"Unable to delete non-existent cluster %s" % cluster.name)
del self.clusters[cluster.name] | def delete(self, cluster) | Deletes the cluster from memory.
:param cluster: cluster to delete
:type cluster: :py:class:`elasticluster.cluster.Cluster` | 3.284527 | 3.832486 | 0.857022 |
clusters = []
cluster_files = glob.glob("%s/*.%s" % (self.storage_path, self.file_ending))
for fname in cluster_files:
try:
name = fname[:-len(self.file_ending)-1]
clusters.append(self.get(name))
except (ImportError, AttributeError) as ex:
log.error("Unable to load cluster %s: `%s`", fname, ex)
log.error("If cluster %s was created with a previous version of elasticluster, you may need to run `elasticluster migrate %s %s` to update it.", cluster_file, self.storage_path, fname)
return clusters | def get_all(self) | Retrieves all clusters from the persistent state.
:return: list of :py:class:`elasticluster.cluster.Cluster` | 4.528258 | 3.897576 | 1.161814 |
path = self._get_cluster_storage_path(cluster.name)
if os.path.exists(path):
os.unlink(path) | def delete(self, cluster) | Deletes the cluster from persistent state.
:param cluster: cluster to delete from persistent state
:type cluster: :py:class:`elasticluster.cluster.Cluster` | 3.804042 | 4.502062 | 0.844955 |
cluster = pickle.load(fp)
cluster.repository = self
return cluster | def load(self, fp) | Load cluster from file descriptor fp | 11.152642 | 7.853427 | 1.420099 |
for cls in self.storage_type_map.values():
filename = os.path.join(self.storage_path,
'{name}.{ending}'.format(
name=name,
ending=cls.file_ending))
if os.path.exists(filename):
try:
return cls(self.storage_path)
except:
continue
raise ClusterNotFound(
"No state file for cluster `{name}` was found in directory `{path}`"
.format(name=name, path=self.storage_path)) | def _get_store_by_name(self, name) | Return an instance of the correct DiskRepository based on the *first* file that matches the standard syntax for repository files | 3.828985 | 3.534652 | 1.083271 |
repo = repository.PickleRepository(self.params.storage_path)
clusters = [i[:-7] for i in os.listdir(self.params.storage_path) if i.endswith('.pickle')]
if self.params.cluster:
clusters = [x for x in clusters if x in self.params.cluster]
if not clusters:
print("No clusters")
sys.exit(0)
patch_cluster()
for cluster in clusters:
print("Cluster `%s`" % cluster)
print("path: %s" % repo.storage_path + '/%s.pickle' % cluster)
cl = repo.get(cluster)
if cl._patches:
print("Attributes changed: ")
for attr, val in cl._patches.items():
print(" %s: %s -> %s" % (attr, val[0], val[1]))
else:
print("No upgrade needed")
print("")
if not self.params.dry_run:
if cl._patches:
del cl._patches
print("Changes saved to disk")
cl.repository.save_or_update(cl) | def execute(self) | migrate storage | 3.952429 | 3.847616 | 1.027241 |
click.echo('Init the db...')
db.create_all()
for i in range(30):
click.echo("Creating user/address combo #{}...".format(i))
address = Address(description='Address#2' + str(i).rjust(2, "0"))
db.session.add(address)
user = User(name='User#1' + str(i).rjust(2, "0"))
user.address = address
db.session.add(user)
sleep(1)
db.session.commit() | def initdb() | Initialize the database. | 3.544557 | 3.571186 | 0.992544 |
# defining columns
columns = [
ColumnDT(User.id),
ColumnDT(User.name),
ColumnDT(Address.description),
ColumnDT(User.created_at)
]
# defining the initial query depending on your purpose
query = db.session.query().select_from(User).join(Address).filter(
Address.id > 14)
# GET parameters
params = request.args.to_dict()
# instantiating a DataTable for the query and table needed
rowTable = DataTables(params, query, columns)
# returns what is needed by DataTable
return jsonify(rowTable.output_result()) | def data() | Return server side data. | 5.333862 | 5.397232 | 0.988259 |
# copy for return
ret_regex = regex
# these characters are escaped (all except alternation | and escape \)
# see http://www.regular-expressions.info/refquick.html
escape_chars = '[^$.?*+(){}'
# remove any escape chars
ret_regex = ret_regex.replace('\\', '')
# escape any characters which are used by regex
# could probably concoct something incomprehensible using re.sub() but
# prefer to write clear code with this loop
# note expectation that no characters have already been escaped
for c in escape_chars:
ret_regex = ret_regex.replace(c, '\\' + c)
# remove any double alternations until these don't exist any more
while True:
old_regex = ret_regex
ret_regex = ret_regex.replace('||', '|')
if old_regex == ret_regex:
break
# if last char is alternation | remove it because this
# will cause operational error
# this can happen as user is typing in global search box
while len(ret_regex) >= 1 and ret_regex[-1] == '|':
ret_regex = ret_regex[:-1]
# and back to the caller
return ret_regex | def clean_regex(regex) | Escape any regex special characters other than alternation.
:param regex: regex from datatables interface
:type regex: str
:rtype: str with regex to use with database | 7.336586 | 7.435054 | 0.986756 |
output = {}
output['draw'] = str(int(self.params.get('draw', 1)))
output['recordsTotal'] = str(self.cardinality)
output['recordsFiltered'] = str(self.cardinality_filtered)
if self.error:
output['error'] = self.error
return output
output['data'] = self.results
for k, v in self.yadcf_params:
output[k] = v
return output | def output_result(self) | Output results in the format needed by DataTables. | 3.65409 | 2.999965 | 1.218044 |
query = self.query
# count before filtering
self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()
self._set_column_filter_expressions()
self._set_global_filter_expression()
self._set_sort_expressions()
self._set_yadcf_data(query)
# apply filters
query = query.filter(
*[e for e in self.filter_expressions if e is not None])
self.cardinality_filtered = query.add_columns(
self.columns[0].sqla_expr).count()
# apply sorts
query = query.order_by(
*[e for e in self.sort_expressions if e is not None])
# add paging options
length = int(self.params.get('length'))
if length >= 0:
query = query.limit(length)
elif length == -1:
pass
else:
raise (ValueError(
'Length should be a positive integer or -1 to disable'))
query = query.offset(int(self.params.get('start')))
# add columns to query
query = query.add_columns(*[c.sqla_expr for c in self.columns])
# fetch the result of the queries
column_names = [
col.mData if col.mData else str(i)
for i, col in enumerate(self.columns)
]
self.results = [{k: v
for k, v in zip(column_names, row)}
for row in query.all()] | def run(self) | Launch filtering, sorting and paging to output results. | 3.316536 | 3.218964 | 1.030312 |
# per columns filters:
for i in range(len(self.columns)):
filter_expr = None
value = self.params.get('columns[{:d}][search][value]'.format(i),
'')
if value:
search_func = SEARCH_METHODS[self.columns[i].search_method]
filter_expr = search_func(self.columns[i].sqla_expr, value)
self.filter_expressions.append(filter_expr) | def _set_column_filter_expressions(self) | Construct the query: filtering.
Add filtering when per column searching is used. | 4.327759 | 3.75835 | 1.151505 |
sort_expressions = []
i = 0
while self.params.get('order[{:d}][column]'.format(i), False):
column_nr = int(self.params.get('order[{:d}][column]'.format(i)))
column = self.columns[column_nr]
direction = self.params.get('order[{:d}][dir]'.format(i))
sort_expr = column.sqla_expr
if direction == 'asc':
sort_expr = sort_expr.asc()
elif direction == 'desc':
sort_expr = sort_expr.desc()
else:
raise ValueError(
'Invalid order direction: {}'.format(direction))
if column.nulls_order:
if column.nulls_order == 'nullsfirst':
sort_expr = sort_expr.nullsfirst()
elif column.nulls_order == 'nullslast':
sort_expr = sort_expr.nullslast()
else:
raise ValueError(
'Invalid order direction: {}'.format(direction))
sort_expressions.append(sort_expr)
i += 1
self.sort_expressions = sort_expressions | def _set_sort_expressions(self) | Construct the query: sorting.
Add sorting(ORDER BY) on the columns needed to be applied on. | 1.878985 | 1.827545 | 1.028147 |
split = len(combined_value) - len(combined_value.lstrip('<>='))
operator = combined_value[:split]
if operator == '':
operator = '='
try:
operator_func = search_operators[operator]
except KeyError:
raise ValueError(
'Numeric query should start with operator, choose from %s' %
', '.join(search_operators.keys()))
value = combined_value[split:].strip()
return operator_func, value | def parse_query_value(combined_value) | Parse value in form of '>value' to a lambda and a value. | 3.693767 | 3.420524 | 1.079883 |
try:
DBSession.query(User).first()
except DBAPIError:
return Response(
conn_err_msg,
content_type="text/plain",
status_int=500,
)
return {"project": "pyramid_tut"} | def home(request) | Try to connect to database, and list available examples. | 6.415204 | 5.866471 | 1.093537 |
columns = [
ColumnDT(User.id),
ColumnDT(User.name),
ColumnDT(Address.description),
ColumnDT(func.strftime("%d-%m-%Y", User.birthday)),
ColumnDT(User.age)
]
query = DBSession.query().select_from(User).join(Address).filter(
Address.id > 4)
rowTable = DataTables(request.GET, query, columns)
return rowTable.output_result() | def data(request) | Return server side data. | 3.707461 | 3.627701 | 1.021986 |
columns = [
ColumnDT(User.id, search_method="numeric"),
ColumnDT(User.name),
ColumnDT(Address.description),
ColumnDT(User.birthday, search_method="date"),
ColumnDT(User.age, search_method="numeric")
]
query = DBSession.query().select_from(User).join(Address).filter(
Address.id > 4)
rowTable = DataTables(request.GET, query, columns)
return rowTable.output_result() | def data_advanced(request) | Return server side data. | 4.147049 | 3.890235 | 1.066015 |
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include("pyramid_jinja2")
config.include("pyramid_debugtoolbar")
config.add_route("home", "/")
config.add_route("data", "/data")
config.add_route("data_advanced", "/data_advanced")
config.add_route("data_yadcf", "/data_yadcf")
config.add_route("dt_110x", "/dt_110x")
config.add_route("dt_110x_custom_column", "/dt_110x_custom_column")
config.add_route("dt_110x_basic_column_search",
"/dt_110x_basic_column_search")
config.add_route("dt_110x_advanced_column_search",
"/dt_110x_advanced_column_search")
config.add_route("dt_110x_yadcf", "/dt_110x_yadcf")
config.scan()
json_renderer = JSON()
json_renderer.add_adapter(date, date_adapter)
config.add_renderer("json_with_dates", json_renderer)
config.add_jinja2_renderer('.html')
return config.make_wsgi_app() | def main(global_config, **settings) | Return a Pyramid WSGI application. | 2.029521 | 1.967548 | 1.031498 |
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
for i in range(30):
with transaction.manager:
address = Address(description="Address#2" + str(i).rjust(2, "0"))
DBSession.add(address)
user = User(
name="User#1" + str(i).rjust(2, "0"),
birthday=date(1980 + i % 8, i % 12 + 1, i % 10 + 1))
user.address = address
DBSession.add(user) | def main(argv=sys.argv) | Populate database with 30 users. | 2.806978 | 2.495742 | 1.124707 |
date, time = t.split(' ')
month, day = date.split('-')
h, m, s = time.split(':')
s, ms = s.split('.')
return (month, day, h, m, s, ms) | def _parse_logline_timestamp(t) | Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond. | 2.741153 | 2.761997 | 0.992453 |
dt1 = _parse_logline_timestamp(t1)
dt2 = _parse_logline_timestamp(t2)
for u1, u2 in zip(dt1, dt2):
if u1 < u2:
return -1
elif u1 > u2:
return 1
return 0 | def logline_timestamp_comparator(t1, t2) | Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. | 2.036506 | 2.343245 | 0.869097 |
s, ms = divmod(epoch_time, 1000)
d = datetime.datetime.fromtimestamp(s, tz=time_zone)
return d.strftime('%m-%d %H:%M:%S.') + str(ms) | def epoch_to_log_line_timestamp(epoch_time, time_zone=None) | Converts an epoch timestamp in ms to log line timestamp format, which
is readible for humans.
Args:
epoch_time: integer, an epoch timestamp in ms.
time_zone: instance of tzinfo, time zone information.
Using pytz rather than python 3.2 time_zone implementation for
python 2 compatibility reasons.
Returns:
A string that is the corresponding timestamp in log line timestamp
format. | 2.916227 | 3.727211 | 0.782415 |
# Parse cli args.
parser = argparse.ArgumentParser(description='Mobly Suite Executable.')
parser.add_argument(
'-c',
'--config',
nargs=1,
type=str,
required=True,
metavar='<PATH>',
help='Path to the test configuration file.')
parser.add_argument(
'--tests',
'--test_case',
nargs='+',
type=str,
metavar='[ClassA[.test_a] ClassB[.test_b] ...]',
help='A list of test classes and optional tests to execute.')
if not argv:
argv = sys.argv[1:]
args = parser.parse_args(argv)
# Load test config file.
test_configs = config_parser.load_test_config_file(args.config[0])
# Check the classes that were passed in
for test_class in test_classes:
if not issubclass(test_class, base_test.BaseTestClass):
logging.error('Test class %s does not extend '
'mobly.base_test.BaseTestClass', test_class)
sys.exit(1)
# Find the full list of tests to execute
selected_tests = compute_selected_tests(test_classes, args.tests)
# Execute the suite
ok = True
for config in test_configs:
runner = test_runner.TestRunner(config.log_path, config.test_bed_name)
for (test_class, tests) in selected_tests.items():
runner.add_test_class(config, test_class, tests)
try:
runner.run()
ok = runner.results.is_all_pass and ok
except signals.TestAbortAll:
pass
except:
logging.exception('Exception when executing %s.',
config.test_bed_name)
ok = False
if not ok:
sys.exit(1) | def run_suite(test_classes, argv=None) | Executes multiple test classes as a suite.
This is the default entry point for running a test suite script file
directly.
Args:
test_classes: List of python classes containing Mobly tests.
argv: A list that is then parsed as cli args. If None, defaults to cli
input. | 3.059737 | 2.970462 | 1.030055 |
serials = android_device.list_adb_devices()
if not serials:
raise Error('No adb device found!')
# No serial provided, try to pick up the device automatically.
if not serial:
env_serial = os.environ.get('ANDROID_SERIAL', None)
if env_serial is not None:
serial = env_serial
elif len(serials) == 1:
serial = serials[0]
else:
raise Error(
'Expected one phone, but %d found. Use the -s flag or '
'specify ANDROID_SERIAL.' % len(serials))
if serial not in serials:
raise Error('Device "%s" is not found by adb.' % serial)
ads = android_device.get_instances([serial])
assert len(ads) == 1
self._ad = ads[0] | def load_device(self, serial=None) | Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one. | 3.447202 | 3.398839 | 1.014229 |
self._telnet_client.open(host, port)
config_str = self._telnet_client.cmd("MN?")
if config_str.startswith("MN="):
config_str = config_str[len("MN="):]
self.properties = dict(
zip(['model', 'max_freq', 'max_atten'], config_str.split("-", 2)))
self.max_atten = float(self.properties['max_atten']) | def open(self, host, port=23) | 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) | 4.446711 | 4.362826 | 1.019227 |
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
if value > self.max_atten:
raise ValueError("Attenuator value out of range!", self.max_atten,
value)
# The actual device uses one-based index for channel numbers.
self._telnet_client.cmd("CHAN:%s:SETATT:%s" % (idx + 1, value)) | def set_atten(self, idx, value) | Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that is the attenuation value to set.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
IndexError: The index of the attenuator is greater than the maximum
index of the underlying instrument.
ValueError: The requested set value is greater than the maximum
attenuation value. | 4.959717 | 3.946578 | 1.256713 |
if not self.is_open:
raise attenuator.Error(
"Connection to attenuator at %s is not open!" %
self._telnet_client.host)
if idx + 1 > self.path_count or idx < 0:
raise IndexError("Attenuator index out of range!", self.path_count,
idx)
atten_val_str = self._telnet_client.cmd("CHAN:%s:ATT?" % (idx + 1))
atten_val = float(atten_val_str)
return atten_val | def get_atten(self, idx=0) | This function returns the current attenuation from an attenuator at a
given index in the instrument.
Args:
idx: This zero-based index is the identifier for a particular
attenuator in an instrument.
Raises:
Error: The underlying telnet connection to the instrument is not
open.
Returns:
A float that is the current attenuation value. | 4.214586 | 3.842758 | 1.096761 |
# Check that sl4a is installed
out = self._adb.shell('pm list package')
if not utils.grep('com.googlecode.android_scripting', out):
raise jsonrpc_client_base.AppStartError(
self._ad, '%s is not installed on %s' % (_APP_NAME,
self._adb.serial))
self.disable_hidden_api_blacklist()
# sl4a has problems connecting after disconnection, so kill the apk and
# try connecting again.
try:
self.stop_app()
except Exception as e:
self.log.warning(e)
# Launch the app
self.device_port = _DEVICE_SIDE_PORT
self._adb.shell(_LAUNCH_CMD % self.device_port)
# Try to start the connection (not restore the connectivity).
# The function name restore_app_connection is used here is for the
# purpose of reusing the same code as it does when restoring the
# connection. And we do not want to come up with another function
# name to complicate the API. Change the name if necessary.
self.restore_app_connection() | def start_app_and_connect(self) | Overrides superclass. | 8.007187 | 7.752611 | 1.032837 |
self.host_port = port or utils.get_available_host_port()
self._retry_connect()
self.ed = self._start_event_client() | def restore_app_connection(self, port=None) | Restores the sl4a after device got disconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started. | 11.506973 | 9.191285 | 1.251944 |
try:
if self._conn:
# Be polite; let the dest know we're shutting down.
try:
self.closeSl4aSession()
except:
self.log.exception('Failed to gracefully shut down %s.',
self.app_name)
# Close the socket connection.
self.disconnect()
self.stop_event_dispatcher()
# Terminate the app
self._adb.shell('am force-stop com.googlecode.android_scripting')
finally:
# Always clean up the adb port
self.clear_host_port() | def stop_app(self) | Overrides superclass. | 8.099072 | 7.64725 | 1.059083 |
try:
self._start_app_and_connect()
except AppStartPreCheckError:
# Precheck errors don't need cleanup, directly raise.
raise
except Exception as e:
# Log the stacktrace of `e` as re-raising doesn't preserve trace.
self._ad.log.exception('Failed to start app and connect.')
# If errors happen, make sure we clean up before raising.
try:
self.stop_app()
except:
self._ad.log.exception(
'Failed to stop app after failure to start and connect.')
# Explicitly raise the original error from starting app.
raise e | def start_app_and_connect(self) | Starts snippet apk on the device and connects to it.
This wraps the main logic with safe handling
Raises:
AppStartPreCheckError, when pre-launch checks fail. | 6.440821 | 5.458293 | 1.180006 |
self._check_app_installed()
self.disable_hidden_api_blacklist()
persists_shell_cmd = self._get_persist_command()
# Use info here so people can follow along with the snippet startup
# process. Starting snippets can be slow, especially if there are
# multiple, and this avoids the perception that the framework is hanging
# for a long time doing nothing.
self.log.info('Launching snippet apk %s with protocol %d.%d',
self.package, _PROTOCOL_MAJOR_VERSION,
_PROTOCOL_MINOR_VERSION)
cmd = _LAUNCH_CMD % (persists_shell_cmd, self.package)
start_time = time.time()
self._proc = self._do_start_app(cmd)
# Check protocol version and get the device port
line = self._read_protocol_line()
match = re.match('^SNIPPET START, PROTOCOL ([0-9]+) ([0-9]+)$', line)
if not match or match.group(1) != '1':
raise ProtocolVersionError(self._ad, line)
line = self._read_protocol_line()
match = re.match('^SNIPPET SERVING, PORT ([0-9]+)$', line)
if not match:
raise ProtocolVersionError(self._ad, line)
self.device_port = int(match.group(1))
# Forward the device port to a new host port, and connect to that port
self.host_port = utils.get_available_host_port()
self._adb.forward(
['tcp:%d' % self.host_port,
'tcp:%d' % self.device_port])
self.connect()
# Yaaay! We're done!
self.log.debug('Snippet %s started after %.1fs on host port %s',
self.package, time.time() - start_time, self.host_port) | def _start_app_and_connect(self) | Starts snippet apk on the device and connects to it.
After prechecks, this launches the snippet apk with an adb cmd in a
standing subprocess, checks the cmd response from the apk for protocol
version, then sets up the socket connection over adb port-forwarding.
Args:
ProtocolVersionError, if protocol info or port info cannot be
retrieved from the snippet apk. | 4.978415 | 4.451138 | 1.118459 |
self.host_port = port or utils.get_available_host_port()
self._adb.forward(
['tcp:%d' % self.host_port,
'tcp:%d' % self.device_port])
try:
self.connect()
except:
# Log the original error and raise AppRestoreConnectionError.
self.log.exception('Failed to re-connect to app.')
raise jsonrpc_client_base.AppRestoreConnectionError(
self._ad,
('Failed to restore app connection for %s at host port %s, '
'device port %s') % (self.package, self.host_port,
self.device_port))
# Because the previous connection was lost, update self._proc
self._proc = None
self._restore_event_client() | def restore_app_connection(self, port=None) | Restores the app after device got reconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected port.
Args:
port: If given, this is the host port from which to connect to remote
device port. If not provided, find a new available port as host
port.
Raises:
AppRestoreConnectionError: When the app was not able to be started. | 5.646517 | 4.721631 | 1.195883 |
event_client = SnippetClient(package=self.package, ad=self._ad)
event_client.host_port = self.host_port
event_client.device_port = self.device_port
event_client.connect(self.uid,
jsonrpc_client_base.JsonRpcCommand.CONTINUE)
return event_client | def _start_event_client(self) | Overrides superclass. | 7.473403 | 6.785019 | 1.101456 |
if not self._event_client:
self._event_client = self._start_event_client()
return
self._event_client.host_port = self.host_port
self._event_client.device_port = self.device_port
self._event_client.connect() | def _restore_event_client(self) | Restores previously created event client. | 2.901075 | 2.677553 | 1.08348 |
while True:
line = self._proc.stdout.readline().decode('utf-8')
if not line:
raise jsonrpc_client_base.AppStartError(
self._ad, 'Unexpected EOF waiting for app to start')
# readline() uses an empty string to mark EOF, and a single newline
# to mark regular empty lines in the output. Don't move the strip()
# call above the truthiness check, or this method will start
# considering any blank output line to be EOF.
line = line.strip()
if (line.startswith('INSTRUMENTATION_RESULT:')
or line.startswith('SNIPPET ')):
self.log.debug(
'Accepted line from instrumentation output: "%s"', line)
return line
self.log.debug('Discarded line from instrumentation output: "%s"',
line) | def _read_protocol_line(self) | Reads the next line of instrumentation output relevant to snippets.
This method will skip over lines that don't start with 'SNIPPET' or
'INSTRUMENTATION_RESULT'.
Returns:
(str) Next line of snippet-related instrumentation output, stripped.
Raises:
jsonrpc_client_base.AppStartError: If EOF is reached without any
protocol lines being read. | 7.398441 | 5.174368 | 1.429825 |
for command in [_SETSID_COMMAND, _NOHUP_COMMAND]:
try:
if command in self._adb.shell(['which',
command]).decode('utf-8'):
return command
except adb.AdbError:
continue
self.log.warning(
'No %s and %s commands available to launch instrument '
'persistently, tests that depend on UiAutomator and '
'at the same time performs USB disconnection may fail',
_SETSID_COMMAND, _NOHUP_COMMAND)
return '' | def _get_persist_command(self) | Check availability and return path of command if available. | 8.952238 | 8.358624 | 1.071018 |
help_text = self._rpc('help')
if print_output:
print(help_text)
else:
return help_text | def help(self, print_output=True) | Calls the help RPC, which returns the list of RPC calls available.
This RPC should normally be used in an interactive console environment
where the output should be printed instead of returned. Otherwise,
newlines will be escaped, which will make the output difficult to read.
Args:
print_output: A bool for whether the output should be printed.
Returns:
A str containing the help output otherwise None if print_output
wasn't set. | 4.03453 | 4.240993 | 0.951317 |
for service in self._service_objects.values():
if service.is_alive:
return True
return False | def is_any_alive(self) | True if any service is alive; False otherwise. | 5.027531 | 3.570893 | 1.40792 |
if not inspect.isclass(service_class):
raise Error(self._device, '"%s" is not a class!' % service_class)
if not issubclass(service_class, base_service.BaseService):
raise Error(
self._device,
'Class %s is not a subclass of BaseService!' % service_class)
if alias in self._service_objects:
raise Error(
self._device,
'A service is already registered with alias "%s".' % alias)
service_obj = service_class(self._device, configs)
if start_service:
service_obj.start()
self._service_objects[alias] = service_obj | def register(self, alias, service_class, configs=None, start_service=True) | Registers a service.
This will create a service instance, starts the service, and adds the
instance to the mananger.
Args:
alias: string, the alias for this instance.
service_class: class, the service class to instantiate.
configs: (optional) config object to pass to the service class's
constructor.
start_service: bool, whether to start the service instance or not.
Default is True. | 2.300782 | 2.407302 | 0.955751 |
if alias not in self._service_objects:
raise Error(self._device,
'No service is registered with alias "%s".' % alias)
service_obj = self._service_objects.pop(alias)
if service_obj.is_alive:
with expects.expect_no_raises(
'Failed to stop service instance "%s".' % alias):
service_obj.stop() | def unregister(self, alias) | Unregisters a service instance.
Stops a service and removes it from the manager.
Args:
alias: string, the alias of the service instance to unregister. | 5.432776 | 4.957721 | 1.095821 |
aliases = list(self._service_objects.keys())
for alias in aliases:
self.unregister(alias) | def unregister_all(self) | Safely unregisters all active instances.
Errors occurred here will be recorded but not raised. | 6.466816 | 6.434902 | 1.00496 |
for alias, service in self._service_objects.items():
if not service.is_alive:
with expects.expect_no_raises(
'Failed to start service "%s".' % alias):
service.start() | def start_all(self) | Starts all inactive service instances. | 8.563468 | 7.384438 | 1.159664 |
for alias, service in self._service_objects.items():
if service.is_alive:
with expects.expect_no_raises(
'Failed to stop service "%s".' % alias):
service.stop() | def stop_all(self) | Stops all active service instances. | 8.769685 | 7.767682 | 1.128996 |
for alias, service in self._service_objects.items():
with expects.expect_no_raises(
'Failed to pause service "%s".' % alias):
service.pause() | def pause_all(self) | Pauses all service instances. | 11.374512 | 9.707488 | 1.171726 |
for alias, service in self._service_objects.items():
with expects.expect_no_raises(
'Failed to pause service "%s".' % alias):
service.resume() | def resume_all(self) | Resumes all service instances. | 12.816421 | 10.891575 | 1.176728 |
if not configs:
raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)
elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:
ads = get_all_instances()
elif not isinstance(configs, list):
raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)
elif isinstance(configs[0], dict):
# Configs is a list of dicts.
ads = get_instances_with_configs(configs)
elif isinstance(configs[0], basestring):
# Configs is a list of strings representing serials.
ads = get_instances(configs)
else:
raise Error('No valid config found in: %s' % configs)
valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id()
for ad in ads:
if ad.serial not in valid_ad_identifiers:
raise DeviceError(ad, 'Android device is specified in config but'
' is not attached.')
_start_services_on_ads(ads)
return ads | def create(configs) | Creates AndroidDevice controller objects.
Args:
configs: A list of dicts, each representing a configuration for an
Android device.
Returns:
A list of AndroidDevice objects. | 4.39198 | 4.176708 | 1.051541 |
for ad in ads:
try:
ad.services.stop_all()
except:
ad.log.exception('Failed to clean up properly.') | def destroy(ads) | Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects. | 7.940836 | 7.808907 | 1.016895 |
running_ads = []
for ad in ads:
running_ads.append(ad)
start_logcat = not getattr(ad, KEY_SKIP_LOGCAT,
DEFAULT_VALUE_SKIP_LOGCAT)
try:
ad.services.register(
SERVICE_NAME_LOGCAT, logcat.Logcat, start_service=start_logcat)
except Exception:
is_required = getattr(ad, KEY_DEVICE_REQUIRED,
DEFAULT_VALUE_DEVICE_REQUIRED)
if is_required:
ad.log.exception('Failed to start some services, abort!')
destroy(running_ads)
raise
else:
ad.log.exception('Skipping this optional device because some '
'services failed to start.') | def _start_services_on_ads(ads) | 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. | 5.311062 | 5.108327 | 1.039687 |
clean_lines = new_str(device_list_str, 'utf-8').strip().split('\n')
results = []
for line in clean_lines:
tokens = line.strip().split('\t')
if len(tokens) == 2 and tokens[1] == key:
results.append(tokens[0])
return results | def parse_device_list(device_list_str, key) | 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. | 3.105596 | 3.309586 | 0.938364 |
out = adb.AdbProxy().devices(['-l'])
clean_lines = new_str(out, 'utf-8').strip().split('\n')
results = []
for line in clean_lines:
tokens = line.strip().split()
if len(tokens) > 2 and tokens[1] == 'device':
results.append(tokens[2])
return results | def list_adb_devices_by_usb_id() | 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. | 4.052591 | 4.527668 | 0.895073 |
results = []
for s in serials:
results.append(AndroidDevice(s))
return results | def get_instances(serials) | Create AndroidDevice instances from a list of serials.
Args:
serials: A list of android device serials.
Returns:
A list of AndroidDevice objects. | 5.495355 | 4.062025 | 1.352861 |
results = []
for c in configs:
try:
serial = c.pop('serial')
except KeyError:
raise Error(
'Required value "serial" is missing in AndroidDevice config %s.'
% c)
is_required = c.get(KEY_DEVICE_REQUIRED, True)
try:
ad = AndroidDevice(serial)
ad.load_config(c)
except Exception:
if is_required:
raise
ad.log.exception('Skipping this optional device due to error.')
continue
results.append(ad)
return results | def get_instances_with_configs(configs) | 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. | 5.144459 | 4.412959 | 1.165762 |
if include_fastboot:
serial_list = list_adb_devices() + list_fastboot_devices()
return get_instances(serial_list)
return get_instances(list_adb_devices()) | def get_all_instances(include_fastboot=False) | 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. | 3.562071 | 4.497367 | 0.792035 |
results = []
for ad in ads:
if func(ad):
results.append(ad)
return results | def filter_devices(ads, func) | 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. | 2.504884 | 3.493865 | 0.716938 |
def _get_device_filter(ad):
for k, v in kwargs.items():
if not hasattr(ad, k):
return False
elif getattr(ad, k) != v:
return False
return True
filtered = filter_devices(ads, _get_device_filter)
if not filtered:
raise Error(
'Could not find a target device that matches condition: %s.' %
kwargs)
else:
return filtered | def get_devices(ads, **kwargs) | 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. | 3.505359 | 3.101001 | 1.130396 |
filtered = get_devices(ads, **kwargs)
if len(filtered) == 1:
return filtered[0]
else:
serials = [ad.serial for ad in filtered]
raise Error('More than one device matched: %s' % serials) | def get_device(ads, **kwargs) | 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. | 3.5121 | 2.837395 | 1.23779 |
begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time))
def take_br(test_name, begin_time, ad, destination):
ad.take_bug_report(test_name, begin_time, destination=destination)
args = [(test_name, begin_time, ad, destination) for ad in ads]
utils.concurrent_exec(take_br, args) | def take_bug_reports(ads, test_name, begin_time, destination=None) | Takes bug reports on a list of android devices.
If you want to take a bug report, call this function with a list of
android_device objects in on_fail. But reports will be taken on all the
devices in the list concurrently. Bug report takes a relative long
time to take, so use this cautiously.
Args:
ads: A list of AndroidDevice instances.
test_name: Name of the test method that triggered this bug report.
begin_time: timestamp taken when the test started, can be either
string or int.
destination: string, path to the directory where the bugreport
should be saved. | 4.330187 | 5.026691 | 0.861439 |
if self._serial is None:
return None
normalized_serial = self._serial.replace(' ', '_')
normalized_serial = normalized_serial.replace(':', '-')
return normalized_serial | def _normalized_serial(self) | 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. | 3.270099 | 2.817008 | 1.160841 |
info = {
'serial': self.serial,
'model': self.model,
'build_info': self.build_info,
'user_added_info': self._user_added_device_info
}
return info | def device_info(self) | 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`. | 4.053335 | 2.711123 | 1.495076 |
self.log.info('Logging debug tag set to "%s"', tag)
self._debug_tag = tag
self.log.extra['tag'] = tag | def debug_tag(self, tag) | 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.' | 6.167715 | 8.863706 | 0.695839 |
if self.has_active_service:
raise DeviceError(
self,
'Cannot change `log_path` when there is service running.')
old_path = self._log_path
if new_path == old_path:
return
if os.listdir(new_path):
raise DeviceError(
self, 'Logs already exist at %s, cannot override.' % new_path)
if os.path.exists(old_path):
# Remove new path so copytree doesn't complain.
shutil.rmtree(new_path, ignore_errors=True)
shutil.copytree(old_path, new_path)
shutil.rmtree(old_path, ignore_errors=True)
self._log_path = new_path | def log_path(self, new_path) | Setter for `log_path`, use with caution. | 3.160825 | 3.02019 | 1.046565 |
new_serial = str(new_serial)
if self.has_active_service:
raise DeviceError(
self,
'Cannot change device serial number when there is service running.'
)
if self._debug_tag == self.serial:
self._debug_tag = new_serial
self._serial = new_serial
self.adb.serial = new_serial
self.fastboot.serial = new_serial | def update_serial(self, new_serial) | 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. | 5.068046 | 4.435522 | 1.142604 |
self.services.stop_all()
try:
yield
finally:
self.wait_for_boot_completion()
if self.is_rootable:
self.root_adb()
self.services.start_all() | def handle_reboot(self) | 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(). | 6.696104 | 5.226621 | 1.281154 |
if self.is_bootloader:
self.log.error('Device is in fastboot mode, could not get build '
'info.')
return
info = {}
info['build_id'] = self.adb.getprop('ro.build.id')
info['build_type'] = self.adb.getprop('ro.build.type')
return info | def build_info(self) | Get the build info of this Android device, including build id and
build type.
This is not available if the device is in bootloader mode.
Returns:
A dict with the build info of this Android device, or None if the
device is in bootloader mode. | 4.002467 | 2.780307 | 1.439577 |
try:
return '0' == self.adb.shell('id -u').decode('utf-8').strip()
except adb.AdbError:
# Wait a bit and retry to work around adb flakiness for this cmd.
time.sleep(0.2)
return '0' == self.adb.shell('id -u').decode('utf-8').strip() | def is_adb_root(self) | True if adb is running as root for this device. | 3.977231 | 3.700779 | 1.074701 |
# If device is in bootloader mode, get mode name from fastboot.
if self.is_bootloader:
out = self.fastboot.getvar('product').strip()
# 'out' is never empty because of the 'total time' message fastboot
# writes to stderr.
lines = out.decode('utf-8').split('\n', 1)
if lines:
tokens = lines[0].split(' ')
if len(tokens) > 1:
return tokens[1].lower()
return None
model = self.adb.getprop('ro.build.product').lower()
if model == 'sprout':
return model
return self.adb.getprop('ro.product.name').lower() | def model(self) | The Android code name for the device. | 6.134098 | 5.316525 | 1.15378 |
for k, v in config.items():
if hasattr(self, k):
raise DeviceError(
self,
('Attribute %s already exists with value %s, cannot set '
'again.') % (k, getattr(self, k)))
setattr(self, k, v) | def load_config(self, config) | Add attributes to the AndroidDevice object based on config.
Args:
config: A dictionary representing the configs.
Raises:
Error: The config is trying to overwrite an existing attribute. | 4.220035 | 3.495297 | 1.207346 |
self.adb.root()
self.adb.wait_for_device(
timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND) | def root_adb(self) | Change adb to root mode for this device if allowed.
If executed on a production build, adb will not be switched to root
mode per security restrictions. | 8.552289 | 9.313499 | 0.918268 |
# Should not load snippet with an existing attribute.
if hasattr(self, name):
raise SnippetError(
self,
'Attribute "%s" already exists, please use a different name.' %
name)
self.services.snippets.add_snippet_client(name, package) | def load_snippet(self, name, package) | Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
SnippetError: Illegal load operations are attempted. | 7.269284 | 6.919002 | 1.050626 |
new_br = True
try:
stdout = self.adb.shell('bugreportz -v').decode('utf-8')
# This check is necessary for builds before N, where adb shell's ret
# code and stderr are not propagated properly.
if 'not found' in stdout:
new_br = False
except adb.AdbError:
new_br = False
if destination:
br_path = utils.abs_path(destination)
else:
br_path = os.path.join(self.log_path, 'BugReports')
utils.create_dir(br_path)
base_name = ',%s,%s.txt' % (begin_time, self._normalized_serial)
if new_br:
base_name = base_name.replace('.txt', '.zip')
test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
out_name = test_name[:test_name_len] + base_name
full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
# in case device restarted, wait for adb interface to return
self.wait_for_boot_completion()
self.log.info('Taking bugreport for %s.', test_name)
if new_br:
out = self.adb.shell('bugreportz', timeout=timeout).decode('utf-8')
if not out.startswith('OK'):
raise DeviceError(self, 'Failed to take bugreport: %s' % out)
br_out_path = out.split(':')[1].strip()
self.adb.pull([br_out_path, full_out_path])
else:
# shell=True as this command redirects the stdout to a local file
# using shell redirection.
self.adb.bugreport(
' > "%s"' % full_out_path, shell=True, timeout=timeout)
self.log.info('Bugreport for %s taken at %s.', test_name,
full_out_path) | def take_bug_report(self,
test_name,
begin_time,
timeout=300,
destination=None) | Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test method that triggered this bug report.
begin_time: Timestamp of when the test started.
timeout: float, the number of seconds to wait for bugreport to
complete, default is 5min.
destination: string, path to the directory where the bugreport
should be saved. | 3.99321 | 4.05871 | 0.983862 |
out = self.adb.shell('iperf3 -c %s %s' % (server_host, extra_args))
clean_out = new_str(out, 'utf-8').strip().split('\n')
if 'error' in clean_out[0].lower():
return False, clean_out
return True, clean_out | def run_iperf_client(self, server_host, extra_args='') | Start iperf client on the device.
Return status as true if iperf client start successfully.
And data flow information as results.
Args:
server_host: Address of the iperf server.
extra_args: A string representing extra arguments for iperf client,
e.g. '-i 1 -t 30'.
Returns:
status: true if iperf client start successfully.
results: results have data flow information | 3.743979 | 4.059371 | 0.922305 |
timeout_start = time.time()
self.adb.wait_for_device(timeout=timeout)
while time.time() < timeout_start + timeout:
try:
if self.is_boot_completed():
return
except adb.AdbError:
# adb shell calls may fail during certain period of booting
# process, which is normal. Ignoring these errors.
pass
time.sleep(5)
raise DeviceError(self, 'Booting process timed out') | def wait_for_boot_completion(
self, timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND) | Waits for Android framework to broadcast ACTION_BOOT_COMPLETED.
This function times out after 15 minutes.
Args:
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect. | 4.780767 | 5.395153 | 0.886123 |
completed = self.adb.getprop('sys.boot_completed')
if completed == '1':
self.log.debug('Device boot completed.')
return True
return False | def is_boot_completed(self) | Checks if device boot is completed by verifying system property. | 4.524682 | 3.443026 | 1.314158 |
serials = list_adb_devices()
if self.serial in serials:
self.log.debug('Is now adb detectable.')
return True
return False | def is_adb_detectable(self) | Checks if USB is on and device is ready by verifying adb devices. | 6.664535 | 6.019492 | 1.107159 |
if self.is_bootloader:
self.fastboot.reboot()
return
with self.handle_reboot():
self.adb.reboot() | def reboot(self) | Reboots the device.
Generally one should use this method to reboot the device instead of
directly calling `adb.reboot`. Because this method gracefully handles
the teardown and restoration of running services.
This method is blocking and only returns when the reboot has completed
and the services restored.
Raises:
Error: Waiting for completion timed out. | 7.92893 | 7.874571 | 1.006903 |
try:
asserts.assert_true(condition, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected a `True` value, got `False`.')
recorder.add_error(e) | def expect_true(condition, msg, extras=None) | 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. | 6.667933 | 8.098448 | 0.823359 |
try:
asserts.assert_false(condition, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected a `False` value, got `True`.')
recorder.add_error(e) | def expect_false(condition, msg, extras=None) | 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. | 7.022824 | 8.490446 | 0.827144 |
try:
asserts.assert_equal(first, second, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected %s equals to %s, but they are not.', first,
second)
recorder.add_error(e) | def expect_equal(first, second, msg=None, extras=None) | 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. | 6.314343 | 7.096951 | 0.889726 |
try:
yield
except Exception as e:
e_record = records.ExceptionRecord(e)
if extras:
e_record.extras = extras
msg = message or 'Got an unexpected exception'
details = '%s: %s' % (msg, e_record.details)
logging.exception(details)
e_record.details = details
recorder.add_error(e_record) | def expect_no_raises(message=None, extras=None) | 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. | 4.041636 | 3.956264 | 1.021579 |
self._record = None
self._count = 0
self._record = record | def reset_internal_states(self, record=None) | Resets the internal state of the recorder.
Args:
record: records.TestResultRecord, the test record for a test. | 8.040537 | 8.454962 | 0.950984 |
self._count += 1
self._record.add_error('expect@%s+%s' % (time.time(), self._count),
error) | def add_error(self, error) | 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. | 12.042881 | 7.629616 | 1.578439 |
self._ad.services.register('sl4a', sl4a_service.Sl4aService)
console_env['s'] = self._ad.services.sl4a
console_env['sl4a'] = self._ad.sl4a
console_env['ed'] = self._ad.ed | def _start_services(self, console_env) | Overrides superclass. | 5.004422 | 4.650253 | 1.076161 |
# Logpersist is only allowed on rootable devices because of excessive
# reads/writes for persisting logs.
if not self._ad.is_rootable:
return
logpersist_warning = ('%s encountered an error enabling persistent'
' logs, logs may not get saved.')
# Android L and older versions do not have logpersist installed,
# so check that the logpersist scripts exists before trying to use
# them.
if not self._ad.adb.has_shell_command('logpersist.start'):
logging.warning(logpersist_warning, self)
return
try:
# Disable adb log spam filter for rootable devices. Have to stop
# and clear settings first because 'start' doesn't support --clear
# option before Android N.
self._ad.adb.shell('logpersist.stop --clear')
self._ad.adb.shell('logpersist.start')
except adb.AdbError:
logging.warning(logpersist_warning, self) | def _enable_logpersist(self) | Attempts to enable logpersist daemon to persist logs. | 7.044123 | 6.83932 | 1.029945 |
try:
self._ad.adb.logcat('-c')
except adb.AdbError as e:
# On Android O, the clear command fails due to a known bug.
# Catching this so we don't crash from this Android issue.
if b'failed to clear' in e.stderr:
self._ad.log.warning(
'Encountered known Android error to clear logcat.')
else:
raise | def clear_adb_log(self) | Clears cached adb content. | 7.512345 | 7.653373 | 0.981573 |
if not self.adb_logcat_file_path:
raise Error(
self._ad,
'Attempting to cat adb log when none has been collected.')
end_time = mobly_logger.get_log_line_timestamp()
self._ad.log.debug('Extracting adb log from logcat.')
adb_excerpt_path = os.path.join(self._ad.log_path, 'AdbLogExcerpts')
utils.create_dir(adb_excerpt_path)
f_name = os.path.basename(self.adb_logcat_file_path)
out_name = f_name.replace('adblog,', '').replace('.txt', '')
out_name = ',%s,%s.txt' % (begin_time, out_name)
out_name = out_name.replace(':', '-')
tag_len = utils.MAX_FILENAME_LEN - len(out_name)
tag = tag[:tag_len]
out_name = tag + out_name
full_adblog_path = os.path.join(adb_excerpt_path, out_name)
with io.open(full_adblog_path, 'w', encoding='utf-8') as out:
in_file = self.adb_logcat_file_path
with io.open(
in_file, 'r', encoding='utf-8', errors='replace') as f:
in_range = False
while True:
line = None
try:
line = f.readline()
if not line:
break
except:
continue
line_time = line[:mobly_logger.log_line_timestamp_len]
if not mobly_logger.is_valid_logline_timestamp(line_time):
continue
if self._is_timestamp_in_range(line_time, begin_time,
end_time):
in_range = True
if not line.endswith('\n'):
line += '\n'
out.write(line)
else:
if in_range:
break | def cat_adb_log(self, tag, begin_time) | Takes an excerpt of the adb logcat log from a certain time point to
current time.
Args:
tag: An identifier of the time period, usualy the name of a test.
begin_time: Logline format timestamp of the beginning of the time
period. | 3.067307 | 3.035454 | 1.010494 |
self._assert_not_running()
if self._configs.clear_log:
self.clear_adb_log()
self._start() | def start(self) | Starts a standing adb logcat collection.
The collection runs in a separate subprocess and saves logs in a file. | 12.376641 | 9.062899 | 1.365638 |
self._enable_logpersist()
logcat_file_path = self._configs.output_file_path
if not logcat_file_path:
f_name = 'adblog,%s,%s.txt' % (self._ad.model,
self._ad._normalized_serial)
logcat_file_path = os.path.join(self._ad.log_path, f_name)
utils.create_dir(os.path.dirname(logcat_file_path))
cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % (
adb.ADB, self._ad.serial, self._configs.logcat_params,
logcat_file_path)
process = utils.start_standing_subprocess(cmd, shell=True)
self._adb_logcat_process = process
self.adb_logcat_file_path = logcat_file_path | def _start(self) | The actual logic of starting logcat. | 4.390608 | 3.948525 | 1.111962 |
if not self._adb_logcat_process:
return
try:
utils.stop_standing_subprocess(self._adb_logcat_process)
except:
self._ad.log.exception('Failed to stop adb logcat.')
self._adb_logcat_process = None | def stop(self) | Stops the adb logcat service. | 4.746122 | 3.477832 | 1.364679 |
self._counter = self._id_counter()
self._conn = socket.create_connection(('localhost', self.host_port),
_SOCKET_CONNECTION_TIMEOUT)
self._conn.settimeout(_SOCKET_READ_TIMEOUT)
self._client = self._conn.makefile(mode='brw')
resp = self._cmd(cmd, uid)
if not resp:
raise ProtocolError(self._ad,
ProtocolError.NO_RESPONSE_FROM_HANDSHAKE)
result = json.loads(str(resp, encoding='utf8'))
if result['status']:
self.uid = result['uid']
else:
self.uid = UNKNOWN_UID | def connect(self, uid=UNKNOWN_UID, cmd=JsonRpcCommand.INIT) | Opens a connection to a JSON RPC server.
Opens a connection to a remote client. The connection attempt will time
out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each
subsequent operation over this socket will time out after
_SOCKET_READ_TIMEOUT seconds as well.
Args:
uid: int, The uid of the session to join, or UNKNOWN_UID to start a
new session.
cmd: JsonRpcCommand, The command to use for creating the connection.
Raises:
IOError: Raised when the socket times out from io error
socket.timeout: Raised when the socket waits to long for connection.
ProtocolError: Raised when there is an error in the protocol. | 4.481399 | 4.122044 | 1.087179 |
if self.host_port:
self._adb.forward(['--remove', 'tcp:%d' % self.host_port])
self.host_port = None | def clear_host_port(self) | Stops the adb port forwarding of the host port used by this client. | 5.028917 | 3.319669 | 1.514885 |
try:
self._client.write(msg.encode("utf8") + b'\n')
self._client.flush()
self.log.debug('Snippet sent %s.', msg)
except socket.error as e:
raise Error(
self._ad,
'Encountered socket error "%s" sending RPC message "%s"' %
(e, msg)) | def _client_send(self, msg) | Sends an Rpc message through the connection.
Args:
msg: string, the message to send.
Raises:
Error: a socket error occurred during the send. | 5.535596 | 5.216382 | 1.061195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.