python-mock

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

夙愿已清 提交于 2019-11-28 17:21:07
I have a function ( foo ) which calls another function ( bar ). If invoking bar() raises an HttpError , I want to handle it specially if the status code is 404, otherwise re-raise. I am trying to write some unit tests around this foo function, mocking out the call to bar() . Unfortunately, I am unable to get the mocked call to bar() to raise an Exception which is caught by my except block. Here is my code which illustrates my problem: import unittest import mock from apiclient.errors import HttpError class FooTests(unittest.TestCase): @mock.patch('my_tests.bar') def test_foo

Patch __call__ of a function

只愿长相守 提交于 2019-11-28 11:54:35
I need to patch current datetime in tests. I am using this solution: def _utcnow(): return datetime.datetime.utcnow() def utcnow(): """A proxy which can be patched in tests. """ # another level of indirection, because some modules import utcnow return _utcnow() Then in my tests I do something like: with mock.patch('***.utils._utcnow', return_value=***): ... But today an idea came to me, that I could make the implementation simpler by patching __call__ of function utcnow instead of having an additional _utcnow . This does not work for me: from ***.utils import utcnow with mock.patch.object

Mock attributes in Python mock?

烈酒焚心 提交于 2019-11-27 18:16:52
I'm having a fairly difficult time using mock in Python: def method_under_test(): r = requests.post("http://localhost/post") print r.ok # prints "<MagicMock name='post().ok' id='11111111'>" if r.ok: return StartResult() else: raise Exception() class MethodUnderTestTest(TestCase): def test_method_under_test(self): with patch('requests.post') as patched_post: patched_post.return_value.ok = True result = method_under_test() self.assertEqual(type(result), StartResult, "Failed to return a StartResult.") The test actually returns the right value, but r.ok is a Mock object, not True . How do you mock

Can't catch mocked exception because it doesn't inherit BaseException

丶灬走出姿态 提交于 2019-11-27 17:12:58
问题 I'm working on a project that involves connecting to a remote server, waiting for a response, and then performing actions based on that response. We catch a couple of different exceptions, and behave differently depending on which exception is caught. For example: def myMethod(address, timeout=20): try: response = requests.head(address, timeout=timeout) except requests.exceptions.Timeout: # do something special except requests.exceptions.ConnectionError: # do something special except requests

Checking call order across multiple mocks

坚强是说给别人听的谎言 提交于 2019-11-27 14:25:22
问题 I have three functions that I'm trying to test the call order of. Let's say that in module module.py I have the following # module.py def a(*args): # do the first thing def b(*args): # do a second thing def c(*args): # do a third thing def main_routine(): a_args = ('a') b_args = ('b') c_args = ('c') a(*a_args) b(*b_args) c(*c_args) I want to check that b is called after a, and before c. So getting a mock for each of a, b and c is easy: # tests.py @mock.patch('module.a') @mock.patch('module.b'

Mocking async call in python 3.5

徘徊边缘 提交于 2019-11-27 12:00:10
问题 How do I mock async call from one native coroutine to other one using unittest.mock.patch ? I currently have quite an awkward solution: class CoroutineMock(MagicMock): def __await__(self, *args, **kwargs): future = Future() future.set_result(self) result = yield from future return result Then class TestCoroutines(TestCase): @patch('some.path', new_callable=CoroutineMock) def test(self, mock): some_action() mock.assert_called_with(1,2,3) This works but looks ugly. Is there more pythonic way to

Python mock multiple return values

浪尽此生 提交于 2019-11-27 11:16:08
I am using pythons mock.patch and would like to change the return value for each call. Here is the caveat: the function being patched has no inputs, so I can not change the return value based on the input. Here is my code for reference. def get_boolean_response(): response = io.prompt('y/n').lower() while response not in ('y', 'n', 'yes', 'no'): io.echo('Not a valid input. Try again']) response = io.prompt('y/n').lower() return response in ('y', 'yes') My Test code: @mock.patch('io') def test_get_boolean_response(self, mock_io): #setup mock_io.prompt.return_value = ['x','y'] result =

Python Mocking a function from an imported module

巧了我就是萌 提交于 2019-11-27 10:46:36
I want to understand how to @patch a function from an imported module. This is where I am so far. app/mocking.py: from app.my_module import get_user_name def test_method(): return get_user_name() if __name__ == "__main__": print "Starting Program..." test_method() app/my_module/__init__.py: def get_user_name(): return "Unmocked User" test/mock-test.py: import unittest from app.mocking import test_method def mock_get_user(): return "Mocked This Silly" @patch('app.my_module.get_user_name') class MockingTestTestCase(unittest.TestCase): def test_mock_stubs(self, mock_method): mock_method.return

Assert a function/method was not called using Mock

纵然是瞬间 提交于 2019-11-27 10:03:15
问题 I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like mock.assert_called_with and mock.assert_called_once_with , but I didn't find anything like mock.assert_not_called or something related to verify mock was NOT called . I could go with something like the following, though it doesn't seem cool nor pythonic: def test_something: # some actions with patch('something') as my_var: try: # args are not important.

Python Mock object with method called multiple times

吃可爱长大的小学妹 提交于 2019-11-27 06:37:13
I have a class that I'm testing which has as a dependency another class (an instance of which gets passed to the CUT's init method). I want to mock out this class using the Python Mock library. What I have is something like: mockobj = Mock(spec=MyDependencyClass) mockobj.methodfromdepclass.return_value = "the value I want the mock to return" assertTrue(mockobj.methodfromdepclass(42), "the value I want the mock to return") cutobj = ClassUnderTest(mockobj) Which is fine, but "methodfromdepclass" is a parameterized method, and as such I want to create a single mock object where depending on what