derwiki-adroll / mock

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

Autospeccing descriptors #155

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Sample code: https://gist.github.com/2597106

When object you try to mock with autospec property is a descriptor, you will 
fail. Example is django-model and it's .objects property, which is a descriptor 
that will lead you to a manager object.

The most important thing for me is that autospec should not raise "has no such 
attribute" exceptions if real object would not raise that exception, so the 
simplest solution (as I see) would be for autospec mechanism to determine if 
object is descriptor and then disable it's speccing mechanism on those.

What do you think?

Original issue reported on code.google.com by k...@k-bx.com on 5 May 2012 at 12:45

GoogleCodeExporter commented 9 years ago
Thanks, I'm looking into it. I would have expected it to work - but clearly it 
doesn't.

Original comment by fuzzyman on 11 May 2012 at 2:40

GoogleCodeExporter commented 9 years ago
Ok, so the problem is that you're autospeccing on the descriptor directly - and 
patch is careful to get the descriptor object without triggering the descriptor 
protocol (so that it can put the original descriptor back when the patch is 
undone).

That means that at the point it does the speccing, it is speccing the 
"BarDescriptor" and not the "RealOne" instance returned by fetching the 
descriptor.

Because of the way that patch works it's not really possible to solve this 
directly.

Instead you can either patch the Foo class instead of the Foo.bar descriptor 
*or* use an alternative invocation that tells patch which object to use as the 
spec:

    with patch('__main__.Foo.bar', autospec=Foo.bar):

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