Change in vdsm[master]: test: Use mock module for testing

edwardh at redhat.com edwardh at redhat.com
Mon Mar 28 16:27:04 UTC 2016


Edward Haas has posted comments on this change.

Change subject: test: Use mock module for testing
......................................................................


Patch Set 1:

(1 comment)

https://gerrit.ovirt.org/#/c/55342/1/lib/vdsm/compat.py
File lib/vdsm/compat.py:

Line 50:     from unittest import mock
Line 51:     mock
Line 52: except ImportError:  # py2
Line 53:     import mock
Line 54:     mock
> When using py.test, there is not reason to use another solution for monkeyp
IMO we should use a solution that answers all requirements and has features we need. If there is a standard library that answer all needs, we do not need to use a special tool than limits us to py.test (someone may want to change py.test to super.test in the future)

You can create a fake object and use it as you do now, its just not something I would recommend one to do, a unit test should check one scenario, no several. Logic inside a mock increases maintenance cost. But this is not relevant here.
If you want to use a fake object with mock, you do this:
>>> fake = lambda value: value + 1
>>> mock = Mock(side_effect=fake)
>>> mock(3)
4
>>> mock(-8)
-7

Or this:
>>> from io import StringIO
>>> def foo():
...     print('Something')
...
>>> @patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
...     foo()
...     assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()

There are endless options...
It solved for me a few requirements which I could not with the monkeypath:
- There is no need to import the dependency module which is used in the production code. Just mock it and its methods in the test file.
- It mocks at the usage point and not at the source, allowing to mock the same object in two different scopes differently.
- The created mock mimics the mocked object signature by default, so input type is validated.
- The fact that we do not need a special fake object in most cases is an advantage IMO.


-- 
To view, visit https://gerrit.ovirt.org/55342
To unsubscribe, visit https://gerrit.ovirt.org/settings

Gerrit-MessageType: comment
Gerrit-Change-Id: I1c0af7baab7c35a2617bd60a62a0b1534e5f8894
Gerrit-PatchSet: 1
Gerrit-Project: vdsm
Gerrit-Branch: master
Gerrit-Owner: Edward Haas <edwardh at redhat.com>
Gerrit-Reviewer: Dan Kenigsberg <danken at redhat.com>
Gerrit-Reviewer: Edward Haas <edwardh at redhat.com>
Gerrit-Reviewer: Jenkins CI
Gerrit-Reviewer: Nir Soffer <nsoffer at redhat.com>
Gerrit-Reviewer: Ondřej Svoboda <osvoboda at redhat.com>
Gerrit-Reviewer: Petr Horáček <phoracek at redhat.com>
Gerrit-Reviewer: Piotr Kliczewski <piotr.kliczewski at gmail.com>
Gerrit-Reviewer: Yaniv Bronhaim <ybronhei at redhat.com>
Gerrit-Reviewer: gerrit-hooks <automation at ovirt.org>
Gerrit-HasComments: Yes


More information about the vdsm-patches mailing list