hRobert12 / mock

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

Autospeccing should not copy spec from class to instance #157

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
https://gist.github.com/2660237

I tried to mock django-form class, and then it's instance access to 
.cleaned_data would throw an AttributeError.

Since most of object-attributes are added in __init__, I find that strange.

Is it on purpose? Even if yes -- I velieve we should change that. Thanks.

Original issue reported on code.google.com by k...@k-bx.com on 11 May 2012 at 2:52

GoogleCodeExporter commented 8 years ago
p.s.: as in past, I find that the best thing on this would be to remember spec 
of class-functions, but disable attributeerror on non-existing attributes 
access.

Original comment by k...@k-bx.com on 11 May 2012 at 2:53

GoogleCodeExporter commented 8 years ago
Well, it is deliberate - and even documented as one of the drawbacks of 
auto-speccing:

http://www.voidspace.org.uk/python/mock/helpers.html#autospeccing

Not throwing AttributeError on unknown attributes would negate what is really 
the *main point* of speccing - that it restricts the attributes available on 
mock objects. 

Original comment by fuzzyman on 11 May 2012 at 3:08

GoogleCodeExporter commented 8 years ago
Ok, after some thoughts, I tend to agree here, actually. Maybe docs should be 
added. My main points are:

1. if it's a rare case -- you should just add to-be-known attributes to your 
mock object. like
a_M = create_autospec(A); a_M.cleaned_data = MagicMock()

2. generally (not only in python), there should be value-objects and 
service-objects (which in python are mostly just functions), and value-objects 
should always be easy to construct/create and avoid doing something in 
__init__(). for hard constructing there's fabrics, and for doing something 
there are methods.

The problem is that many frameworks / libs do not go with this methodics, but:
1. it's a question to library / framework authors
2. mock with autospec still lets you add attributes, so that solves everything.

Original comment by k...@k-bx.com on 11 May 2012 at 3:19

GoogleCodeExporter commented 8 years ago
RIght, I agree with you that this limitation makes auto-speccing less generally 
useful than it might be - and that attaching manually created mocks as 
attributes is probably the best workaround. I can add this to the docs.

Original comment by fuzzyman on 11 May 2012 at 3:26