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() ...
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._...
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_p...
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...
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 ...
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 ...
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 ...
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) ...
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, AttributeErro...
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.exis...
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: ...
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")) ...
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( Ad...
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 character...
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['...
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) ...
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].searc...
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)) ...
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, c...
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 = ...
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).fil...
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("d...
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 ...
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.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_argume...
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 ...
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....
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, ...
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 i...
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, ...
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 i...
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, ...
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 t...
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.', ...
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....
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...
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: Protoc...
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. ...
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...
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_clien...
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 ...
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_clien...
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....
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: ...
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!' % ...
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 t...
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( ...
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...
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)...
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 l...
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: ...
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...
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 Erro...
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...
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...
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, ar...
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:...
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 DeviceE...
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 DeviceErro...
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 ...
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 ...
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 sa...
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') ...
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'...
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, packa...
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 whic...
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 = Fals...
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...
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...
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...
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 ...
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...
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 t...
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....
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.det...
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 ...
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 s...
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...
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...
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.lo...
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') r...
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. ...
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 "%...
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