【问题标题】:Python test whole scriptPython测试整个脚本
【发布时间】:2016-04-12 12:17:46
【问题描述】:

我有一个 Python 脚本。我使用unittest 进行测试,但是如何测试整个脚本。

我的想法是这样的:

def test_script(self):
    output=runScript('test.py --a 5 --b 3')
    self.assertEqual(output, '8') 

test.py 接受参数 a 和 b 并打印 a+b,在本例中为 8

【问题讨论】:

    标签: python unit-testing python-3.x testing automated-tests


    【解决方案1】:

    您可以使用subprocess 库来调用脚本并捕获输出。

    import subprocess
    
    p = subprocess.Popen(
        ['./test.py', '--a', ...],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    
    print p.stdout.read()
    

    【讨论】:

      【解决方案2】:

      不确定这是你想要的,使用 python unittest 来结束黑盒测试

      import unittest # install and import
      

      将您的测试包装在 TestCase 中

      class ScriptTest(unittest.TestCase):
          def test_script(self):
              output=runScript('test.py --a 5 --b 3')
              self.assertEqual(output, '8')
      

      将测试用例添加到单元测试

      if __name__ == '__main__':
          suite = unittest.TestLoader().loadTestsFromTestCase(ScriptTest)
          unittest.TextTestRunner(verbosity=2).run(suite)
      

      【讨论】:

        猜你喜欢
        • 2011-08-23
        • 2019-04-21
        • 2014-05-26
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多