The python "mock" library is the preferred mocking library for python unittests in the Chromium OS source. There still exist many tests that use "mox", but "mock" is preferred for all new tests. python-mock is the standard mocking framework starting in Python 3.3 (imported as unittest.mock).
python-mock is already added to the chroot, but people who run unit tests outside the chroot need to manually install it. Here are the commands to run:
Unlike pymox, python-mock is really easy to extend - no messing with ReplyAll()'s, VerifyAlls(), etc. It's also more pythonic. Here's a quick snippet of running a test with somemodule.func() mocked out:
In the chromite source there is a partial mocking library, located at lib/partial_mock.py. This extends python-mock to allow for writing re-usable mocks. An example is the cros_build_lib_unittest.RunCommandMock class, which can be used to easily simulate command line behavior. Here's a code snippet of a function we want to test:
Here's how we'd test it with the RunCommandMock partial mock:
No mucking with setting up mock CommandResults, or mock RunCommandErrors, or testing for the right redirect_* or error_code_ok=True arguments. The partial mock handles all of that for you by using RunCommand logic directly.
It's also easy to write your own partial mocks that can then be used by other unit tests. Having a corpus of re-usable mocks will make the barrier to testing lower, and will help us get into a more test-driven development workflow.
Thanks for reading, and happy mocking! :)