2013-07-23 18 views
1

我遇到了問題,獲取docopt將包含空格的參數解析爲與我的單元測試一起使用的適當字典對象。在單元測試中生成docopt包含空格的解析參數

這是我目前使用構造參數列表docopt解析代碼:

testargs = [] 

def clear_args(): 
    testargs[:] = [] 
    return 

def add_testfiles(file1='defaultfile1.txt', file2='defaultfile2.txt'): 
    clear_args() 
    testargs.append('--debug') 
    testargs.append(file1) 
    testargs.append(file2) 
    return 

def parse_args(optlist): 
    argstr = ' '.join(optlist) 
    return docopt(downpost.__doc__, argv=argstr) 

我寫單元測試有2次測試,分別給予下列參數的代碼:

-t <title> # <title> can be any string (with spaces) inside quotation marks 
"A Filename with Spaces.txt" # any filename as long as it's in quotation marks 

要添加,例如,-t參數,我會做:

def test_exampleunittest(self): 
    add_testfiles() 
    testargs.append('-t "This is the title I want"') 
    self.args = parse_args(testargs) 
    self.post = myPythonScript.process(self.args) 
    self.assertEqual(self.post['Subject'], 'This is the title I want') 

如果我使用上述參數運行我正在測試的腳本,它們在沒有任何問題的情況下被接受,輸出如預期。

但是,如果我運行的使用包含空格的參數的單元測試,我得到以下幾點:

需要相同的字典對象(含相同參數)做工精細
DocoptExit: Usage: myPythonScript [options] <file_1> <file_2> 

其他單元測試。

我應該在我的代碼中更改哪些內容以使docopt像通常一樣解析參數?

+0

此問題已在docopt的[Github上的問題跟蹤器](https://github.com/docopt/docopt/issues/129)上重新發布和回答。只是等待@哈爾斯特在這裏複製他的答案,所以它可以被標記爲接受。 – Isxek

回答

2

docopt以argv參數作爲字符串或列表。

  • 如果它是一個列表,它將解釋列表中的每個項目作爲單獨的參數。
  • 如果它是一個字符串,它將使用.split()將字符串拆分成一個列表。這樣你就可以釋放所有的空白。

因此,爲了讓您的測試工作,您應該傳遞一個列表,而不是將它加入字符串argstr = ' '.join(testargs)

這種混淆可能是由於傳遞給argv的字符串沒有記錄。實際上它不是API的一部分,只是一個實現細節。您不應該依賴docopt argv接受字符串這一事實 - 這可能會消失。但docopt將始終接受argv的列表。