summaryrefslogtreecommitdiffstats
path: root/python/mock-1.0.0/html/_sources/compare.txt
blob: 41555308e2fdb6365f34142cfdadd3f3405c773e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
=========================
 Mock Library Comparison
=========================


.. testsetup::

    def assertEqual(a, b):
        assert a == b, ("%r != %r" % (a, b))

    def assertRaises(Exc, func):
        try:
            func()
        except Exc:
            return
        assert False, ("%s not raised" % Exc)

    sys.modules['somemodule'] = somemodule = mock.Mock(name='somemodule')
    class SomeException(Exception):
        some_method = method1 = method2 = None
    some_other_object = SomeObject = SomeException


A side-by-side comparison of how to accomplish some basic tasks with mock and
some other popular Python mocking libraries and frameworks.

These are:

* `flexmock <http://pypi.python.org/pypi/flexmock>`_
* `mox <http://pypi.python.org/pypi/mox>`_
* `Mocker <http://niemeyer.net/mocker>`_
* `dingus <http://pypi.python.org/pypi/dingus>`_
* `fudge <http://pypi.python.org/pypi/fudge>`_

Popular python mocking frameworks not yet represented here include
`MiniMock <http://pypi.python.org/pypi/MiniMock>`_.

`pMock <http://pmock.sourceforge.net/>`_ (last release 2004 and doesn't import
in recent versions of Python) and
`python-mock <http://python-mock.sourceforge.net/>`_ (last release 2005) are
intentionally omitted.

.. note::

    A more up to date, and tested for all mock libraries (only the mock
    examples on this page can be executed as doctests) version of this
    comparison is maintained by Gary Bernhardt:

    * `Python Mock Library Comparison
      <http://garybernhardt.github.com/python-mock-comparison/>`_

This comparison is by no means complete, and also may not be fully idiomatic
for all the libraries represented. *Please* contribute corrections, missing
comparisons, or comparisons for additional libraries to the `mock issue
tracker <https://code.google.com/p/mock/issues/list>`_.

This comparison page was originally created by the `Mox project
<https://code.google.com/p/pymox/wiki/MoxComparison>`_ and then extended for
`flexmock and mock <http://has207.github.com/flexmock/compare.html>`_ by
Herman Sheremetyev. Dingus examples written by `Gary Bernhadt
<http://garybernhardt.github.com/python-mock-comparison/>`_. fudge examples
provided by `Kumar McMillan <http://farmdev.com/>`_.

.. note::

    The examples tasks here were originally created by Mox which is a mocking
    *framework* rather than a library like mock. The tasks shown naturally
    exemplify tasks that frameworks are good at and not the ones they make
    harder. In particular you can take a `Mock` or `MagicMock` object and use
    it in any way you want with no up-front configuration. The same is also
    true for Dingus.

    The examples for mock here assume version 0.7.0.


Simple fake object
~~~~~~~~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> my_mock = mock.Mock()
    >>> my_mock.some_method.return_value = "calculated value"
    >>> my_mock.some_attribute = "value"
    >>> assertEqual("calculated value", my_mock.some_method())
    >>> assertEqual("value", my_mock.some_attribute)

::

    # Flexmock
    mock = flexmock(some_method=lambda: "calculated value", some_attribute="value")
    assertEqual("calculated value", mock.some_method())
    assertEqual("value", mock.some_attribute)

    # Mox
    mock = mox.MockAnything()
    mock.some_method().AndReturn("calculated value")
    mock.some_attribute = "value"
    mox.Replay(mock)
    assertEqual("calculated value", mock.some_method())
    assertEqual("value", mock.some_attribute)

    # Mocker
    mock = mocker.mock()
    mock.some_method()
    mocker.result("calculated value")
    mocker.replay()
    mock.some_attribute = "value"
    assertEqual("calculated value", mock.some_method())
    assertEqual("value", mock.some_attribute)

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus(some_attribute="value",
    ...                           some_method__returns="calculated value")
    >>> assertEqual("calculated value", my_dingus.some_method())
    >>> assertEqual("value", my_dingus.some_attribute)

::

    >>> # fudge
    >>> my_fake = (fudge.Fake()
    ...            .provides('some_method')
    ...            .returns("calculated value")
    ...            .has_attr(some_attribute="value"))
    ...
    >>> assertEqual("calculated value", my_fake.some_method())
    >>> assertEqual("value", my_fake.some_attribute)


