2017-09-17 75 views
0

所以奇怪的問題,cmd模塊打破了cmdloop()(主sudo命令行循環),每當我返回一個返回消息。通過單元測試,assertequal方法僅適用於返回的內容。我怎樣才能解決這個問題?哈克單元測試cmd模塊沒有返回字符串

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

幾個選項春天的腦海:

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

我感到猶豫,使用內置的框架,非但是我會保持開放的心態。另外,我確實嘗試了打印到標準輸出,但沒有運氣 – Nova

+0

我也有點猶豫是否也開始使用它,但真正意識到使用pytest的次數越多,測試的樂趣就越多。我認爲最大的好處是測試是如何輕鬆地讀取其他框架,尤其是單元測試。很多巨大的項目已經從單元測試/鼻子等切換到pytest:Mozilla,scipy等。給它一個鏡頭。 :)你可以直接用你的測試編寫測試,或者將它用作單元測試的跑步者。 – rjsberry

+0

好吧,我會放棄它!謝謝一堆 – Nova