[TIP] Making mock objects that call the original function
Kevin Tran
hekevintran at gmail.com
Fri May 17 11:35:31 PDT 2013
Yes! The wraps parameter was what I was looking for.
I tried passing wraps=True into ``patch()`` as you suggested, but this resulted in an TypeError because True is not callable:
Traceback (most recent call last):
File "/Users/haitran/repos/soalike_project/eggs/mock-1.0.1-py2.7.egg/mock.py", line 1031, in _mock_call
return self._mock_wraps(*args, **kwargs)
TypeError: 'bool' object is not callable
Anyway the wraps parameter is good balance between explicitness and convenience for me. Thanks!
On May 17, 2013, at 3:15 AM, Michael Foord <fuzzyman at voidspace.org.uk> wrote:
>
> 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