Simple mock
~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> my_mock = mock.Mock()
    >>> my_mock.some_method.return_value = "value"
    >>> assertEqual("value", my_mock.some_method())
    >>> my_mock.some_method.assert_called_once_with()

::

    # Flexmock
    mock = flexmock()
    mock.should_receive("some_method").and_return("value").once
    assertEqual("value", mock.some_method())

    # Mox
    mock = mox.MockAnything()
    mock.some_method().AndReturn("value")
    mox.Replay(mock)
    assertEqual("value", mock.some_method())
    mox.Verify(mock)

    # Mocker
    mock = mocker.mock()
    mock.some_method()
    mocker.result("value")
    mocker.replay()
    assertEqual("value", mock.some_method())
    mocker.verify()

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus(some_method__returns="value")
    >>> assertEqual("value", my_dingus.some_method())
    >>> assert my_dingus.some_method.calls().once()

::

    >>> # fudge
    >>> @fudge.test
    ... def test():
    ...     my_fake = (fudge.Fake()
    ...                .expects('some_method')
    ...                .returns("value")
    ...                .times_called(1))
    ...
    >>> test()
    Traceback (most recent call last):
    ...
    AssertionError: fake:my_fake.some_method() was not called


Creating partial mocks
~~~~~~~~~~~~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> SomeObject.some_method = mock.Mock(return_value='value')
    >>> assertEqual("value", SomeObject.some_method())

::

    # Flexmock
    flexmock(SomeObject).should_receive("some_method").and_return('value')
    assertEqual("value", mock.some_method())

    # Mox
    mock = mox.MockObject(SomeObject)
    mock.some_method().AndReturn("value")
    mox.Replay(mock)
    assertEqual("value", mock.some_method())
    mox.Verify(mock)

    # Mocker
    mock = mocker.mock(SomeObject)
    mock.Get()
    mocker.result("value")
    mocker.replay()
    assertEqual("value", mock.some_method())
    mocker.verify()

::

    >>> # Dingus
    >>> object = SomeObject
    >>> object.some_method = dingus.Dingus(return_value="value")
    >>> assertEqual("value", object.some_method())

::

    >>> # fudge
    >>> fake = fudge.Fake().is_callable().returns("<fudge-value>")
    >>> with fudge.patched_context(SomeObject, 'some_method', fake):
    ...     s = SomeObject()
    ...     assertEqual("<fudge-value>", s.some_method())
    ...


Ensure calls are made in specific order
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> my_mock = mock.Mock(spec=SomeObject)
    >>> my_mock.method1()
    <Mock name='mock.method1()' id='...'>
    >>> my_mock.method2()
    <Mock name='mock.method2()' id='...'>
    >>> assertEqual(my_mock.mock_calls, [call.method1(), call.method2()])

::

    # Flexmock
    mock = flexmock(SomeObject)
    mock.should_receive('method1').once.ordered.and_return('first thing')
    mock.should_receive('method2').once.ordered.and_return('second thing')

    # Mox
    mock = mox.MockObject(SomeObject)
    mock.method1().AndReturn('first thing')
    mock.method2().AndReturn('second thing')
    mox.Replay(mock)
    mox.Verify(mock)

    # Mocker
    mock = mocker.mock()
    with mocker.order():
        mock.method1()
        mocker.result('first thing')
        mock.method2()
        mocker.result('second thing')
        mocker.replay()
        mocker.verify()

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus()
    >>> my_dingus.method1()
    <Dingus ...>
    >>> my_dingus.method2()
    <Dingus ...>
    >>> assertEqual(['method1', 'method2'], [call.name for call in my_dingus.calls])

::

    >>> # fudge
    >>> @fudge.test
    ... def test():
    ...     my_fake = (fudge.Fake()
    ...                .remember_order()
    ...                .expects('method1')
    ...                .expects('method2'))
    ...     my_fake.method2()
    ...     my_fake.method1()
    ...
    >>> test()
    Traceback (most recent call last):
    ...
    AssertionError: Call #1 was fake:my_fake.method2(); Expected: #1 fake:my_fake.method1(), #2 fake:my_fake.method2(), end


Raising exceptions
~~~~~~~~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> my_mock = mock.Mock()
    >>> my_mock.some_method.side_effect = SomeException("message")
    >>> assertRaises(SomeException, my_mock.some_method)

