signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@contextlib.contextmanager<EOL><INDENT>def handle_usb_disconnect(self):<DEDENT>
self.services.pause_all()<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>self.services.resume_all()<EOL><DEDENT>
Properly manage the service life cycle when USB is disconnected. The device can temporarily lose adb connection due to user-triggered USB disconnection, e.g. the following cases can be handled by this method: * Power measurement: Using Monsoon device to measure battery consumption would potentially disconnect USB. * Unplug USB so device loses connection. * ADB connection over WiFi and WiFi got disconnected. * Any other type of USB disconnection, as long as snippet session can be kept alive while USB disconnected (reboot caused USB disconnection is not one of these cases because snippet session cannot survive reboot. Use handle_reboot() instead). Use this function to make sure the services started by Mobly are properly reconnected afterwards. Just like the usage of self.handle_reboot(), this method does not automatically detect if the disconnection is because of a reboot or USB disconnect. Users of this function should make sure the right handle_* function is used to handle the correct type of disconnection. This method also reconnects snippet event client. Therefore, the callback objects created (by calling Async RPC methods) before disconnection would still be valid and can be used to retrieve RPC execution result after device got reconnected. Example Usage: .. code-block:: python with ad.handle_usb_disconnect(): try: # User action that triggers USB disconnect, could throw # exceptions. do_something() finally: # User action that triggers USB reconnect action_that_reconnects_usb() # Make sure device is reconnected before returning from this # context ad.adb.wait_for_device(timeout=SOME_TIMEOUT)
f7496:c0:m16
@property<EOL><INDENT>def build_info(self):<DEDENT>
if self.is_bootloader:<EOL><INDENT>self.log.error('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>info = {}<EOL>info['<STR_LIT>'] = self.adb.getprop('<STR_LIT>')<EOL>info['<STR_LIT>'] = self.adb.getprop('<STR_LIT>')<EOL>return info<EOL>
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.
f7496:c0:m17
@property<EOL><INDENT>def is_bootloader(self):<DEDENT>
return self.serial in list_fastboot_devices()<EOL>
True if the device is in bootloader mode.
f7496:c0:m18
@property<EOL><INDENT>def is_adb_root(self):<DEDENT>
try:<EOL><INDENT>return '<STR_LIT:0>' == self.adb.shell('<STR_LIT>').decode('<STR_LIT:utf-8>').strip()<EOL><DEDENT>except adb.AdbError:<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL>return '<STR_LIT:0>' == self.adb.shell('<STR_LIT>').decode('<STR_LIT:utf-8>').strip()<EOL><DEDENT>
True if adb is running as root for this device.
f7496:c0:m19
@property<EOL><INDENT>def model(self):<DEDENT>
<EOL>if self.is_bootloader:<EOL><INDENT>out = self.fastboot.getvar('<STR_LIT>').strip()<EOL>lines = out.decode('<STR_LIT:utf-8>').split('<STR_LIT:\n>', <NUM_LIT:1>)<EOL>if lines:<EOL><INDENT>tokens = lines[<NUM_LIT:0>].split('<STR_LIT:U+0020>')<EOL>if len(tokens) > <NUM_LIT:1>:<EOL><INDENT>return tokens[<NUM_LIT:1>].lower()<EOL><DEDENT><DEDENT>return None<EOL><DEDENT>model = self.adb.getprop('<STR_LIT>').lower()<EOL>if model == '<STR_LIT>':<EOL><INDENT>return model<EOL><DEDENT>return self.adb.getprop('<STR_LIT>').lower()<EOL>
The Android code name for the device.
f7496:c0:m21
def load_config(self, config):
for k, v in config.items():<EOL><INDENT>if hasattr(self, k):<EOL><INDENT>raise DeviceError(<EOL>self,<EOL>('<STR_LIT>'<EOL>'<STR_LIT>') % (k, getattr(self, k)))<EOL><DEDENT>setattr(self, k, v)<EOL><DEDENT>
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.
f7496:c0:m22
def root_adb(self):
self.adb.root()<EOL>self.adb.wait_for_device(<EOL>timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND)<EOL>
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.
f7496:c0:m23
def load_snippet(self, name, package):
<EOL>if hasattr(self, name):<EOL><INDENT>raise SnippetError(<EOL>self,<EOL>'<STR_LIT>' %<EOL>name)<EOL><DEDENT>self.services.snippets.add_snippet_client(name, package)<EOL>
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.
f7496:c0:m24
def unload_snippet(self, name):
self.services.snippets.remove_snippet_client(name)<EOL>
Stops a snippet apk. Args: name: The attribute name the snippet server is attached with. Raises: SnippetError: The given snippet name is not registered.
f7496:c0:m25
def run_iperf_client(self, server_host, extra_args='<STR_LIT>'):
out = self.adb.shell('<STR_LIT>' % (server_host, extra_args))<EOL>clean_out = new_str(out, '<STR_LIT:utf-8>').strip().split('<STR_LIT:\n>')<EOL>if '<STR_LIT:error>' in clean_out[<NUM_LIT:0>].lower():<EOL><INDENT>return False, clean_out<EOL><DEDENT>return True, clean_out<EOL>
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
f7496:c0:m27
def wait_for_boot_completion(<EOL>self, timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND):
timeout_start = time.time()<EOL>self.adb.wait_for_device(timeout=timeout)<EOL>while time.time() < timeout_start + timeout:<EOL><INDENT>try:<EOL><INDENT>if self.is_boot_completed():<EOL><INDENT>return<EOL><DEDENT><DEDENT>except adb.AdbError:<EOL><INDENT>pass<EOL><DEDENT>time.sleep(<NUM_LIT:5>)<EOL><DEDENT>raise DeviceError(self, '<STR_LIT>')<EOL>
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.
f7496:c0:m28
def is_boot_completed(self):
completed = self.adb.getprop('<STR_LIT>')<EOL>if completed == '<STR_LIT:1>':<EOL><INDENT>self.log.debug('<STR_LIT>')<EOL>return True<EOL><DEDENT>return False<EOL>
Checks if device boot is completed by verifying system property.
f7496:c0:m29
def is_adb_detectable(self):
serials = list_adb_devices()<EOL>if self.serial in serials:<EOL><INDENT>self.log.debug('<STR_LIT>')<EOL>return True<EOL><DEDENT>return False<EOL>
Checks if USB is on and device is ready by verifying adb devices.
f7496:c0:m30
def reboot(self):
if self.is_bootloader:<EOL><INDENT>self.fastboot.reboot()<EOL>return<EOL><DEDENT>with self.handle_reboot():<EOL><INDENT>self.adb.reboot()<EOL><DEDENT>
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.
f7496:c0:m31
def __getattr__(self, name):
client = self.services.snippets.get_snippet_client(name)<EOL>if client:<EOL><INDENT>return client<EOL><DEDENT>return self.__getattribute__(name)<EOL>
Tries to return a snippet client registered with `name`. This is for backward compatibility of direct accessing snippet clients.
f7496:c0:m32
def __init__(self, app_name, ad):
self.host_port = None<EOL>self.device_port = None<EOL>self.app_name = app_name<EOL>self._ad = ad<EOL>self.log = self._ad.log<EOL>self.uid = None<EOL>self._client = None <EOL>self._conn = None<EOL>self._counter = None<EOL>self._lock = threading.Lock()<EOL>self._event_client = None<EOL>
Args: app_name: (str) The user-visible name of the app being communicated with. ad: (AndroidDevice) The device object associated with a client.
f7497:c6:m0
def start_app_and_connect(self):
raise NotImplementedError()<EOL>
Starts the server app on the android device and connects to it. After this, the self.host_port and self.device_port attributes must be set. Must be implemented by subclasses. Raises: AppStartError: When the app was not able to be started.
f7497:c6:m2
def stop_app(self):
raise NotImplementedError()<EOL>
Kills any running instance of the app. Must be implemented by subclasses.
f7497:c6:m3
def restore_app_connection(self, port=None):
raise NotImplementedError()<EOL>
Reconnects to the app after device USB was disconnected. Instead of creating new instance of the client: - Uses the given port (or finds a new available host_port if none is given). - Tries to connect to remote server with selected port. Must be implemented by subclasses. 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 reconnected.
f7497:c6:m4
def _start_event_client(self):
raise NotImplementedError()<EOL>
Starts a separate JsonRpc client to the same session for propagating events. This is an optional function that should only implement if the client utilizes the snippet event mechanism. Returns: A JsonRpc Client object that connects to the same session as the one on which this function is called.
f7497:c6:m5
def connect(self, uid=UNKNOWN_UID, cmd=JsonRpcCommand.INIT):
self._counter = self._id_counter()<EOL>self._conn = socket.create_connection(('<STR_LIT:localhost>', self.host_port),<EOL>_SOCKET_CONNECTION_TIMEOUT)<EOL>self._conn.settimeout(_SOCKET_READ_TIMEOUT)<EOL>self._client = self._conn.makefile(mode='<STR_LIT>')<EOL>resp = self._cmd(cmd, uid)<EOL>if not resp:<EOL><INDENT>raise ProtocolError(self._ad,<EOL>ProtocolError.NO_RESPONSE_FROM_HANDSHAKE)<EOL><DEDENT>result = json.loads(str(resp, encoding='<STR_LIT:utf8>'))<EOL>if result['<STR_LIT:status>']:<EOL><INDENT>self.uid = result['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>self.uid = UNKNOWN_UID<EOL><DEDENT>
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.
f7497:c6:m6
def disconnect(self):
if self._conn:<EOL><INDENT>self._conn.close()<EOL>self._conn = None<EOL><DEDENT>
Close the connection to the remote client.
f7497:c6:m7
def clear_host_port(self):
if self.host_port:<EOL><INDENT>self._adb.forward(['<STR_LIT>', '<STR_LIT>' % self.host_port])<EOL>self.host_port = None<EOL><DEDENT>
Stops the adb port forwarding of the host port used by this client.
f7497:c6:m8
def _client_send(self, msg):
try:<EOL><INDENT>self._client.write(msg.encode("<STR_LIT:utf8>") + b'<STR_LIT:\n>')<EOL>self._client.flush()<EOL>self.log.debug('<STR_LIT>', msg)<EOL><DEDENT>except socket.error as e:<EOL><INDENT>raise Error(<EOL>self._ad,<EOL>'<STR_LIT>' %<EOL>(e, msg))<EOL><DEDENT>
Sends an Rpc message through the connection. Args: msg: string, the message to send. Raises: Error: a socket error occurred during the send.
f7497:c6:m9
def _client_receive(self):
try:<EOL><INDENT>response = self._client.readline()<EOL>self.log.debug('<STR_LIT>', response)<EOL>return response<EOL><DEDENT>except socket.error as e:<EOL><INDENT>raise Error(<EOL>self._ad,<EOL>'<STR_LIT>' % e)<EOL><DEDENT>
Receives the server's response of an Rpc message. Returns: Raw byte string of the response. Raises: Error: a socket error occurred during the read.
f7497:c6:m10
def _cmd(self, command, uid=None):
if not uid:<EOL><INDENT>uid = self.uid<EOL><DEDENT>self._client_send(json.dumps({'<STR_LIT>': command, '<STR_LIT>': uid}))<EOL>return self._client_receive()<EOL>
Send a command to the server. Args: command: str, The name of the command to execute. uid: int, the uid of the session to send the command to. Returns: The line that was written back.
f7497:c6:m11
def _rpc(self, method, *args):
with self._lock:<EOL><INDENT>apiid = next(self._counter)<EOL>data = {'<STR_LIT:id>': apiid, '<STR_LIT>': method, '<STR_LIT>': args}<EOL>request = json.dumps(data)<EOL>self._client_send(request)<EOL>response = self._client_receive()<EOL><DEDENT>if not response:<EOL><INDENT>raise ProtocolError(self._ad,<EOL>ProtocolError.NO_RESPONSE_FROM_SERVER)<EOL><DEDENT>result = json.loads(str(response, encoding='<STR_LIT:utf8>'))<EOL>if result['<STR_LIT:error>']:<EOL><INDENT>raise ApiError(self._ad, result['<STR_LIT:error>'])<EOL><DEDENT>if result['<STR_LIT:id>'] != apiid:<EOL><INDENT>raise ProtocolError(self._ad, ProtocolError.MISMATCHED_API_ID)<EOL><DEDENT>if result.get('<STR_LIT>') is not None:<EOL><INDENT>if self._event_client is None:<EOL><INDENT>self._event_client = self._start_event_client()<EOL><DEDENT>return callback_handler.CallbackHandler(<EOL>callback_id=result['<STR_LIT>'],<EOL>event_client=self._event_client,<EOL>ret_value=result['<STR_LIT:result>'],<EOL>method_name=method,<EOL>ad=self._ad)<EOL><DEDENT>return result['<STR_LIT:result>']<EOL>
Sends an rpc to the app. Args: method: str, The name of the method to execute. args: any, The args of the method. Returns: The result of the rpc. Raises: ProtocolError: Something went wrong with the protocol. ApiError: The rpc went through, however executed with errors.
f7497:c6:m12
def disable_hidden_api_blacklist(self):
version_codename = self._ad.adb.getprop('<STR_LIT>')<EOL>sdk_version = int(self._ad.adb.getprop('<STR_LIT>'))<EOL>if self._ad.is_rootable and (sdk_version >= <NUM_LIT><EOL>or version_codename == '<STR_LIT:P>'):<EOL><INDENT>self._ad.adb.shell(<EOL>'<STR_LIT>')<EOL><DEDENT>
If necessary and possible, disables hidden api blacklist.
f7497:c6:m13
def __getattr__(self, name):
def rpc_call(*args):<EOL><INDENT>return self._rpc(name, *args)<EOL><DEDENT>return rpc_call<EOL>
Wrapper for python magic to turn method calls into RPC calls.
f7497:c6:m14
def has_service_by_name(self, name):
return name in self._service_objects<EOL>
Checks if the manager has a service registered with a specific name. Args: name: string, the name to look for. Returns: True if a service is registered with the specified name, False otherwise.
f7499:c1:m1
@property<EOL><INDENT>def is_any_alive(self):<DEDENT>
for service in self._service_objects.values():<EOL><INDENT>if service.is_alive:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
True if any service is alive; False otherwise.
f7499:c1:m2
def register(self, alias, service_class, configs=None, start_service=True):
if not inspect.isclass(service_class):<EOL><INDENT>raise Error(self._device, '<STR_LIT>' % service_class)<EOL><DEDENT>if not issubclass(service_class, base_service.BaseService):<EOL><INDENT>raise Error(<EOL>self._device,<EOL>'<STR_LIT>' % service_class)<EOL><DEDENT>if alias in self._service_objects:<EOL><INDENT>raise Error(<EOL>self._device,<EOL>'<STR_LIT>' % alias)<EOL><DEDENT>service_obj = service_class(self._device, configs)<EOL>if start_service:<EOL><INDENT>service_obj.start()<EOL><DEDENT>self._service_objects[alias] = service_obj<EOL>
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.
f7499:c1:m3
def unregister(self, alias):
if alias not in self._service_objects:<EOL><INDENT>raise Error(self._device,<EOL>'<STR_LIT>' % alias)<EOL><DEDENT>service_obj = self._service_objects.pop(alias)<EOL>if service_obj.is_alive:<EOL><INDENT>with expects.expect_no_raises(<EOL>'<STR_LIT>' % alias):<EOL><INDENT>service_obj.stop()<EOL><DEDENT><DEDENT>
Unregisters a service instance. Stops a service and removes it from the manager. Args: alias: string, the alias of the service instance to unregister.
f7499:c1:m4
def unregister_all(self):
aliases = list(self._service_objects.keys())<EOL>for alias in aliases:<EOL><INDENT>self.unregister(alias)<EOL><DEDENT>
Safely unregisters all active instances. Errors occurred here will be recorded but not raised.
f7499:c1:m5
def start_all(self):
for alias, service in self._service_objects.items():<EOL><INDENT>if not service.is_alive:<EOL><INDENT>with expects.expect_no_raises(<EOL>'<STR_LIT>' % alias):<EOL><INDENT>service.start()<EOL><DEDENT><DEDENT><DEDENT>
Starts all inactive service instances.
f7499:c1:m6
def stop_all(self):
for alias, service in self._service_objects.items():<EOL><INDENT>if service.is_alive:<EOL><INDENT>with expects.expect_no_raises(<EOL>'<STR_LIT>' % alias):<EOL><INDENT>service.stop()<EOL><DEDENT><DEDENT><DEDENT>
Stops all active service instances.
f7499:c1:m7
def pause_all(self):
for alias, service in self._service_objects.items():<EOL><INDENT>with expects.expect_no_raises(<EOL>'<STR_LIT>' % alias):<EOL><INDENT>service.pause()<EOL><DEDENT><DEDENT>
Pauses all service instances.
f7499:c1:m8
def resume_all(self):
for alias, service in self._service_objects.items():<EOL><INDENT>with expects.expect_no_raises(<EOL>'<STR_LIT>' % alias):<EOL><INDENT>service.resume()<EOL><DEDENT><DEDENT>
Resumes all service instances.
f7499:c1:m9
def __getattr__(self, name):
if self.has_service_by_name(name):<EOL><INDENT>return self._service_objects[name]<EOL><DEDENT>return self.__getattribute__(name)<EOL>
Syntactic sugar to enable direct access of service objects by alias. Args: name: string, the alias a service object was registered under.
f7499:c1:m10
def poll_events(self):
while self.started:<EOL><INDENT>event_obj = None<EOL>event_name = None<EOL>try:<EOL><INDENT>event_obj = self._sl4a.eventWait(<NUM_LIT>)<EOL><DEDENT>except:<EOL><INDENT>if self.started:<EOL><INDENT>print("<STR_LIT>")<EOL>print(traceback.format_exc())<EOL>raise<EOL><DEDENT><DEDENT>if not event_obj:<EOL><INDENT>continue<EOL><DEDENT>elif '<STR_LIT:name>' not in event_obj:<EOL><INDENT>print("<STR_LIT>".format(event_obj))<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>event_name = event_obj['<STR_LIT:name>']<EOL><DEDENT>if event_name in self.handlers:<EOL><INDENT>self.handle_subscribed_event(event_obj, event_name)<EOL><DEDENT>if event_name == "<STR_LIT>":<EOL><INDENT>self._sl4a.closeSl4aSession()<EOL>break<EOL><DEDENT>else:<EOL><INDENT>self.lock.acquire()<EOL>if event_name in self.event_dict: <EOL><INDENT>self.event_dict[event_name].put(event_obj)<EOL><DEDENT>else:<EOL><INDENT>q = queue.Queue()<EOL>q.put(event_obj)<EOL>self.event_dict[event_name] = q<EOL><DEDENT>self.lock.release()<EOL><DEDENT><DEDENT>
Continuously polls all types of events from sl4a. Events are sorted by name and store in separate queues. If there are registered handlers, the handlers will be called with corresponding event immediately upon event discovery, and the event won't be stored. If exceptions occur, stop the dispatcher and return
f7500:c3:m1
def register_handler(self, handler, event_name, args):
if self.started:<EOL><INDENT>raise IllegalStateError(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL><DEDENT>self.lock.acquire()<EOL>try:<EOL><INDENT>if event_name in self.handlers:<EOL><INDENT>raise DuplicateError('<STR_LIT>'.format(<EOL>event_name))<EOL><DEDENT>self.handlers[event_name] = (handler, args)<EOL><DEDENT>finally:<EOL><INDENT>self.lock.release()<EOL><DEDENT>
Registers an event handler. One type of event can only have one event handler associated with it. Args: handler: The event handler function to be registered. event_name: Name of the event the handler is for. args: User arguments to be passed to the handler when it's called. Raises: IllegalStateError: Raised if attempts to register a handler after the dispatcher starts running. DuplicateError: Raised if attempts to register more than one handler for one type of event.
f7500:c3:m2
def start(self):
if not self.started:<EOL><INDENT>self.started = True<EOL>self.executor = ThreadPoolExecutor(max_workers=<NUM_LIT:32>)<EOL>self.poller = self.executor.submit(self.poll_events)<EOL><DEDENT>else:<EOL><INDENT>raise IllegalStateError("<STR_LIT>")<EOL><DEDENT>
Starts the event dispatcher. Initiates executor and start polling events. Raises: IllegalStateError: Can't start a dispatcher again when it's already running.
f7500:c3:m3
def clean_up(self):
if not self.started:<EOL><INDENT>return<EOL><DEDENT>self.started = False<EOL>self.clear_all_events()<EOL>self._sl4a.disconnect()<EOL>self.poller.set_result("<STR_LIT>")<EOL>self.executor.shutdown(wait=False)<EOL>
Clean up and release resources after the event dispatcher polling loop has been broken. The following things happen: 1. Clear all events and flags. 2. Close the sl4a client the event_dispatcher object holds. 3. Shut down executor without waiting.
f7500:c3:m4
def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT):
if not self.started:<EOL><INDENT>raise IllegalStateError(<EOL>"<STR_LIT>")<EOL><DEDENT>e_queue = self.get_event_q(event_name)<EOL>if not e_queue:<EOL><INDENT>raise TypeError("<STR_LIT>".format(<EOL>event_name))<EOL><DEDENT>try:<EOL><INDENT>if timeout:<EOL><INDENT>return e_queue.get(True, timeout)<EOL><DEDENT>elif timeout == <NUM_LIT:0>:<EOL><INDENT>return e_queue.get(False)<EOL><DEDENT>else:<EOL><INDENT>return e_queue.get(True)<EOL><DEDENT><DEDENT>except queue.Empty:<EOL><INDENT>raise queue.Empty('<STR_LIT>'.format(<EOL>timeout, event_name))<EOL><DEDENT>
Pop an event from its queue. Return and remove the oldest entry of an event. Block until an event of specified name is available or times out if timeout is set. Args: event_name: Name of the event to be popped. timeout: Number of seconds to wait when event is not present. Never times out if None. Returns: The oldest entry of the specified event. None if timed out. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling.
f7500:c3:m5
def wait_for_event(self,<EOL>event_name,<EOL>predicate,<EOL>timeout=DEFAULT_TIMEOUT,<EOL>*args,<EOL>**kwargs):
deadline = time.time() + timeout<EOL>while True:<EOL><INDENT>event = None<EOL>try:<EOL><INDENT>event = self.pop_event(event_name, <NUM_LIT:1>)<EOL><DEDENT>except queue.Empty:<EOL><INDENT>pass<EOL><DEDENT>if event and predicate(event, *args, **kwargs):<EOL><INDENT>return event<EOL><DEDENT>if time.time() > deadline:<EOL><INDENT>raise queue.Empty(<EOL>'<STR_LIT>'.format(<EOL>timeout, event_name))<EOL><DEDENT><DEDENT>
Wait for an event that satisfies a predicate to appear. Continuously pop events of a particular name and check against the predicate until an event that satisfies the predicate is popped or timed out. Note this will remove all the events of the same name that do not satisfy the predicate in the process. Args: event_name: Name of the event to be popped. predicate: A function that takes an event and returns True if the predicate is satisfied, False otherwise. timeout: Number of seconds to wait. *args: Optional positional args passed to predicate(). **kwargs: Optional keyword args passed to predicate(). Returns: The event that satisfies the predicate. Raises: queue.Empty: Raised if no event that satisfies the predicate was found before time out.
f7500:c3:m6
def pop_events(self, regex_pattern, timeout):
if not self.started:<EOL><INDENT>raise IllegalStateError(<EOL>"<STR_LIT>")<EOL><DEDENT>deadline = time.time() + timeout<EOL>while True:<EOL><INDENT>results = self._match_and_pop(regex_pattern)<EOL>if len(results) != <NUM_LIT:0> or time.time() > deadline:<EOL><INDENT>break<EOL><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>if len(results) == <NUM_LIT:0>:<EOL><INDENT>raise queue.Empty('<STR_LIT>'.format(<EOL>timeout, regex_pattern))<EOL><DEDENT>return sorted(results, key=lambda event: event['<STR_LIT:time>'])<EOL>
Pop events whose names match a regex pattern. If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout. Results are sorted by timestamp in ascending order. Args: regex_pattern: The regular expression pattern that an event name should match in order to be popped. timeout: Number of seconds to wait for events in case no event matching the condition exits when the function is called. Returns: Events whose names match a regex pattern. Empty if none exist and the wait timed out. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling. queue.Empty: Raised if no event was found before time out.
f7500:c3:m7
def _match_and_pop(self, regex_pattern):
results = []<EOL>self.lock.acquire()<EOL>for name in self.event_dict.keys():<EOL><INDENT>if re.match(regex_pattern, name):<EOL><INDENT>q = self.event_dict[name]<EOL>if q:<EOL><INDENT>try:<EOL><INDENT>results.append(q.get(False))<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.lock.release()<EOL>return results<EOL>
Pop one event from each of the event queues whose names match (in a sense of regular expression) regex_pattern.
f7500:c3:m8
def get_event_q(self, event_name):
self.lock.acquire()<EOL>if not event_name in self.event_dict or self.event_dict[<EOL>event_name] is None:<EOL><INDENT>self.event_dict[event_name] = queue.Queue()<EOL><DEDENT>self.lock.release()<EOL>event_queue = self.event_dict[event_name]<EOL>return event_queue<EOL>
Obtain the queue storing events of the specified name. If no event of this name has been polled, wait for one to. Returns: A queue storing all the events of the specified name. None if timed out. Raises: queue.Empty: Raised if the queue does not exist and timeout has passed.
f7500:c3:m9
def handle_subscribed_event(self, event_obj, event_name):
handler, args = self.handlers[event_name]<EOL>self.executor.submit(handler, event_obj, *args)<EOL>
Execute the registered handler of an event. Retrieve the handler and its arguments, and execute the handler in a new thread. Args: event_obj: Json object of the event. event_name: Name of the event to call handler for.
f7500:c3:m10
def _handle(self, event_handler, event_name, user_args, event_timeout,<EOL>cond, cond_timeout):
if cond:<EOL><INDENT>cond.wait(cond_timeout)<EOL><DEDENT>event = self.pop_event(event_name, event_timeout)<EOL>return event_handler(event, *user_args)<EOL>
Pop an event of specified type and calls its handler on it. If condition is not None, block until condition is met or timeout.
f7500:c3:m11
def handle_event(self,<EOL>event_handler,<EOL>event_name,<EOL>user_args,<EOL>event_timeout=None,<EOL>cond=None,<EOL>cond_timeout=None):
worker = self.executor.submit(self._handle, event_handler, event_name,<EOL>user_args, event_timeout, cond,<EOL>cond_timeout)<EOL>return worker<EOL>
Handle events that don't have registered handlers In a new thread, poll one event of specified type from its queue and execute its handler. If no such event exists, the thread waits until one appears. Args: event_handler: Handler for the event, which should take at least one argument - the event json object. event_name: Name of the event to be handled. user_args: User arguments for the handler; to be passed in after the event json. event_timeout: Number of seconds to wait for the event to come. cond: A condition to wait on before executing the handler. Should be a threading.Event object. cond_timeout: Number of seconds to wait before the condition times out. Never times out if None. Returns: A concurrent.Future object associated with the handler. If blocking call worker.result() is triggered, the handler needs to return something to unblock.
f7500:c3:m12
def pop_all(self, event_name):
if not self.started:<EOL><INDENT>raise IllegalStateError(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL><DEDENT>results = []<EOL>try:<EOL><INDENT>self.lock.acquire()<EOL>while True:<EOL><INDENT>e = self.event_dict[event_name].get(block=False)<EOL>results.append(e)<EOL><DEDENT><DEDENT>except (queue.Empty, KeyError):<EOL><INDENT>return results<EOL><DEDENT>finally:<EOL><INDENT>self.lock.release()<EOL><DEDENT>
Return and remove all stored events of a specified name. Pops all events from their queue. May miss the latest ones. If no event is available, return immediately. Args: event_name: Name of the events to be popped. Returns: List of the desired events. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling.
f7500:c3:m13
def clear_events(self, event_name):
self.lock.acquire()<EOL>try:<EOL><INDENT>q = self.get_event_q(event_name)<EOL>q.queue.clear()<EOL><DEDENT>except queue.Empty:<EOL><INDENT>return<EOL><DEDENT>finally:<EOL><INDENT>self.lock.release()<EOL><DEDENT>
Clear all events of a particular name. Args: event_name: Name of the events to be popped.
f7500:c3:m14
def clear_all_events(self):
self.lock.acquire()<EOL>self.event_dict.clear()<EOL>self.lock.release()<EOL>
Clear all event queues and their cached events.
f7500:c3:m15
def from_dict(event_dict):
return SnippetEvent(<EOL>callback_id=event_dict['<STR_LIT>'],<EOL>name=event_dict['<STR_LIT:name>'],<EOL>creation_time=event_dict['<STR_LIT:time>'],<EOL>data=event_dict['<STR_LIT:data>'])<EOL>
Create a SnippetEvent object from a dictionary. Args: event_dict: a dictionary representing an event. Returns: A SnippetEvent object.
f7501:m0
def waitAndGet(self, event_name, timeout=DEFAULT_TIMEOUT):
if timeout:<EOL><INDENT>if timeout > MAX_TIMEOUT:<EOL><INDENT>raise Error(<EOL>self._ad,<EOL>'<STR_LIT>' %<EOL>(timeout, MAX_TIMEOUT))<EOL><DEDENT><DEDENT>timeout_ms = int(timeout * <NUM_LIT:1000>)<EOL>try:<EOL><INDENT>raw_event = self._event_client.eventWaitAndGet(<EOL>self._id, event_name, timeout_ms)<EOL><DEDENT>except Exception as e:<EOL><INDENT>if '<STR_LIT>' in str(e):<EOL><INDENT>raise TimeoutError(<EOL>self._ad,<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (timeout, event_name, self._method_name,<EOL>self._id))<EOL><DEDENT>raise<EOL><DEDENT>return snippet_event.from_dict(raw_event)<EOL>
Blocks until an event of the specified name has been received and return the event, or timeout. Args: event_name: string, name of the event to get. timeout: float, the number of seconds to wait before giving up. Returns: SnippetEvent, the oldest entry of the specified event. Raises: Error: If the specified timeout is longer than the max timeout supported. TimeoutError: The expected event does not occur within time limit.
f7502:c2:m2
def waitForEvent(self, event_name, predicate, timeout=DEFAULT_TIMEOUT):
deadline = time.time() + timeout<EOL>while time.time() <= deadline:<EOL><INDENT>rpc_timeout = deadline - time.time()<EOL>if rpc_timeout < <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>rpc_timeout = min(rpc_timeout, MAX_TIMEOUT)<EOL>try:<EOL><INDENT>event = self.waitAndGet(event_name, rpc_timeout)<EOL><DEDENT>except TimeoutError:<EOL><INDENT>break<EOL><DEDENT>if predicate(event):<EOL><INDENT>return event<EOL><DEDENT><DEDENT>raise TimeoutError(<EOL>self._ad,<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (timeout, event_name, predicate.__name__))<EOL>
Wait for an event of a specific name that satisfies the predicate. This call will block until the expected event has been received or time out. The predicate function defines the condition the event is expected to satisfy. It takes an event and returns True if the condition is satisfied, False otherwise. Note all events of the same name that are received but don't satisfy the predicate will be discarded and not be available for further consumption. Args: event_name: string, the name of the event to wait for. predicate: function, a function that takes an event (dictionary) and returns a bool. timeout: float, default is 120s. Returns: dictionary, the event that satisfies the predicate if received. Raises: TimeoutError: raised if no event that satisfies the predicate is received after timeout seconds.
f7502:c2:m3
def getAll(self, event_name):
raw_events = self._event_client.eventGetAll(self._id, event_name)<EOL>return [snippet_event.from_dict(msg) for msg in raw_events]<EOL>
Gets all the events of a certain name that have been received so far. This is a non-blocking call. Args: callback_id: The id of the callback. event_name: string, the name of the event to get. Returns: A list of SnippetEvent, each representing an event from the Java side.
f7502:c2:m4
def __init__(self, ad):
super(Sl4aClient, self).__init__(app_name=_APP_NAME, ad=ad)<EOL>self._ad = ad<EOL>self.ed = None<EOL>self._adb = ad.adb<EOL>
Initializes an Sl4aClient. Args: ad: AndroidDevice object.
f7504:c0:m0
def start_app_and_connect(self):
<EOL>out = self._adb.shell('<STR_LIT>')<EOL>if not utils.grep('<STR_LIT>', out):<EOL><INDENT>raise jsonrpc_client_base.AppStartError(<EOL>self._ad, '<STR_LIT>' % (_APP_NAME,<EOL>self._adb.serial))<EOL><DEDENT>self.disable_hidden_api_blacklist()<EOL>try:<EOL><INDENT>self.stop_app()<EOL><DEDENT>except Exception as e:<EOL><INDENT>self.log.warning(e)<EOL><DEDENT>self.device_port = _DEVICE_SIDE_PORT<EOL>self._adb.shell(_LAUNCH_CMD % self.device_port)<EOL>self.restore_app_connection()<EOL>
Overrides superclass.
f7504:c0:m1
def restore_app_connection(self, port=None):
self.host_port = port or utils.get_available_host_port()<EOL>self._retry_connect()<EOL>self.ed = self._start_event_client()<EOL>
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.
f7504:c0:m2
def stop_app(self):
try:<EOL><INDENT>if self._conn:<EOL><INDENT>try:<EOL><INDENT>self.closeSl4aSession()<EOL><DEDENT>except:<EOL><INDENT>self.log.exception('<STR_LIT>',<EOL>self.app_name)<EOL><DEDENT>self.disconnect()<EOL>self.stop_event_dispatcher()<EOL><DEDENT>self._adb.shell('<STR_LIT>')<EOL><DEDENT>finally:<EOL><INDENT>self.clear_host_port()<EOL><DEDENT>
Overrides superclass.
f7504:c0:m3
def exe_cmd(*cmds):
cmd = '<STR_LIT:U+0020>'.join(cmds)<EOL>proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>(out, err) = proc.communicate()<EOL>if not err:<EOL><INDENT>return out<EOL><DEDENT>return err<EOL>
Executes commands in a new shell. Directing stderr to PIPE. This is fastboot's own exe_cmd because of its peculiar way of writing non-error info to stderr. Args: cmds: A sequence of commands and arguments. Returns: The output of the command run. Raises: Exception: An error occurred during the command execution.
f7505:m0
@property<EOL><INDENT>def is_alive(self):<DEDENT>
return any(<EOL>[client.is_alive for client in self._snippet_clients.values()])<EOL>
True if any client is running, False otherwise.
f7506:c1:m1
def get_snippet_client(self, name):
if name in self._snippet_clients:<EOL><INDENT>return self._snippet_clients[name]<EOL><DEDENT>
Gets the snippet client managed under a given name. Args: name: string, the name of the snippet client under management. Returns: SnippetClient.
f7506:c1:m2
def add_snippet_client(self, name, package):
<EOL>if name in self._snippet_clients:<EOL><INDENT>raise Error(<EOL>self,<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(name, self._snippet_clients[name].client.package))<EOL><DEDENT>for snippet_name, client in self._snippet_clients.items():<EOL><INDENT>if package == client.package:<EOL><INDENT>raise Error(<EOL>self,<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (package, snippet_name))<EOL><DEDENT><DEDENT>client = snippet_client.SnippetClient(package=package, ad=self._device)<EOL>client.start_app_and_connect()<EOL>self._snippet_clients[name] = client<EOL>
Adds a snippet client to the management. 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: Error, if a duplicated name or package is passed in.
f7506:c1:m3
def remove_snippet_client(self, name):
if name not in self._snippet_clients:<EOL><INDENT>raise Error(self._device, MISSING_SNIPPET_CLIENT_MSG % name)<EOL><DEDENT>client = self._snippet_clients.pop(name)<EOL>client.stop_app()<EOL>
Removes a snippet client from management. Args: name: string, the name of the snippet client to remove. Raises: Error: if no snippet client is managed under the specified name.
f7506:c1:m4
def start(self):
for client in self._snippet_clients.values():<EOL><INDENT>if not client.is_alive:<EOL><INDENT>self._device.log.debug('<STR_LIT>',<EOL>client.package)<EOL>client.start_app_and_connect()<EOL><DEDENT>else:<EOL><INDENT>self._device.log.debug(<EOL>'<STR_LIT>',<EOL>client.package)<EOL><DEDENT><DEDENT>
Starts all the snippet clients under management.
f7506:c1:m5
def stop(self):
for client in self._snippet_clients.values():<EOL><INDENT>if client.is_alive:<EOL><INDENT>self._device.log.debug('<STR_LIT>',<EOL>client.package)<EOL>client.stop_app()<EOL><DEDENT>else:<EOL><INDENT>self._device.log.debug(<EOL>'<STR_LIT>',<EOL>client.package)<EOL><DEDENT><DEDENT>
Stops all the snippet clients under management.
f7506:c1:m6
def pause(self):
for client in self._snippet_clients.values():<EOL><INDENT>self._device.log.debug(<EOL>'<STR_LIT>',<EOL>client.host_port, client.package)<EOL>client.clear_host_port()<EOL><DEDENT>
Pauses all the snippet clients under management. This clears the host port of a client because a new port will be allocated in `resume`.
f7506:c1:m7
def resume(self):
for client in self._snippet_clients.values():<EOL><INDENT>if client.is_alive and client.host_port is None:<EOL><INDENT>self._device.log.debug('<STR_LIT>',<EOL>client.package)<EOL>client.restore_app_connection()<EOL><DEDENT>else:<EOL><INDENT>self._device.log.debug('<STR_LIT>',<EOL>client.package)<EOL><DEDENT><DEDENT>
Resumes all paused snippet clients.
f7506:c1:m8
def __getattr__(self, name):
if self._sl4a_client:<EOL><INDENT>return getattr(self._sl4a_client, name)<EOL><DEDENT>return self.__getattribute__(name)<EOL>
Forwards the getattr calls to the client itself.
f7507:c0:m6
def __init__(self, device, configs=None):
self._device = device<EOL>self._configs = configs<EOL>
Constructor of the class. The constructor is the only place to pass in a config. If you need to change the config later, you should unregister the service instance from `ServiceManager` and register again with the new config. Args: device: the device object this service is associated with. config: optional configuration defined by the author of the service class.
f7508:c0:m0
@property<EOL><INDENT>def is_alive(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
True if the service is active; False otherwise.
f7508:c0:m1
def start(self):
raise NotImplementedError('<STR_LIT>')<EOL>
Starts the service.
f7508:c0:m2
def stop(self):
raise NotImplementedError('<STR_LIT>')<EOL>
Stops the service and cleans up all resources. This method should handle any error and not throw.
f7508:c0:m3
def pause(self):
self.stop()<EOL>
Pauses a service temporarily. For when the Python service object needs to temporarily lose connection to the device without shutting down the service running on the actual device. This is relevant when a service needs to maintain a constant connection to the device and the connection is lost if USB connection to the device is disrupted. E.g. a services that utilizes a socket connection over adb port forwarding would need to implement this for the situation where the USB connection to the device will be temporarily cut, but the device is not rebooted. For more context, see: `mobly.controllers.android_device.AndroidDevice.handle_usb_disconnect` If not implemented, we assume the service is not sensitive to device disconnect, and `stop` will be called by default.
f7508:c0:m4
def resume(self):
self.start()<EOL>
Resumes a paused service. Same context as the `pause` method. This should resume the service after the connection to the device has been re-established. If not implemented, we assume the service is not sensitive to device disconnect, and `start` will be called by default.
f7508:c0:m5
def _enable_logpersist(self):
<EOL>if not self._ad.is_rootable:<EOL><INDENT>return<EOL><DEDENT>logpersist_warning = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>if not self._ad.adb.has_shell_command('<STR_LIT>'):<EOL><INDENT>logging.warning(logpersist_warning, self)<EOL>return<EOL><DEDENT>try:<EOL><INDENT>self._ad.adb.shell('<STR_LIT>')<EOL>self._ad.adb.shell('<STR_LIT>')<EOL><DEDENT>except adb.AdbError:<EOL><INDENT>logging.warning(logpersist_warning, self)<EOL><DEDENT>
Attempts to enable logpersist daemon to persist logs.
f7510:c2:m1
def clear_adb_log(self):
try:<EOL><INDENT>self._ad.adb.logcat('<STR_LIT:-c>')<EOL><DEDENT>except adb.AdbError as e:<EOL><INDENT>if b'<STR_LIT>' in e.stderr:<EOL><INDENT>self._ad.log.warning(<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>
Clears cached adb content.
f7510:c2:m5
def cat_adb_log(self, tag, begin_time):
if not self.adb_logcat_file_path:<EOL><INDENT>raise Error(<EOL>self._ad,<EOL>'<STR_LIT>')<EOL><DEDENT>end_time = mobly_logger.get_log_line_timestamp()<EOL>self._ad.log.debug('<STR_LIT>')<EOL>adb_excerpt_path = os.path.join(self._ad.log_path, '<STR_LIT>')<EOL>utils.create_dir(adb_excerpt_path)<EOL>f_name = os.path.basename(self.adb_logcat_file_path)<EOL>out_name = f_name.replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>out_name = '<STR_LIT>' % (begin_time, out_name)<EOL>out_name = out_name.replace('<STR_LIT::>', '<STR_LIT:->')<EOL>tag_len = utils.MAX_FILENAME_LEN - len(out_name)<EOL>tag = tag[:tag_len]<EOL>out_name = tag + out_name<EOL>full_adblog_path = os.path.join(adb_excerpt_path, out_name)<EOL>with io.open(full_adblog_path, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as out:<EOL><INDENT>in_file = self.adb_logcat_file_path<EOL>with io.open(<EOL>in_file, '<STR_LIT:r>', encoding='<STR_LIT:utf-8>', errors='<STR_LIT:replace>') as f:<EOL><INDENT>in_range = False<EOL>while True:<EOL><INDENT>line = None<EOL>try:<EOL><INDENT>line = f.readline()<EOL>if not line:<EOL><INDENT>break<EOL><DEDENT><DEDENT>except:<EOL><INDENT>continue<EOL><DEDENT>line_time = line[:mobly_logger.log_line_timestamp_len]<EOL>if not mobly_logger.is_valid_logline_timestamp(line_time):<EOL><INDENT>continue<EOL><DEDENT>if self._is_timestamp_in_range(line_time, begin_time,<EOL>end_time):<EOL><INDENT>in_range = True<EOL>if not line.endswith('<STR_LIT:\n>'):<EOL><INDENT>line += '<STR_LIT:\n>'<EOL><DEDENT>out.write(line)<EOL><DEDENT>else:<EOL><INDENT>if in_range:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>
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.
f7510:c2:m6
def _assert_not_running(self):
if self.is_alive:<EOL><INDENT>raise Error(<EOL>self._ad,<EOL>'<STR_LIT>')<EOL><DEDENT>
Asserts the logcat service is not running. Raises: Error, if the logcat service is running.
f7510:c2:m7
def start(self):
self._assert_not_running()<EOL>if self._configs.clear_log:<EOL><INDENT>self.clear_adb_log()<EOL><DEDENT>self._start()<EOL>
Starts a standing adb logcat collection. The collection runs in a separate subprocess and saves logs in a file.
f7510:c2:m8
def _start(self):
self._enable_logpersist()<EOL>logcat_file_path = self._configs.output_file_path<EOL>if not logcat_file_path:<EOL><INDENT>f_name = '<STR_LIT>' % (self._ad.model,<EOL>self._ad._normalized_serial)<EOL>logcat_file_path = os.path.join(self._ad.log_path, f_name)<EOL><DEDENT>utils.create_dir(os.path.dirname(logcat_file_path))<EOL>cmd = '<STR_LIT>' % (<EOL>adb.ADB, self._ad.serial, self._configs.logcat_params,<EOL>logcat_file_path)<EOL>process = utils.start_standing_subprocess(cmd, shell=True)<EOL>self._adb_logcat_process = process<EOL>self.adb_logcat_file_path = logcat_file_path<EOL>
The actual logic of starting logcat.
f7510:c2:m9
def stop(self):
if not self._adb_logcat_process:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>utils.stop_standing_subprocess(self._adb_logcat_process)<EOL><DEDENT>except:<EOL><INDENT>self._ad.log.exception('<STR_LIT>')<EOL><DEDENT>self._adb_logcat_process = None<EOL>
Stops the adb logcat service.
f7510:c2:m10
def pause(self):
self.stop()<EOL>self.clear_adb_log()<EOL>
Pauses logcat. Note: the service is unable to collect the logs when paused, if more logs are generated on the device than the device's log buffer can hold, some logs would be lost. Clears cached adb content, so that when the service resumes, we don't duplicate what's in the device's log buffer already. This helps situations like USB off.
f7510:c2:m11
def resume(self):
self._assert_not_running()<EOL>self._start()<EOL>
Resumes a paused logcat service.
f7510:c2:m12
def __init__(self, package, ad):
super(SnippetClient, self).__init__(app_name=package, ad=ad)<EOL>self.package = package<EOL>self._ad = ad<EOL>self._adb = ad.adb<EOL>self._proc = None<EOL>
Initializes a SnippetClient. Args: package: (str) The package name of the apk where the snippets are defined. ad: (AndroidDevice) the device object associated with this client.
f7511:c2:m0
@property<EOL><INDENT>def is_alive(self):<DEDENT>
return self._conn is not None<EOL>
Is the client alive. The client is considered alive if there is a connection object held for it. This is an approximation due to the following scenario: In the USB disconnect case, the host subprocess that kicked off the snippet apk would die, but the snippet apk itself would continue running on the device. The best approximation we can make is, the connection object has not been explicitly torn down, so the client should be considered alive. Returns: True if the client is considered alive, False otherwise.
f7511:c2:m1
def start_app_and_connect(self):
try:<EOL><INDENT>self._start_app_and_connect()<EOL><DEDENT>except AppStartPreCheckError:<EOL><INDENT>raise<EOL><DEDENT>except Exception as e:<EOL><INDENT>self._ad.log.exception('<STR_LIT>')<EOL>try:<EOL><INDENT>self.stop_app()<EOL><DEDENT>except:<EOL><INDENT>self._ad.log.exception(<EOL>'<STR_LIT>')<EOL><DEDENT>raise e<EOL><DEDENT>
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.
f7511:c2:m2
def _start_app_and_connect(self):
self._check_app_installed()<EOL>self.disable_hidden_api_blacklist()<EOL>persists_shell_cmd = self._get_persist_command()<EOL>self.log.info('<STR_LIT>',<EOL>self.package, _PROTOCOL_MAJOR_VERSION,<EOL>_PROTOCOL_MINOR_VERSION)<EOL>cmd = _LAUNCH_CMD % (persists_shell_cmd, self.package)<EOL>start_time = time.time()<EOL>self._proc = self._do_start_app(cmd)<EOL>line = self._read_protocol_line()<EOL>match = re.match('<STR_LIT>', line)<EOL>if not match or match.group(<NUM_LIT:1>) != '<STR_LIT:1>':<EOL><INDENT>raise ProtocolVersionError(self._ad, line)<EOL><DEDENT>line = self._read_protocol_line()<EOL>match = re.match('<STR_LIT>', line)<EOL>if not match:<EOL><INDENT>raise ProtocolVersionError(self._ad, line)<EOL><DEDENT>self.device_port = int(match.group(<NUM_LIT:1>))<EOL>self.host_port = utils.get_available_host_port()<EOL>self._adb.forward(<EOL>['<STR_LIT>' % self.host_port,<EOL>'<STR_LIT>' % self.device_port])<EOL>self.connect()<EOL>self.log.debug('<STR_LIT>',<EOL>self.package, time.time() - start_time, self.host_port)<EOL>
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.
f7511:c2:m3
def restore_app_connection(self, port=None):
self.host_port = port or utils.get_available_host_port()<EOL>self._adb.forward(<EOL>['<STR_LIT>' % self.host_port,<EOL>'<STR_LIT>' % self.device_port])<EOL>try:<EOL><INDENT>self.connect()<EOL><DEDENT>except:<EOL><INDENT>self.log.exception('<STR_LIT>')<EOL>raise jsonrpc_client_base.AppRestoreConnectionError(<EOL>self._ad,<EOL>('<STR_LIT>'<EOL>'<STR_LIT>') % (self.package, self.host_port,<EOL>self.device_port))<EOL><DEDENT>self._proc = None<EOL>self._restore_event_client()<EOL>
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.
f7511:c2:m4
def _start_event_client(self):
event_client = SnippetClient(package=self.package, ad=self._ad)<EOL>event_client.host_port = self.host_port<EOL>event_client.device_port = self.device_port<EOL>event_client.connect(self.uid,<EOL>jsonrpc_client_base.JsonRpcCommand.CONTINUE)<EOL>return event_client<EOL>
Overrides superclass.
f7511:c2:m6
def _restore_event_client(self):
if not self._event_client:<EOL><INDENT>self._event_client = self._start_event_client()<EOL>return<EOL><DEDENT>self._event_client.host_port = self.host_port<EOL>self._event_client.device_port = self.device_port<EOL>self._event_client.connect()<EOL>
Restores previously created event client.
f7511:c2:m7
def _read_protocol_line(self):
while True:<EOL><INDENT>line = self._proc.stdout.readline().decode('<STR_LIT:utf-8>')<EOL>if not line:<EOL><INDENT>raise jsonrpc_client_base.AppStartError(<EOL>self._ad, '<STR_LIT>')<EOL><DEDENT>line = line.strip()<EOL>if (line.startswith('<STR_LIT>')<EOL>or line.startswith('<STR_LIT>')):<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>', line)<EOL>return line<EOL><DEDENT>self.log.debug('<STR_LIT>',<EOL>line)<EOL><DEDENT>
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.
f7511:c2:m10
def _get_persist_command(self):
for command in [_SETSID_COMMAND, _NOHUP_COMMAND]:<EOL><INDENT>try:<EOL><INDENT>if command in self._adb.shell(['<STR_LIT>',<EOL>command]).decode('<STR_LIT:utf-8>'):<EOL><INDENT>return command<EOL><DEDENT><DEDENT>except adb.AdbError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>self.log.warning(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>_SETSID_COMMAND, _NOHUP_COMMAND)<EOL>return '<STR_LIT>'<EOL>
Check availability and return path of command if available.
f7511:c2:m11
def help(self, print_output=True):
help_text = self._rpc('<STR_LIT>')<EOL>if print_output:<EOL><INDENT>print(help_text)<EOL><DEDENT>else:<EOL><INDENT>return help_text<EOL><DEDENT>
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.
f7511:c2:m12
def _start_services(self, console_env):
raise NotImplemented()<EOL>
Starts the services needed by this client and adds them to console_env. Must be implemented by subclasses.
f7512:c1:m0
def _get_banner(self, serial):
raise NotImplemented()<EOL>
Returns the user-friendly banner message to print before the console. Must be implemented by subclasses.
f7512:c1:m1
def load_device(self, serial=None):
serials = android_device.list_adb_devices()<EOL>if not serials:<EOL><INDENT>raise Error('<STR_LIT>')<EOL><DEDENT>if not serial:<EOL><INDENT>env_serial = os.environ.get('<STR_LIT>', None)<EOL>if env_serial is not None:<EOL><INDENT>serial = env_serial<EOL><DEDENT>elif len(serials) == <NUM_LIT:1>:<EOL><INDENT>serial = serials[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise Error(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % len(serials))<EOL><DEDENT><DEDENT>if serial not in serials:<EOL><INDENT>raise Error('<STR_LIT>' % serial)<EOL><DEDENT>ads = android_device.get_instances([serial])<EOL>assert len(ads) == <NUM_LIT:1><EOL>self._ad = ads[<NUM_LIT:0>]<EOL>
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.
f7512:c1:m2