Using mock to fix non-existent attribute

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 # Do some tests on mock object 

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.

+5
source share
1 answer

To use patch in these tests, you must use the create parameter, which forces the attribute to be created if it does not exist.

So your test should do something like this:

 def test_MyContextManager(): with patch.object(MyClass, 'myfunc', create=True, return_value=None) as mock_obj: with MyContextManager(): pass 
+8
source

All Articles