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

时间:2015-04-16 21:30:00

标签: python unit-testing testing stdout

我一直在尝试编写测试(使用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(如果网络)不知道。这将假设这个对等体将成为新网络的开始)]'。

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

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)

我不确定这个错误意味着什么,因为代码工作正常。是否有更简单的方法来编写我需要的测试,或者是一种修复测试的方法?

1 个答案:

答案 0 :(得分:0)

好的,经过一番搜索后,我研究了如何将stdout从我的函数绑定到变量。然后,使用assertEqual(),我能够将它与预期的&#39;进行比较。字符串:

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)]'

这使我成功通过测试。