[TIP] How to get magic mock wraps to work with dict attributes?
robertc at robertcollins.net
Sun Oct 11 18:38:56 PDT 2015
On 7 October 2015 at 03:15, Darragh Bailey <daragh.bailey at gmail.com> wrote:
> I'm trying to create a mock wrapper around a requests Response object, so
> that I can check the calls to both methods and attributes, while still using
> the underlying Response object.
> However I'm struggling to ensure that access of a custom dict class that is
> an attribute of the Response object works as expected and I'm wondering if
> I'm missing something or perhaps mock doesn't support my desired usage?
> see https://gist.github.com/electrofelix/40f4c38cf28bb701dba3 for an example
> with some asserts that ideally should work but fails in membership tests.
> The Response object headers attribute, is of type CaseInsensitiveDict, but
> there doesn't seem to be an easy way to wrap that object so that various
> tests for membership against the mock will work as expected. Though certain
> key access works correctly.
> My first assumption is I'm doing something wrong, but it might just be a bug
> or missing desirable behaviour?
The dict dunder methods are not included in the magics that MagicMock
knows about. You basically want __getitem__ to dereference via the
wrapped object (and return a wrapped answer) rather than mocking, in
the same way attribute access does. File a bug on bugs.python.org I
suspect... once fixed we'll backport it into mock.
Robert Collins <rbtcollins at hp.com>
HP Converged Cloud
More information about the testing-in-python