In writing unit tests for my application, I have always been using the @mock.patch
and @patch.object
decorators. But now, for some unit tests when I use the decorator, I receive an error 'TypeError: staticmethod object is not an iterator'.
But with the same code, if I use mock.patch.object
or mock.patch.object
, everything works just fine.
For example, in my test class I have this method:
@staticmethod
def my_mock():
...do something
When I try the following unit test
@mock.patch('mypackage.mymodule.my_method', side_effect=my_mock)
def test_something(self, my_method_mocked):
...test something
I receive the error message stated before 'TypeError: staticmethod object is not an iterator'.
But when I try this way
def test_something(self):
with patch.object(mymodule, "my_method") as mocked_method:
mocked_method.side_effect = self.my_mock
...test something
then everything works perfectly.
I've read the Python documentation about mock and unit tests, but I couldn't find any explanation for this behavior.
What is the difference between using the decorator pattern and the with pattern? Where I can find more about this?
Just to be more clear, this my code structure:
class TestClass(unittest.TestCase):
@staticmethod
def my_mock():
...mock
return service
# doesn't work
@mock.patch('mypackage.mymodule.my_method', side_effect=my_mock)
def test_something(self, my_method_mocked):
...test something
# work
def test_something(self):
with patch.object(mymodule, "my_method") as mocked_method:
mocked_method.side_effect = self.my_mock
...test something
That's why I can't do TestClass.my_mock
. If I do, I get a reference error.