在Python,测试一个函数的标准输出

In Python, testing the standard output of a function

我一直在尝试编写一个测试(使用 unittest)来测试函数的输出。 函数如下:

def main():
    arg_pressent = len(sys.argv)
    if arg_pressent < 2:
        print "usage: ./pyPeerChat [IP ADDRESS of pc] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]"
    else: 
          IP = str(sys.argv[1])
          connect.main(IP)

if __name__ == '__main__':
     main()

因此,我的测试需要测试这样一个事实:当此函数自行运行(未传递任何参数)时,它会打印 'usage: ./pyPeerChat [IP ADDRESS of pc] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]'.

到目前为止,我目前一直在尝试实施的测试是:

import myModuleChat
from io import StringIO
import unittest
from mock import patch

def main():
     Testmain.test_main_prints_without_ARGs()

class TestMain(unittest.TestCase):
     def test_main_prints_without_ARGs(self):
          expected_print = 'usage: ./pyPeerChat [IP ADDRESS of Bootpeer] / [0 (if the network is not known. This will assume that this peer will be the #start of a new network)]'
          with patch('sys.stdout', new=StringIO()) as fake_out:
               pyPeerChat.main()
          self.assertEqual(fake_out.getvalue(), expected_print)

if __name__ == '__main__':
     test_program = unittest.main(verbosity=0, buffer=False, exit=False)

但是,我一直无法让这个测试顺利通过。测试失败,我得到一个错误。以下是测试的完整输出,错误为:

======================================================================
ERROR: test_main_prints_without_ARGs (__main__.TestMain)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "testpyPeerChat.py", line 24, in test_main_prints_without_ARGs
    pyPeerChat.main()
  File "/home/peer-node/Testing/P2PChat/source/pyPeerChat.py", line 47, in main
    print "usage: ./pyPeerChat [IP ADDRESS of Bootpeer] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]"
TypeError: unicode argument expected, got 'str'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

我完全不确定这个错误是什么意思,因为代码工作正常。有没有更简单的方法来编写我需要的测试,或者有什么方法可以修复我的测试?

好的,经过更多的搜索,我弄清楚了如何将标准输出从我的函数绑定到一个变量。然后,使用 assertEqual(),我能够将它与 'expected' 字符串进行比较:

from pyPeerChat import main
from StringIO import StringIO
import unittest


class TestFoo(unittest.TestCase):
    def test_output_without_args(self):
        out = StringIO()
            main(out=out)
            output = out.getvalue().strip()
            expected = 'usage: ./pyPeerChat [IP ADDRESS of Bootpeer] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]'
        self.assertEqual(output, expected)



if __name__ == '__main__':
    unittest.main() 

#'usage: ./pyPeerChat [IP ADDRESS of Bootpeer] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]'

这让我成功通过了测试。