2013-09-26 99 views
1

我試圖寫一個隨機輸入數字遊戲了一些測試,但不太清楚如何進行的。Nosetests - 猜數字遊戲

我從http://inventwithpython.com/chapter4.html

以下Python的遊戲與文件test_guess.py

from unittest import TestCase 
import pexpect as pe 

import guess as g 

class GuessTest(TestCase): 
    def setUp(self): 
     self.intro = 'I have chosen a number from 1-10' 
     self.request = 'Guess a number: ' 
     self.responseHigh = "That's too high." 
     self.responseLow = "That's too low." 
     self.responseCorrect = "That's right!" 
     self.goodbye = 'Goodbye and thanks for playing!' 

    def test_main(self): 
     #cannot execute main now because it will 
     #require user input 
     from guess import main 

    def test_guessing_hi_low_4(self): 
     # Conversation assuming number is 4 
     child = pe.spawn('python guess.py') 
     child.expect(self.intro,timeout=5) 
     child.expect(self.request,timeout=5) 
     child.sendline('5') 
     child.expect(self.responseHigh,timeout=5) 
     child.sendline('3') 
     child.expect(self.responseLow,timeout=5) 
     child.sendline('4') 
     child.expect(self.responseCorrect,timeout=5) 
     child.expect(self.goodbye,timeout=5) 

    def test_guessing_low_hi_4(self): 
     # Conversation assuming number is 4 
     child = pe.spawn('python guess.py') 
     child.expect(self.intro,timeout=5) 
     child.expect(self.request,timeout=5) 
     child.sendline('3') 
     child.expect(self.responseLow,timeout=5) 
     child.sendline('5') 
     child.expect(self.responseHigh,timeout=5) 
     child.sendline('4') 
     child.expect(self.responseCorrect,timeout=5) 
     child.expect(self.goodbye,timeout=5) 

intro = 'I have chosen a number from 1-10' 
request = 'Guess a number: ' 
responseHigh = "That's too high." 
responseLow = "That's too low." 
responseCorrect = "That's right!" 
goodbye = 'Goodbye and thanks for playing!' 


def main(): 
    print(intro) 
    user_input = raw_input(request) 
    print(responseHigh) 
    print(request) 
    user_input = raw_input(request) 
    print(responseLow) 
    user_input = raw_input(request) 
    print(responseCorrect) 
    print(goodbye) 

if __name__ == '__main__': 
    main() 

不能確定guess.py文件如何開始測試繼續用if語句編寫幾個測試來測試值是低還是高。我被告知嘗試像optparse這樣的命令行開關來傳遞數字,但不知道如何做到這一點。

有點新的人與Python,任何指導或援助,將不勝感激。

回答

0

爲了在nosetests中執行命令行解析,您必須執行類似於this的操作(至少這是我必須做的),即創建一個插件,讓您可以訪問命令行參數nosetests。一旦你添加了給你命令行參數的插件,創建一個可以利用傳入的參數的測試會非常容易。

from test_args import case_options 

class GuessTest(TestCase): 
... 

    def test_guessing(self): 
     # Conversation assuming number is 4 
     if case_options.number < 4: 
      # Do something 
     elif case_option.number > 4: 
      # Do some other test 
     else: 
      # Do the final test 

這有道理嗎?我可能會誤解你想要做的事情,如果我願意,只要讓我知道,並希望我們能夠清除它。