簡體   English   中英

破解單元測試cmd模塊而不返回字符串

[英]Hack to unittest cmd module without returning string

如此奇怪的問題是,每當我返回一條返回消息時,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. 返回您寫入標准輸出的字符串。 您提到了這破壞了您的主循環-聽起來不像所需的功能。 也許調查為什么會這樣?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM