A Python Mocking and Patching Library for Testing
>>> from mock import Mock >>> func = Mock(return_value="Hello, mock!") >>> func() 'Hello, mock!'
...Create all attributes and methods (dynamically) as you access them
>>> from mock import Mock >>> func = Mock() >>> hasattr(func, 'foo') True
...Keep track of how they are used
func = Mock() assert func.called Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError func() func.assert_called_with() func(1, 2, 3) func.assert_called_with(1, 2, 3) func('foo', bar='baz') args, kwargs = func.call_args_list[2]
...can act like other functions
sumMock = Mock(side_effect=sum) total = sumMock([1,2,4]) assert total == 7 sumMock.assert_called_once_with([1, 2, 4])
Use patch for context.
def foo(): print 'Hello, mock!' with patch('sys.stdout', new_callable=StringIO) as stdout: foo() assert stdout.getvalue() == 'Hello, mock!'
patch decorators help, too.
def foo(): print 'Hello, mock!' @patch('sys.stdout', new_callable=StringIO) def test(stdout): foo() assert stdout.getvalue() == 'Hello, mock!\n'
delorean.py:
import datetime def travel(mph=None): return datetime.date.today()
testBackToTheFuture.py:
@patch.object(delorean, 'datetime', spec=datetime) def testDelorean(datetimeMock): datetimeMock.date.today.return_value = \ datetime.date(1955, 11, 5) date = delorean.travel(mph=88) assert date.strftime('%b %d %Y').upper() == 'NOV 05 1955'
@patch.object(Foo, 'baz') def foo(my_mocked_func): my_mocked_func.return_value = "Hello, mock!" fooInstance = Foo() result = fooInstance.bar() assert isinstance(fooInstance, Foo) assert result == "Hello, mock!" my_mocked_func.assert_called_once_with()
@patch.object(Foo, 'baz') def foo(my_mocked_func): my_mocked_func.return_value = "Hello, mock!"
fooInstance = Foo() result = fooInstance.bar()
assert isinstance(fooInstance, Foo) assert result == "Hello, mock!" my_mocked_func.assert_called_once_with()
See me.