Let's say I have a class like this.
class SomeProductionProcess(CustomCachedSingleTon):@classmethoddef 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?
Here is a simple way to do it using mock
import mockdef new_loaddata(cls, *args, **kwargs):# Your custom testing overridereturn 1def 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.