I was considering reassigning some functions from a standard library module in my testing suite, however I have found that doing so has a global effect (when I expected them to only have an effect locally). For example:
import time
def test():
time.sleep = "hello" #woah there! time is mutable so this won't just apply locally!
print time.sleep #prints <built-in function sleep>
test()
print time.sleep #prints hello (!)
Must I be revert time.sleep to what it was before at the end of test()?
Is this something which is discouraged… How should I be doing this kind of testing?
If you have an object that you want to test against in this fashion you should use dependency injection and mocking. Pass in an object (in this case time) from the ‘top’ of the program. then you can unit-test individual functions or objects by passing in a mocked-out version.
Example: