Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to supply a mock class method for python unit test?

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?

like image 219
Vineel Avatar asked Jul 26 '16 00:07

Vineel


People also ask

How do you mock a class object in unittest Python?

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.

How do you mock a class instance in Python?

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.


2 Answers

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.

like image 142
Brendan Abel Avatar answered Sep 19 '22 21:09

Brendan Abel


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 
like image 26
Mattew Whitt Avatar answered Sep 19 '22 21:09

Mattew Whitt