pythonunit-testingnoseautomockingfudge

Automocking for Python?


I'm used to using AutoFixture.AutoMoq with C# and wanted to know if something similar is available for Python. I'm not using django or databases, so django-autofixture is not going to help me.

What I'm looking for is something that cuts down on the code I need to write to setup all my interrelated objects with stubs/mocks for testing. I'm using the IoC pattern for design (but no DI framework since Python doesn't really need them).

I'm using Nose and Fudge.


Solution

  • Try looking at Mock

    It allows you to mock out classes

    from mock import Mock
    mock = Mock()
    

    Patch functions

    from mock import patch
    
    @patch("package.function")
    def test():
        do_stuff()
    

    And then assert how many times that you've called a function

    mock = Mock()
    mock.foo()
    mock.foo.assert_called_once()
    

    So say you have a class structure as you describe.

    class A(object):
        def __init__(self, class_b):
            self.class_b = class_b
            ...
    
    class B(object):
        def __init__(self, class_c):
            ...
    
    ...
    

    Then if you want to mock out A

    In [2]: import mock
    
    In [3]: mock = mock.Mock()
    
    In [4]: a = A(mock)
    
    In [5]: a.class_b
    Out[5]: <Mock id='21280080'>
    

    Going down the line:

    In [6]: a.class_b.class_c
    Out[6]: <Mock name='mock.class_c' id='21281488'>
    In [7]: a.class_b.class_c.class_d
    Out[7]: <Mock name='mock.class_c.class_d' id='21051984'>
    

    It will all be mocked out for you regardless of how tight you've coupled your code. I imagine there are similar ways to do this for Fudge