Hack to unittest cmd module而不返回字符串

时间:2017-09-17 00:49:47

标签: python unit-testing cmd

这个奇怪的问题,只要我返回一条返回消息,cmd模块就会破坏cmdloop()(主sudo命令行循环)。通过单元测试,assertequal方法仅适用于返回的内容。我怎么能绕过这个?

commandline.py

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

unittesting.py

...
def test_cd(self):
        self.assertEqual(CommandPrompt.HelloWorld().do_cd('foo'), '\nnot a directory')

1 个答案:

答案 0 :(得分:1)

我想到了几个选择:

  1. 将您写入的字符串返回给stdout。你提到这会破坏你的主循环 - 这听起来并不像所需的功能。或许可以调查为什么会这样?

  2. 使用pytest单元测试框架及其内置夹具capsys

    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 == ''