I am trying to test a context manager that uses a class that uses __getattr__ magic to solve several attributes that do not actually exist in the class. I encounter a problem when mock raises an AttributeError when trying to fix a class.
A simplified example of the objects I want to fix.
class MyClass(object): def __getattr__(self, attr): if attr == 'myfunc': return lambda:return None raise AttributeError('error') class MyContextManager(object): def __init__(self): super(MyContextManager, self).__init__() self.myclass = MyClass() def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): self.myclass.myfunc()
Test code
def test_MyContextManager(): with patch.object(MyClass, 'myfunc', return_value=None) as mock_obj: with MyContextManager(): pass
Here is the error I get:
AttributeError: <class 'MyClass'> does not have the attribute 'myfunc'
I can do this and run the test, but it does not restore the attribute (or just remove the mock attribute in this case) automatically:
MyClass.myfunc= Mock(return_value=None)
I am open to using another library, in addition to doing this. I also use pytest.
source share