[TIP] removing attributes and dictionary keys using mock.patch

Chris Withers chris at simplistix.co.uk
Sat Dec 6 03:46:57 PST 2014


On 05/12/2014 19:56, Barry Warsaw wrote:
> On Dec 05, 2014, at 06:19 PM, Michael Foord wrote:
>
>> 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. In which case just having patch.dict support key removal
>> would work.
>
> Would it be feasible to pretend to delete by something that raises
> AttributeError instead?

Hmmm, maybe, but what about items in a dict?
I guess they'd both have to be implemented as descriptors, but not sure 
even that would work for the dictionary access bit?

> In some sense unittest.mock almost should be its own thing outside of
> unittest.

Well, that's where it started ;-)

> In the rare cases where you have to monkeypatch something,
> unittest.mock comes darn close to providing this useful functionality in a way
> that allows you to narrowly monkeypatch and safely unpatch after the task is
> done.

Yep, although if you're doing that, you're in a fairly unpleasant place 
already...

Chris



More information about the testing-in-python mailing list