[TIP] removing attributes and dictionary keys using mock.patch
michael at voidspace.org.uk
Sun Dec 7 13:51:20 PST 2014
> On 5 Dec 2014, at 18:34, Chris Withers <chris at simplistix.co.uk> wrote:
>> On 5 Dec 2014, at 18:19, Michael Foord <michael at voidspace.org.uk> wrote:
>>> On 05/12/14 16:54, Chris Withers wrote:
>>> Hi All,
>>> I'm excited to see how far mock.patch has come, mainly as I'm hoping I can deprecate testfixtures.Replacer as a result ;-)
>>> The only think it looks like Mock can't currently do is remove attributes or dictionary items:
>>> Michael, would you be up for me adding that to Mock or is it a non-starter?
>>> I'd be happy to approach using either a delete=True option to patch() and patch.dict() (I don't really understand what patch.object does, so can't comment...) or, alternatively, a not_there or deleted marker object like I did in testfixtures.
>>> Lemme know your thoughts...
>> So, removing an attribute is not possible in the *general* case. In the specific case of it being an instance attribute you can remove it from the object dictionary.
> Yeah, my take on it is "anything where delattr works"...
But how will you know?
>> In which case just having patch.dict support key removal would work.
> ...or delitem in this case.
>> I don't have any objection if the api can be clean and the implementation isn't horrible.
> Do you have a preference for a marker object (like testfixtures uses) or a keyword param (such as delete=True)?
> A whole separate set of decorators/context managers/etc seems like overkill, so I hope that's not your preference ;-)
A marker object would be better. Like:
DELETE = sentinel.DELETE
with patch('foo.bar', attribute=DELETE):
Please create on issue on bugs.python.org, preferably with patch, tests and docs :-)
May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing
More information about the testing-in-python