Skip to content

Commit

Permalink
Add get_service_alias_by_class in Android service manager.
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 follow the anti-pattern of attempting to register the service
again under the name the util expects. This causes duplication.
This API can be used to clean things up.
  • Loading branch information
xpconanfan committed Sep 5, 2024
1 parent cf3fbfd commit 768a02a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
18 changes: 18 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,24 @@ 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.
Note the same class can be registered multiple times with different alias
names. So this returnes a list.
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 768a02a

Please sign in to comment.