gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:54:41 25 4
gpt4 key购买 nike

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

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

最佳答案

好的,经过更多的搜索,我弄清楚了如何将标准输出从我的函数绑定(bind)到一个变量。然后,使用 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)]'

这让我成功通过了测试。

关于python - 在 Python 中,测试函数的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29686331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com