derwiki-adroll / mock

Automatically exported from code.google.com/p/mock
BSD 2-Clause "Simplified" License
0 stars 0 forks source link

Implement __delattr__ for removing attributes #131

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
In order to be able to test code like: http://bpaste.net/show/21613/

it'd be useful to have support for __delattr__ for marking attributes that one 
wishes would raise AttributeErrors.

Quickly cobbled together implementation patch attached.

Original issue reported on code.google.com by jul...@grayvines.com on 11 Jan 2012 at 2:46

Attachments:

GoogleCodeExporter commented 9 years ago
Does this example do what you want?
{{{

from mock import Mock

deleted = object()
missing = object()

class DeletingMock(Mock):
    def __delattr__(self, attr):
        if attr in self.__dict__:
            return super(DeletingMock, self).__delattr__(attr)
        obj = self._mock_children.get(attr, missing)
        if obj is deleted:
            raise AttributeError(attr)
        if obj is not missing:
            del self._mock_children[attr]
        self._mock_children[attr] = deleted

    def __getattr__(self, attr):
        result = super(DeletingMock, self).__getattr__(attr)
        if result is deleted:
            raise AttributeError(attr)
        return result
}}}

I think it would be reasonable to add this to mock. The only problem is that it 
is possible to delete methods, which you couldn't do on a real instance object, 
and after deleting you lose the reference to the mock and can't make assertions 
on it.

Original comment by fuzzyman on 11 Jan 2012 at 2:09

GoogleCodeExporter commented 9 years ago
I'd thought about that second part of that actually. Assuming you go with 
something like the implementation I had in the patch, if you wanted to allow 
that (which in my current use case I actually did), you could add a 
restore_deletions() context manager (probably just as an example on the 
examples page, not sure if you'd actually want to include it with mock) that 
patched _mock_excluded and restored it on __exit__.

Original comment by jul...@grayvines.com on 11 Jan 2012 at 2:37

GoogleCodeExporter commented 9 years ago
Will be in 1.0.

Original comment by fuzzyman on 14 Mar 2012 at 6:16