1

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.

Matt
  • 14,353
  • 5
  • 53
  • 65

1 Answers1

1

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

Greg
  • 5,422
  • 1
  • 27
  • 32
  • I"m aware of mocking frameworks, I use Fudge, which is an alternative to Mock. What I'm talking about is when you have some Class A, which accepts Class Bdependency in the constructor. Class B accepts class C, which accepts class D, etc... If I want to mock/stub B, I'd have to also stub C and D too. Automocking frameworks take care of stubbing out those dependencies objects for you cutting down on setting up your test. They typically would work in conjunction with something like Mock or Fudge. If there was a port of the C# autofixture available for python there would be AutoFixture.AutoFudge. – Matt Aug 27 '13 at 22:30
  • If the flow is as you describe all you have to stub is class B using Mock – Greg Aug 27 '13 at 22:47
  • Hmm... it looks like Fudge's `is_a_stub()` provides fakes for situations like mentioned. It seems once again with dynamic languages we have much more flexibility than in static. I just tested the following and it works: `fake_b=fudge.Fake('b').is_a_stub() sut=A(fake_b) fake_c=sut._b._c expected='Auto stub worked!' fake_c.provides('do_something').returns(expected) actual=fake_c.do_something() assert expected==actual` – Matt Aug 28 '13 at 00:15