Python单元测试失败

2024-10-03 02:47:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕获命令“wahji-h”的输出。将该输出保存到字符串op中。我有一个保存为wahjiHelp.txt的文本文件,它正是命令“wahji-h”的预期输出。然后我尝试将该文件读入字符串who2。然后,我尝试通过使用断言来比较这两个应该完全相同的字符串,以确保从命令“wahji-h”接收到正确的输出。我正在使用python 2.7。非常感谢您的帮助

运行测试时,我收到以下失败消息: 我可以看出它正在比较的两个字符串之间存在差异。当我在终端中运行“wahji-h”时,输出以“用法:wahji.py[-h]”开始。出于某种原因,当我从该命令捕获该输出并将其保存到字符串op时,它会将输出显示为“用法:wahji[-h]”。它没有添加.py扩展名,我不明白为什么在使用子流程捕获命令的输出时,输出与在终端中实际键入相同的“wahji-h”命令时的输出不完全相同

FAIL: test_help (__main__.HelpTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_wahji_help.py", line 30, in test_help
self.assertEqual(op, who2)
AssertionError: 'usage: wahji [-h] {init,remove,page,build,new} ...\n\noptional arguments:\n  -h, --help            show this help message and exit\n\nwahji commands:\n              The following are possible command line parameters for wahji\n\n  {init,remove,page,build,new}\n                        \n                        \twahji init --help\n                        \twahji remove --help\n                        \twahji page --help\n                        \twahji build --help\n                        \twahji new --help\n' != 'usage: wahji.py [-h] {init,remove,page,build,new} ...\n\noptional arguments:\n  -h, --help            show this help message and exit\n\nwahji commands:\n              The following are possible command line parameters for wahji\n\n  {init,remove,page,build,new}\n                        \n                        \twahji init --help\n                        \twahji remove --help\n                        \twahji page --help\n                        \twahji build --help\n                        \twahji new --help\n'

这是我的密码:

  1 import unittest
  2 import subprocess
  3 import filecmp
  4 import os
  5 import sys
  6 
  7 
  8 class HelpTest(unittest.TestCase):
  9 
 10         def test_help(self):   
 11 
 12                 op = subprocess.Popen(["wahji", "-h"], stdout=subprocess.PIPE).communicate()[0]
 13 
 14                 print op
 15 
 16                 opw = open( 'op1.txt', 'w' )
 17                 opw.write(op)
 18                 opw.close()
 19 
 20                 who = open('wahjiHelp.txt', 'r')
 21                 who2 = who.read()
 22                 who.close()
 23                 print who2
 24 
 25                 # print filecmp.cmp('op1.txt', 'wahjiHelp.txt', shallow = False)
 26 
 27                 op.strip()
 28                 who2.strip()
 29 
 30                 self.assertEqual(op, who2)
 31 
 32                 
 33 
 34 
 35 if __name__ == '__main__':
 36         unittest.main()

Tags: 字符串pyimport命令buildtxtnewinit