Testing Python Scripts

后端 未结 5 1452
小蘑菇
小蘑菇 2021-02-14 01:23

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

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 02:22

    I see two ways :

    1. 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"
      
    2. Use a logger for your outputs and listen to it in your test.

提交回复
热议问题