::

    # Flexmock
    mock = flexmock()
    mock.should_receive("some_method").and_raise(SomeException("message"))
    assertRaises(SomeException, mock.some_method)

    # Mox
    mock = mox.MockAnything()
    mock.some_method().AndRaise(SomeException("message"))
    mox.Replay(mock)
    assertRaises(SomeException, mock.some_method)
    mox.Verify(mock)

    # Mocker
    mock = mocker.mock()
    mock.some_method()
    mocker.throw(SomeException("message"))
    mocker.replay()
    assertRaises(SomeException, mock.some_method)
    mocker.verify()

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus()
    >>> my_dingus.some_method = dingus.exception_raiser(SomeException)
    >>> assertRaises(SomeException, my_dingus.some_method)

::

    >>> # fudge
    >>> my_fake = (fudge.Fake()
    ...            .is_callable()
    ...            .raises(SomeException("message")))
    ...
    >>> my_fake()
    Traceback (most recent call last):
    ...
    SomeException: message


Override new instances of a class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> with mock.patch('somemodule.Someclass') as MockClass:
    ...     MockClass.return_value = some_other_object
    ...     assertEqual(some_other_object, somemodule.Someclass())
    ...


::

    # Flexmock
    flexmock(some_module.SomeClass, new_instances=some_other_object)
    assertEqual(some_other_object, some_module.SomeClass())

    # Mox
    # (you will probably have mox.Mox() available as self.mox in a real test)
    mox.Mox().StubOutWithMock(some_module, 'SomeClass', use_mock_anything=True)
    some_module.SomeClass().AndReturn(some_other_object)
    mox.ReplayAll()
    assertEqual(some_other_object, some_module.SomeClass())

    # Mocker
    instance = mocker.mock()
    klass = mocker.replace(SomeClass, spec=None)
    klass('expected', 'args')
    mocker.result(instance)

::

    >>> # Dingus
    >>> MockClass = dingus.Dingus(return_value=some_other_object)
    >>> with dingus.patch('somemodule.SomeClass', MockClass):
    ...     assertEqual(some_other_object, somemodule.SomeClass())
    ...

::

    >>> # fudge
    >>> @fudge.patch('somemodule.SomeClass')
    ... def test(FakeClass):
    ...     FakeClass.is_callable().returns(some_other_object)
    ...     assertEqual(some_other_object, somemodule.SomeClass())
    ...
    >>> test()


Call the same method multiple times
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. note::

    You don't need to do *any* configuration to call `mock.Mock()` methods
    multiple times. Attributes like `call_count`, `call_args_list` and
    `method_calls` provide various different ways of making assertions about
    how the mock was used.

.. doctest::

    >>> # mock
    >>> my_mock = mock.Mock()
    >>> my_mock.some_method()
    <Mock name='mock.some_method()' id='...'>
    >>> my_mock.some_method()
    <Mock name='mock.some_method()' id='...'>
    >>> assert my_mock.some_method.call_count >= 2

::

    # Flexmock # (verifies that the method gets called at least twice)
    flexmock(some_object).should_receive('some_method').at_least.twice

    # Mox
    # (does not support variable number of calls, so you need to create a new entry for each explicit call)
    mock = mox.MockObject(some_object)
    mock.some_method(mox.IgnoreArg(), mox.IgnoreArg())
    mock.some_method(mox.IgnoreArg(), mox.IgnoreArg())
    mox.Replay(mock)
    mox.Verify(mock)

    # Mocker
    # (TODO)

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus()
    >>> my_dingus.some_method()
    <Dingus ...>
    >>> my_dingus.some_method()
    <Dingus ...>
    >>> assert len(my_dingus.calls('some_method')) == 2

::

    >>> # fudge
    >>> @fudge.test
    ... def test():
    ...     my_fake = fudge.Fake().expects('some_method').times_called(2)
    ...     my_fake.some_method()
    ...
    >>> test()
    Traceback (most recent call last):
    ...
    AssertionError: fake:my_fake.some_method() was called 1 time(s). Expected 2.


Mock chained methods
~~~~~~~~~~~~~~~~~~~~

.. doctest::

    >>> # mock
    >>> my_mock = mock.Mock()
    >>> method3 = my_mock.method1.return_value.method2.return_value.method3
    >>> method3.return_value = 'some value'
    >>> assertEqual('some value', my_mock.method1().method2().method3(1, 2))
    >>> method3.assert_called_once_with(1, 2)

