[TIP] Changes to mock in subversion: please try

Gregor Müllegger gregor at muellegger.de
Sat Oct 23 11:58:17 PDT 2010


Hi Michael,


I kind of disagree that the new behaviour of the spec argument is a good thing.
At least that it's a good thing in every situation.

Take django's request object as an example. I often use a Mock() object as
request replacement to test views and middlewares. However middlewares often
attach new attributes to the request like the built-in SessionMiddleware that
makes the request.session attribute available.

Using the stricter meaning of `spec` here won't allow me to use this for my
request mocks to test middlewares.

This special case hit me this week. Testing a custom middleware like I
described above. I was using Mock(spec=HttpRequest) but this failed because
assigning a new attribute to the request was not allowed. But if I omitted the
spec argument, a test passed which should have failed because some code
accessed a request attribute that was not set yet.

Needless to say that you could work around this by "customizing" the mock with
`side_effect` etc.. But on the other hand its sometimes very "pythonic" to
assign new attributes to an existing object (and yep - sometimes its just
laziness and bad practice :-)).

So I think both interpretations of spec have their own use cases. What about a
new `weakspec` argument that implements the old behaviour?


I hope you understand what I want to express since my English isn't that good.
Keep up your great work on mock, it's really fun to use and made my life with
unittests in python much easier. Thank you!


Gregor



More information about the testing-in-python mailing list