I donโt know if this is the best way, but I usually use try ... finally when I do this in tests to establish subsequent changes during each test.
A brief example:
class TestRawInput(unittest.TestCase): def test_raw_input(self): orig_raw_input = raw_input try: raw_input = lambda _: 'Alice' self.assertEquals(raw_input(), 'Alice') finally: raw_input = orig_raw_input
An alternative would be to create a context manager for this if this is a common operation in tests.
source share