derwiki-adroll / mock

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

Add a stub class / function #174

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Since the terminology all over testing is so wonky, by a stub I mean an object 
with only a provided list of attributes that are generally real, precalculated 
and valid.

Stubs are generally easy to write manually, but once I'm using mock I often 
find myself being lazy and using a `mock.Mock` object rather than writing one, 
since it's just there for me already, and has a convenient construction. Of 
course that works, but the disadvantage is obviously that you've given your 
test more leeway than you meant to, which can be mitigated with `spec=[]` but 
that gets messy to keep writing.

It'd be nice to have `mock.Stub` essentially just be a thing that took either 
of `kwargs` or mock's fqn-mapped dictionary to assign attributes and have a 
reasonable `repr` -- I think there's probably one or two other things we could 
give it that I don't remember off the top of my head right now but I can edit 
in later.

Implementation the obvious way is probably easier than calling out to 
`mock.Mock(spec=[])`.

Original issue reported on code.google.com by jul...@grayvines.com on 4 Sep 2012 at 12:59

GoogleCodeExporter commented 9 years ago
I'm inclined to say that if mock.Mock(spec=[], **kwargs) does what you want, 
then just use that rather than add a new type to mock.

Original comment by fuzzyman on 5 Nov 2012 at 9:07

GoogleCodeExporter commented 9 years ago
Note that this class provides a "stub" functionality, identical to the "stub" 
in the pretend library by Alex Gaynor. At the very least it should go as an 
example in the documentation:

from mock import MagicMock, _is_magic

def _wrap(f, n):
    if not (_is_magic(n) and isinstance(f, type(lambda: None))):
        return f
    def inner(self, *args, **kwargs):
        return f(*args, **kwargs)
    inner.__name__ = n
    return inner

class stub(MagicMock):
    def __init__(self, spec_set=None, **kwargs):
        super(MagicMock, self).__init__(spec=list(kwargs), spec_set=spec_set)
        [setattr(self, k, _wrap(v, k)) for k, v in kwargs.items()]

Original comment by fuzzyman on 8 Nov 2012 at 11:25