Python mock access "real" objects while mocking a module -
is possible access "real" objects while mocking module? i'm trying mock function, throw "real" exceptions, this:
@mock.patch('my_project.requests') def test_foo(self, mock_requests): mock_requests.post = mock.mock(side_effect=requests.connectionerror()) thread = commandthread("command", 3, 2, 0) thread.run() #this exercise requests.post self.assert(thread.was_successful false)
inside commandthread have check like
try: requests.post(url, data=data) except (requests.connectionerror, requests.timeout): self.was_successful = false
however, test fails because exception not caught inside try/except block (when except exception:
works) reason, think, because mocked "namespace" in test case, raise my_project.requests.connectionerror
exception rather proper, requests.connectionerror
original package. somehow possible access/throw "real" exceptions?
this happening because mock overwriting entire requests module in code. here how can debug this:
in code, add this:
try: requests.post('', data='') except (requests.connectionerror, requests.timeout): was_successful = false except exception, err: import pdb pdb.set_trace()
when run test, dropped debugger can take @ happening. if @ catching, see:
(pdb) requests.connectionerror <magicmock name='requests.connectionerror' id='4562438992'>
you catching mock connectionerror because mock patched out entire requests module , feeding in real requests error.
you can fix making mock more specific , overriding post method on requests module:
@mock.patch('my_project.requests.post') def test_foo(self, mock_requests): mock_requests.side_effect = requests.connectionerror() ...
Comments
Post a Comment