I'm using python's unittest.mock to do some testing in a Django app. I want to check that a class is called, and that a method on its instance is also called.
For example, given this simplified example code:
# In project/app.py
def do_something():
obj = MyClass(name='bob')
return obj.my_method(num=10)
And this test to check what's happening:
# In tests/test_stuff.py
#patch('project.app.MyClass')
def test_it(self, my_class):
do_something()
my_class.assert_called_once_with(name='bob')
my_class.my_method.assert_called_once_with(num=10)
The test successfully says that my_class is called, but says my_class.my_method isn't called. I know I'm missing something - mocking a method on the mocked class? - but I'm not sure what or how to make it work.
Your second mock assertion needs to test that you are calling my_method on the instance, not on the class itself.
Call the mock object like this,
my_class().my_method.assert_called_once_with(num=10)
^^
A small refactoring suggestion for your unittests to help with other instance methods you might come across in your tests. Instead of mocking your class in each method, you can set this all up in the setUp method. That way, with the class mocked out and creating a mock object from that class, you can now simply use that object as many times as you want, testing all the methods in your class.
To help illustrate this, I put together the following example. Comments in-line:
class MyTest(unittest.TestCase):
def setUp(self):
# patch the class
self.patcher = patch('your_module.MyClass')
self.my_class = self.patcher.start()
# create your mock object
self.mock_stuff_obj = Mock()
# When your real class is called, return value will be the mock_obj
self.my_class.return_value = self.mock_stuff_obj
def test_it(self):
do_something()
# assert your stuff here
self.my_class.assert_called_once_with(name='bob')
self.mock_stuff_obj.my_method.assert_called_once_with(num=10)
# stop the patcher in the tearDown
def tearDown(self):
self.patcher.stop()
To provide some insight on how this is put together, inside the setUp method we will provide functionality to apply the patch across multiple methods as explained in the docs here.
The patching is done in these two lines:
# patch the class
self.patcher = patch('your_module.MyClass')
self.my_class = self.patcher.start()
Finally, the mock object is created here:
# create your mock object
self.mock_stuff_obj = Mock()
self.my_class.return_value = self.mock_stuff_obj
Now, all your test methods can simply use self.my_class and self.mock_stuff_obj in all your calls.
This line
my_class.my_method.assert_called_once_with(num=10)
will work if my_method is a class method.
Is it the case?
Otherwise, if my_method is just an normal instance method, then you will need to refactor the function do_something to get hold of the instance variable obj
e.g.
def do_something():
obj = MyClass(name='bob')
return obj, obj.my_method(num=10)
# In tests/test_stuff.py
#patch('project.app.MyClass')
def test_it(self, my_class):
obj, _ = do_something()
my_class.assert_called_once_with(name='bob')
obj.my_method.assert_called_once_with(num=10)
Related
I'm using the mock Python module for performing my tests.
There are times when I'm mocking a class, however I just want to mock some of its methods and properties, and not all of them.
Suppose the following scenario:
# module.py
class SomeClass:
def some_method(self):
return 100
def another_method(self):
return 500
# test.py
class Tests(unittest.TestCase):
#patch('module.SomeClass')
def test_some_operation(self, some_class_mock):
some_class_instance = some_class_mock.return_value
# I'm mocking only the some_method method.
some_class_instance.some_method.return_value = 25
# This is ok, the specific method I mocked returns the value I wished.
self.assertEquals(
25,
SomeClass().some_method()
)
# However, another_method, which I didn't mock, returns a MagicMock instance
# instead of the original value 500
self.assertEquals(
500,
SomeClass().another_method()
)
On the code above, once I patch the SomeClass class, calls to methods whose return_values
I didn't exlicitely set will return MagicMock objects.
My question is: How can I mock only some of a class methods but keep others intact?
There are two ways I can think of, but none of them are really good.
One way is to set the mock's method to the original class method, like this:
some_class_instance.another_method = SomeClass.another_method
This is not really desirable because the class may have a lot of methods and properties to
"unmock".
Another way is to patch each method I want explicitly, such as:
#patch('module.SomeClass.some_method')
def test_some_operation(self, some_method_mock):
But this doesn't really work if I want to mock the class itself, for mocking calls to the
initializer for example. The code below would override all SomeClass's methods anyway.
#patch('module.SomeClass.some_method')
#patch('module.SomeClass')
def test_some_operation(self, some_class_mock, some_method_mock):
Here is a more specific example:
class Order:
def process_event(self, event, data):
if event == 'event_a':
return self.process_event_a(data)
elif event == 'event_b':
return self.process_event_b(data)
else:
return None
def process_event_a(self, data):
# do something with data
def process_event_b(self, data):
# do something different with data
In this case, I have a general method process_event which calls a specific processing event depending on the supplied event.
I would like to test only the method process_event. I just want to know if the proper specific event is called depending on the event I supply.
So, in my test case what I want to do is to mock just process_event_a and process_event_b, call the original process_event with specific parameters, and then assert either process_event_a or process_event_b were called with the proper parameters.
Instead of patching the whole class, you must patch the object. Namely, make an instance of your class, then, patch the methods of that instance.
Note that you can also use the decorator #patch.object instead of my approach.
class SomeClass:
def some_method(self):
return 100
def another_method(self):
return 500
In your test.py
from unittest import mock
class Tests(unittest.TestCase):
def test_some_operation(self):
some_class_instance = SomeClass()
# I'm mocking only the some_method method.
with mock.patch.object(some_class_instance, 'some_method', return_value=25) as cm:
# This is gonna be ok
self.assertEquals(
25,
SomeClass().some_method()
)
# The other methods work as they were supposed to.
self.assertEquals(
500,
SomeClass().another_method()
)
I cannot instantiate an object because it is an abstract class, so I have to use mocking in order to test my code.
I have been told this is best done by creating a new mock class.
class MockMyClass(MyClass):
def my_first_function(...):
The idea is that I then instantiate a MockMyClass object, where I can test private function in that.
I have read the python guide and researched other stack questions. Here, the theory behind mock has been well explained. Unfortunately, I am still lost with how mocking can be used in a large unittest for multiple functions. For instance:
If I have a class, from which other classes in the main code inherit functions from. This can take the form:
class SharedFunctions(AnotherClass):
first_function():
#do some important calculations to generate stuff.#
self.stuff = first_function_attribute_stuff
return returned_first_stuff
second_functions(returned_stuff)
returned_second_stuff = self.stuff + returned_first_stuff
return returned_second_stuff
and where the class SharedFunctions also inherits from another class (noting the abstract method) of the form:
class AnotherClass():
#abc.abstractmethod
def one_important_universal_function(...):
pass
I have tried to construct a unittest for the SharedFunctions piece of code.
This is what I have tried so far:
class MockSharedFunctions(SharedFunctions):
def first_function(...):
self.stuff = some value
returned_first_stuff = given some other value
return returned_first_stuff
def second_function
returned_second_stuff = another value.
return returned_second_stuff
class TestSharedFunctions(unittest.TestCase):
def test_first_function(self):
# insert code #
self.assertTrue(True)
def test_second_function(self):
# insert code #
self.assetEqual(output, expected)
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
Where insert code has been a number of various attempts to use mocking. However, I have not come across a clear example of how mock functions can be used to replace other functions, or a confirmation that this will work.
Thank you for any help.
A common issue is too over complicate the use of mocking functions. You can almost treat them like another class method. In your case, the abstractmethod decorator is probably generating the confusion.
This is something close to what you might need.
class MockSharedFunctions(SharedFunctions):
def one_important_universal_function(**args):
return 0
class TestSharedFunctions(unittest.TestCase):
def test_first_function(self):
mock = MockSharedFunctions()
mock_output = firstfunction(**args)
mock_stuff = mock.stuff
self.assertTrue(True)
self.assetEqual(mock_output, expected)
self.assetEqual(mock_stuff, expected)
def test_second_function(self):
mock = MockSharedFunctions()
mock.stuff = some_value
mock_output = second_function(**args)
self.assetEqual(mock_output, expected)
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
Here, in the MockSharedFunctions you are already inheriting SharedFunctions. As one_important_universal_function is an abstract method, it needs to be defined.
I have a method foo in Python that creates a Service class. I want to mock the Service class but when I run the test, it still attempts to instantiate the class. Here is the simplified version of my setup:
class Service:
def __init__(self, service):
self.service_stuff = service
def run_service(self):
do_service_stuff()
def foo:
new_service = Service("bar")
new_service.run_service()
Then my unit test:
#patch('mymodule.service_file.Service')
def test_foo(self, mock_service):
foo()
I would like to run foo, but have it use my mocked object instead of creating an actual Service instance, but instead, when I run it, it tries to instantiate an actual instance of Service() and runs foo() as usual even though it seems to recognize the string signature I've put into patch. Why is this happening?
Figured it out: The patch reference to the class had to be of its imported name in the method itself rather than the original class, similar to https://stackoverflow.com/a/32461515/4234853
So the patch should look like:
#patch('mymodule.foo_file.Service')
instead of trying to patch the class directly.
In this case, it might be easier to make your function more test-friendly:
def foo(cls=Service):
new_service = cls("bar")
new_service.run_service()
Then your test doesn't need to patch anything.
def test_foo(self):
mock_service = Mock()
foo(mock_service)
I'm trying to use #patch decorators and mock objects to test the behavior of my code consuming some libraries. Unfortunately, I can't see any way to do what I'm trying to do using only decorators, and it seems like I should be able to. I realize that generally I should be more concerned with the return value of a method than the particular sequence of calls it makes to a library, but it's very difficult to write a test to compare one image to another.
I thought that maybe I could create instances of my mock objects and then use #patch.object(...) but that didn't work, and obviously #patch('MockObject.method') will only mock class methods. I can get the code to work by using with patch.object(someMock.return_value, 'method') as mockName but this makes my tests messy.
from some.module import SomeClass
class MockObject:
def method(self):
pass
class TestClass:
#patch('SomeClass.open', return_value=MockObject())
#patch('??????.method') # I can't find any value to put here that works
def test_as_desired(self, mockMethod, mockOpen):
instance = SomeClass.open()
instance.method()
mockOpen.assert_called_once()
mockMethod.assert_called_once()
#patch('SomeClass.open', return_value=MockObject())
def test_messy(self, mockOpen):
with patch.object(mockOpen.return_value, 'method') as mockMethod:
instance = SomeClass.open()
instance.method()
mockOpen.assert_called_once()
mockMethod.assert_called_once()
I think you are overcomplicating things:
import unittest.mock
#unittest.mock.patch.object(SomeClass, 'open', return_value=mock.Mock())
def test_as_desired(self, mock_open):
instance = SomeClass.open() # SomeClass.open is a mock, so its return value is too
instance.method()
mock_ppen.assert_called_once()
instance.method.assert_called_once()
I want to test a method but mock out other methods that it calls. I created this simple example that should illustrate the concept:
class myClass():
def one_method(self):
print "hey"
def two_deep(self):
self.one_method()
def three_deep(self):
self.two_deep()
I was using a python mock framework called Mox and wrote the following code to do this:
def test_partial(self):
self_mox = mox.Mox()
some_object = myClass()
## 1. make your mock
my_mock = mox.MockObject(some_object)
my_mock.one_method().AndReturn('some_value')
self_mox.ReplayAll()
ret = my_mock.three_deep() ## *** SEE NOTE BELOW called "comment":
self_mox.VerifyAll()
Comment:
I thought that if I called this mock on a method that hadn't been overwritten, then the mock would default to the original code, then I could get the chain of calls that I want, with the last call being replaced... but it doesn't do this. I can't figure out how to embed a mock object inside a test object that doesn't have an inserting method.
I looked into Partial Mocks and Chained Mocks to solve this, but I couldn't find a way to pull this off.
Thanks for any help :)
-- Peter
Check documentation for StubOutWithMock:
https://code.google.com/p/pymox/wiki/MoxDocumentation#Stub_Out
https://code.google.com/p/pymox/wiki/MoxRecipes#Mock_a_method_in_the_class_under_test.
So what you needed is:
def test_partial(self):
self_mox = mox.Mox()
# Create the class as is, instead of doing mock.
some_object = myClass()
# Stub your particular method using the StubOutWithMock.
m.StubOutWithMock(some_object, "one_method")
some_object.one_method().AndReturn('some_value')
self_mox.ReplayAll()
ret = some_object.three_deep()
self_mox.UnsetStubs()
self_mox.VerifyAll()