::

    # Flexmock
    # (intermediate method calls are automatically assigned to temporary fake objects
    # and can be called with any arguments)
    flexmock(some_object).should_receive(
        'method1.method2.method3'
    ).with_args(arg1, arg2).and_return('some value')
    assertEqual('some_value', some_object.method1().method2().method3(arg1, arg2))

::

    # Mox
    mock = mox.MockObject(some_object)
    mock2 = mox.MockAnything()
    mock3 = mox.MockAnything()
    mock.method1().AndReturn(mock1)
    mock2.method2().AndReturn(mock2)
    mock3.method3(arg1, arg2).AndReturn('some_value')
    self.mox.ReplayAll()
    assertEqual("some_value", some_object.method1().method2().method3(arg1, arg2))
    self.mox.VerifyAll()

    # Mocker
    # (TODO)

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus()
    >>> method3 = my_dingus.method1.return_value.method2.return_value.method3
    >>> method3.return_value = 'some value'
    >>> assertEqual('some value', my_dingus.method1().method2().method3(1, 2))
    >>> assert method3.calls('()', 1, 2).once()

::

    >>> # fudge
    >>> @fudge.test
    ... def test():
    ...     my_fake = fudge.Fake()
    ...     (my_fake
    ...      .expects('method1')
    ...      .returns_fake()
    ...      .expects('method2')
    ...      .returns_fake()
    ...      .expects('method3')
    ...      .with_args(1, 2)
    ...      .returns('some value'))
    ...     assertEqual('some value', my_fake.method1().method2().method3(1, 2))
    ...
    >>> test()


Mocking a context manager
~~~~~~~~~~~~~~~~~~~~~~~~~

Examples for mock, Dingus and fudge only (so far):

.. doctest::

    >>> # mock
    >>> my_mock = mock.MagicMock()
    >>> with my_mock:
    ...     pass
    ...
    >>> my_mock.__enter__.assert_called_with()
    >>> my_mock.__exit__.assert_called_with(None, None, None)

::


    >>> # Dingus (nothing special here; all dinguses are "magic mocks")
    >>> my_dingus = dingus.Dingus()
    >>> with my_dingus:
    ...     pass
    ...
    >>> assert my_dingus.__enter__.calls()
    >>> assert my_dingus.__exit__.calls('()', None, None, None)

::

    >>> # fudge
    >>> my_fake = fudge.Fake().provides('__enter__').provides('__exit__')
    >>> with my_fake:
    ...     pass
    ...


Mocking the builtin open used as a context manager
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example for mock only (so far):

.. doctest::

    >>> # mock
    >>> my_mock = mock.MagicMock()
    >>> with mock.patch('__builtin__.open', my_mock):
    ...     manager = my_mock.return_value.__enter__.return_value
    ...     manager.read.return_value = 'some data'
    ...     with open('foo') as h:
    ...         data = h.read()
    ...
    >>> data
    'some data'
    >>> my_mock.assert_called_once_with('foo')

*or*:

.. doctest::

    >>> # mock
    >>> with mock.patch('__builtin__.open') as my_mock:
    ...     my_mock.return_value.__enter__ = lambda s: s
    ...     my_mock.return_value.__exit__ = mock.Mock()
    ...     my_mock.return_value.read.return_value = 'some data'
    ...     with open('foo') as h:
    ...         data = h.read()
    ...
    >>> data
    'some data'
    >>> my_mock.assert_called_once_with('foo')

::

    >>> # Dingus
    >>> my_dingus = dingus.Dingus()
    >>> with dingus.patch('__builtin__.open', my_dingus):
    ...     file_ = open.return_value.__enter__.return_value
    ...     file_.read.return_value = 'some data'
    ...     with open('foo') as h:
    ...         data = f.read()
    ...
    >>> data
    'some data'
    >>> assert my_dingus.calls('()', 'foo').once()

::

    >>> # fudge
    >>> from contextlib import contextmanager
    >>> from StringIO import StringIO
    >>> @contextmanager
    ... def fake_file(filename):
    ...     yield StringIO('sekrets')
    ...
    >>> with fudge.patch('__builtin__.open') as fake_open:
    ...     fake_open.is_callable().calls(fake_file)
    ...     with open('/etc/password') as f:
    ...         data = f.read()
    ...
    fake:__builtin__.open
    >>> data
    'sekrets'