tags:

views:

205

answers:

2

I'm using the Python MiniMock library for unit testing. I'd like to mock out a function defined in the same Python file as my doctest. Can MiniMock handle that? The naive approach fails:

def foo():
    raise ValueError, "Don't call me during testing!"

def bar():
    """
    Returns twice the value of foo()

    >>> from minimock import mock
    >>> mock('foo',returns=5)
    >>> bar()
    Called foo()
    10

    """
    return foo() * 2

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Here's what happens if I try to run this code:

**********************************************************************
File "test.py", line 9, in __main__.bar
Failed example:
    bar()
Exception raised:
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/doctest.py", line 1212, in __run
        compileflags, 1) in test.globs
      File "<doctest __main__.bar[2]>", line 1, in <module>
        bar()
      File "test.py", line 13, in bar
        return foo() * 2
      File "test.py", line 2, in foo
        raise ValueError, "Don't call me!"
    ValueError: Don't call me!
**********************************************************************
1 items had failures:
   1 of   3 in __main__.bar
***Test Failed*** 1 failures.

Edit: As per the answers below, this has been identified as a bug, and has been fixed in MiniMock.

+1  A: 
itsadok
This issue has been brought up in the MiniMock mailing list: http://groups.google.com/group/minimock-dev/browse_thread/thread/f8a583bc862f279?hl=en
lorin
+5  A: 

I just replied on the mailing list with a MiniMock patch that fixes this.

Until that's applied, instead of the following two lines in itsadok's snippet:

>>> mock('foo',returns=5)
>>> bar.func_globals['foo'] = foo

you could also use

>>> mock('foo', nsdicts=(bar.func_globals,), returns=5)
Josh Bronson
I've applied the patch to tip (see http://bitbucket.org/jab/minimock/changeset/bb9528bb454d/).
Josh Bronson