我一直在尝试编写一个测试(使用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()


因此,我的测试需要测试以下事实:当此函数单独运行(不传递任何参数)时,它会打印'用法:./pyPeerChat [pc的IP地址] / [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)


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

最佳答案

好的,因此,在进行更多搜索之后,我确定了如何将标准输出从函数绑定到变量。然后,使用assertEqual(),我可以将其与“期望的”字符串进行比较:

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


这使我成功通过了测试。

10-07 15:51
查看更多