I have a python program with a global function that is painful to test (it needs a large dataset to work properly). What is the best way to get around this while testing functions that call it?
I've found that the following works (but it make me feel dirty to use it).
module foo:
def PainLiesHere():
return 4; #guaranteed to be random
module test
import foo
def BlissLiesHere():
return 5
foo.PainLiesHere = BlissLiesHere
# test stuff
Advanced: Mocking in Unit TestIn pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.
mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.
This is a perfectly fine way to do it. As long as you know that BlissLiesHere
does not change the overall behavior of the unit you are testing...
EDIT:
This is what is being done, under all the nice extras they provide, by different kinds of mocking libraries, such as Mock, Mox, etc.
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