Skip to content

Commit

Permalink
Add get_service_alias_by_class in Android service manager. (#942)
Browse files Browse the repository at this point in the history
This is useful for looking up how many instances of a service has
been registered, and find out their aliases.

Util functions may depend on services like `uiautomator`. Users tend
to make the mistake of registering the service multiple times even
the service itself only supports one instance. This can cause implicit
failures that are difficult to debug.

This API can be used to clean things up.
  • Loading branch information
xpconanfan authored Sep 5, 2024
1 parent cf3fbfd commit de93e1e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
19 changes: 19 additions & 0 deletions mobly/controllers/android_device_lib/service_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,25 @@ def for_each(self, func):
):
func(self._service_objects[alias])

def get_service_alias_by_class(self, service_class):
"""Gets the aslias name of a registered service.
The same service class can be registered multiple times with different
aliases. When not well managed, duplication and race conditions can arise.
One can use this API to de-duplicate as needed.
Args:
service_class: class, the class of a service type.
Returns:
list of strings, the aliases the service is registered with.
"""
aliases = []
for alias, service_object in self._service_objects.items():
if isinstance(service_object, service_class):
aliases.append(alias)
return aliases

def list_live_services(self):
"""Lists the aliases of all the services that are alive.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,14 @@ def test_resume_services_non_existent(self):
with self.assertRaisesRegex(service_manager.Error, msg):
manager.resume_services(['mock_service'])

def test_get_alias_by_class(self):
manager = service_manager.ServiceManager(mock.MagicMock())
manager.register('mock_service1', MockService, start_service=False)
manager.register('mock_service2', MockService, start_service=False)
manager.start_services(['mock_service2'])
aliases = manager.get_service_alias_by_class(MockService)
self.assertEqual(aliases, ['mock_service1', 'mock_service2'])


if __name__ == '__main__':
unittest.main()

0 comments on commit de93e1e

Please sign in to comment.