derwiki-adroll / mock

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

Get spec of class methods for mock object #137

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Hi!

Say you have a class A and you want to create a mock for it's object instance 
(result of A()).

To make your testing better, you want to also get maximum out of spec of A, so 
that your test will fail when you will call method of A with wrong parameters.

Right now the only way is to first create A() object, then put it into spec= 
parameter. But sometimes creating object is too harmful (too much parameters 
etc.) just for specs.

So what I want to suggest is to have "less strict" spec, that would take your 
class A, get it's methods, and remember their call-specs. So you will do 
something like::

    class A(object):
        def b(self, a, b, c): pass

    mock = MagicMock(class_spec=A)
    mock.b()
    AssertionError! b takes 4 arguments(1 given)
    mock.c  # <-- no exception, since this spec is not so strict

Also, you can combine this class_spec param to make mock pass isinstance(A), so 
then you will have http://code.google.com/p/mock/issues/detail?id=136 
implemented via the same param name :)

Thanks!

Original issue reported on code.google.com by k...@k-bx.com on 3 Mar 2012 at 1:44

GoogleCodeExporter commented 9 years ago
The problem I have with this is that the "spec" situation with mock is already 
confusing. There are currently three "spec" variants (none of which do quite 
what you want): spec, spec_set and create_autospec.

I'm not wild about the idea of adding a fourth. (Note that a normal spec 
doesn't check the number of arguments to methods - it's only create_autospec 
that does that.)

Original comment by fuzzyman on 3 Mar 2012 at 11:22

GoogleCodeExporter commented 9 years ago

Original comment by fuzzyman on 4 Mar 2012 at 12:01

GoogleCodeExporter commented 9 years ago
So I don't want to add another constructor parameter. How about I make 
__class__ assignable, so at least it allows you to solve your isinstance 
problem?

Original comment by fuzzyman on 14 Mar 2012 at 6:10

GoogleCodeExporter commented 9 years ago
That would be perfect. I mean, first time I wanted this, I tried exactly this 
solution :)

Original comment by k...@k-bx.com on 14 Mar 2012 at 10:02

GoogleCodeExporter commented 9 years ago
This is now implemented in the mercurial repository, and the standard library 
version.

Original comment by fuzzyman on 14 Mar 2012 at 8:36