Let's say I have a class like this.
class SomeProductionProcess(CustomCachedSingleTon): @classmethod def loaddata(cls): """ Uses an iterator over a large file in Production for the Data pipeline. """ pass
Now at test time I want to change the logic inside the loaddata()
method. It would be a simple custom logic that doesn't process large data.
How do we supply custom implementation of loaddata()
at testtime using Python Mock UnitTest framework?
The patch() decorators makes it easy to temporarily replace classes in a particular module with a Mock object. By default patch() will create a MagicMock for you. You can specify an alternative class of Mock using the new_callable argument to patch() . Create a new Mock object.
First, we need to import the mock library, so from unittest. mock import Mock . 00:13 This will give you the Mock class, which you can make your mock objects from. I'm going to say mock = Mock() , and then let's just print(mock) so we can see what this Mock object looks like.
Here is a simple way to do it using mock
import mock def new_loaddata(cls, *args, **kwargs): # Your custom testing override return 1 def test_SomeProductionProcess(): with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata): obj = SomeProductionProcess() obj.loaddata() # This will call your mock method
I'd recommend using pytest
instead of the unittest
module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase
-style tests.
To easily mock out a class method with a structured return_value, can use unittest.mock.Mock
.
from unittest.mock import Mock mockObject = SomeProductionProcess mockObject.loaddata = Mock(return_value=True)
EDIT:
Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.
def custom_method(*args, **kwargs): # do custom implementation SomeProductionProcess.loaddata = custom_method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With