[TIP] Making mock objects that call the original function

Michael Foord fuzzyman at voidspace.org.uk
Fri May 17 03:15:23 PDT 2013


On 17 May 2013, at 00:46, Kevin Tran <hekevintran at gmail.com> wrote:

> The mock objects in the Jasmine testing framework have a `andCallthrough()` method.  This allows you have a mock that when called, calls the original function.  An example:
> 
>    describe("A spy, when configured to call through", function() {
>      var foo, bar, fetchedBar;
> 
>      beforeEach(function() {
>        foo = {
>          setBar: function(value) {
>            bar = value;
>          },
>          getBar: function() {
>            return bar;
>          }
>        };
> 
>        spyOn(foo, 'getBar').andCallThrough();
> 
>        foo.setBar(123);
>        fetchedBar = foo.getBar();
>      });
> 
>      it("tracks that the spy was called", function() {
>        expect(foo.getBar).toHaveBeenCalled();
>      });
> 
>      it("should not effect other functions", function() {
>        expect(bar).toEqual(123);
>      });
> 
>      it("when called returns the requested value", function() {
>        expect(fetchedBar).toEqual(123);
>      });
>    });
> 
> The only way I know how to do this in the Python mock library (http://www.voidspace.org.uk/python/mock/) is by setting the original function manually:
> 
>    with patch('my_project.forms.create_user') as mock_create_user:
>        mock_create_user.side_effect = create_user
>        client.post('/signup/', data)
>        self.assertEqual(1, mock_create_user.call_count)
>        self.assertEqual(1, User.objects.count())
> 
> Is there a better built-in way to do this?


You can use the "wraps" keyword argument.

>>> from mock import Mock
>>> def foo():
...     print 'Called'
...     
>>> m = Mock(wraps=foo)
>>> 
>>> m()
Called

I believe that patch takes a "wraps=True" keyword argument to do this automatically for you.

All the best,

Michael Foord

> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


--
http://www.voidspace.org.uk/


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing 
http://www.sqlite.org/different.html








More information about the testing-in-python mailing list