How do I test the STDOUT output of a Python script with a testing framework like doctest, unittest, nose, etc? For example, say running my script "todo.py --list" shou
I see two ways :
Redirect stdout during the unittest:
class YourTest(TestCase):
def setUp(self):
self.output = StringIO()
self.saved_stdout = sys.stdout
sys.stdout = self.output
def tearDown(self):
self.output.close()
sys.stdout = self.saved_stdout
def testYourScript(self):
yourscriptmodule.main()
assert self.output.getvalue() == "My expected ouput"
Use a logger for your outputs and listen to it in your test.