Johnnysweb is what you need to do, but instead of riding yourself, you can import and use mock . Mock is specifically designed for unit testing and makes it extremely easy to do what you are trying to do. It is built into Python 3.3.
For example, if you want to run unit test, which replaces the os.path.isfile file and always returns True:
try: from unittest.mock import patch except ImportError: from mock import patch class SomeTest(TestCase): def test_blah(): with patch("os.path.isfile", lambda x: True): self.assertTrue(some_function("input"))
This can save a lot of template code, and it is quite readable.
If you need something more complex, for example, replacing supbroccess.check_output, you can create a simple helper function:
def _my_monkeypatch_function(li): x,y = li[0], li[1] if x == "Reavers": return "Gorram" if x == "Inora": return "Shiny!" if x == y: return "The Ballad of Jayne" def test_monkey(): with patch("subprocess.check_output", _my_monkeypatch_function): assertEquals(subprocess.check_output(["Mudder","Mudder"]), "The Ballad of Jayne")
source share