Any way to reset a mocked method to its original state? – Python Mock – mock 1.0b1

You can use mock.patch as a decorator or a context manager: from mock import patch, MagicMock @patch(‘myClass.A’, MagicMock(return_value=”CPU”)) def test(self): pass or: def test(self): with patch(‘myClass.A’, MagicMock(return_value=”CPU”)): pass If you don’t supply a mock object to patch then it will provide an autospecced mock that you can modify: @patch(‘myClass.A’) def test(self, mock_A): mock_A.return_value=”CPU” pass or: … Read more

Better way to mock class attribute in python unit test

base.Base.assignment is simply replaced with a Mock object. You made it a descriptor by adding a __get__ method. It’s a little verbose and a little unnecessary; you could simply set base.Base.assignment directly: def test_empty(self): Base.assignment = {} assert len(Base().assignment.values()) == 0 This isn’t too safe when using test concurrency, of course. To use a PropertyMock, … Read more

Mocking async call in python 3.5

The solution was actually quite simple: I just needed to convert __call__ method of mock into coroutine: class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) This works perfectly, when mock is called, code receives native coroutine Example usage: @mock.patch(‘my.path.asyncio.sleep’, new_callable=AsyncMock) def test_stuff(sleep): # code

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute: barMock.side_effect = HttpError(mock.Mock(status=404), ‘not found’) Additional keyword arguments to Mock() are set as attributes on the resulting object. I put your foo and bar definitions in a my_tests module, … Read more

Assert a function/method was not called using Mock

This should work for your case; assert not my_var.called, ‘method should not have been called’ Sample; >>> mock=Mock() >>> mock.a() <Mock name=”mock.a()” id=’4349129872′> >>> assert not mock.b.called, ‘b was called and should not have been’ >>> assert not mock.a.called, ‘a was called and should not have been’ Traceback (most recent call last): File “<stdin>”, line … Read more

Python Mocking a function from an imported module

When you are using the patch decorator from the unittest.mock package you are patching it in the namespace that is under test (in this case app.mocking.get_user_name), not the namespace the function is imported from (in this case app.my_module.get_user_name). To do what you describe with @patch try something like the below: from mock import patch from … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)