google / mobly

E2E test framework for tests with complex environment requirements.
https://github.com/google/mobly
Apache License 2.0
628 stars 175 forks source link

Inspect class instead of class instance to get test methods list. #762

Closed xianyuanjia closed 2 years ago

xianyuanjia commented 2 years ago

This prevents inspect.getmembers from calling the properties of given test class.

e.g.

>>>class Foo():
...   @property
...   def bar(self):
...       print('Called')

>>> inspect.getmembers(Foo(), callable)
Called
[...]
>>> getattr(Foo(), 'bar')
Called
'baz'

>>> inspect.getmembers(Foo, callable)
[...]
>>> getattr(Foo, 'bar')
<property object at 0x7f7c7463cb30>

This change is Reviewable

eric100lin commented 2 years ago

According to the cpython source codes:
https://github.com/python/cpython/blob/3.9/Lib/inspect.py#L351

When using inspect with class instance:inspect.getmembers(Foo(), callable) It will call getattr(foo_instance, key) on all keys from dir(foo_instance), therefore the bar property getter will be called.

When using inspect with class type: inspect.getmembers(Foo, callable) It will call getattr(Foo, key) on all keys from dir(Foo), the bar property getter will not be called.

Another approach we can consider is to use dir instead of inspect.getmembers.