这个奇怪的问题,只要我返回一条返回消息,cmd模块就会破坏cmdloop()(主sudo命令行循环)。通过单元测试,assertequal方法仅适用于返回的内容。我怎么能绕过这个?
def do_cd(self, directory): # change directory
'''
syntax 'cd [directory]'
change to [directory]
'''
args = directory.split(' ')
# next 6 lines are cheater proof biz
if args[0] == 'game':
self.stdout.write('\nnot a directory')
return
if os.path.split(os.getcwd())[1] == 'user' and args[0] == '..':
self.stdout.write('\nnot a directory')
return
try:
os.chdir(args[0])
except OSError:
self.stdout.write('\nnot a directory')
return
...
def test_cd(self):
self.assertEqual(CommandPrompt.HelloWorld().do_cd('foo'), '\nnot a directory')
答案 0 :(得分:1)
我想到了几个选择:
将您写入的字符串返回给stdout。你提到这会破坏你的主循环 - 这听起来并不像所需的功能。或许可以调查为什么会这样?
import pytest
def test_cd(capsys):
# given a non-existent dir
# when try to cd to dir
# then print error to stdout
CommandPrompt.HelloWorld().do_cd('foo')
out, err = capsys.readouterr()
assert out == '\nnot a directory.'
assert err == ''