Fix Python – Using python’s mock patch.object to change the return value of a method called within another method

Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods I’m testing) to returned my specified variables each time it is called. For example:
class Foo:
def method_1():
results = uses_some_other_method()
def method_n(….

Fix Python – Mocking a function to raise an Exception to test an except block

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 Exceptio….

Fix Python – Mocking a class: Mock() or patch()?

I am using mock with Python and was wondering which of those two approaches is better (read: more pythonic).
Method one: Just create a mock object and use that. The code looks like:
def test_one (self):
mock = Mock()
mock.method.return_value = True
self.sut.something(mock) # This should called mock.method and checks the result.

Fix Python – Assert a function/method was not called using Mock

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 followin….

Fix Python – How to mock an import

Module A includes import B at its top. However under test conditions I’d like to mock B in A (mock A.B) and completely refrain from importing B.
In fact, B isn’t installed in the test environment on purpose.
A is the unit under test. I have to import A with all its functionality. B is the module I need to mock. But how can I mock B within A and s….

Fix Python – Mocking python function based on input arguments

We have been using Mock for python for a while.
Now, we have a situation in which we want to mock a function
def foo(self, my_param):
#do something here, assign something to my_result
return my_result

Normally, the way to mock this would be (assuming foo being part of an object) = MagicMock(return_value=”mocked!”)

Even, if i ca….