2012-06-12 62 views
9

我與Spock一起工作過,並喜歡'where'子句,它允許您輕鬆地使用多個輸入和輸出來運行測試用例。例如:是否有Python的Spock式測試庫

class HelloSpock extends spock.lang.Specification { 
    def "length of Spock's and his friends' names"() { 
     expect: 
      name.size() == length 

     where: 
      name  | length 
      "Spock" | 5 
      "Kirk" | 4 
      "Scotty" | 6 
    } 
} 

Python是否有類似的東西?

+0

您是否覺得下面的回覆有用? –

回答

3

pytest讓你parametrise a test function

import pytest 
@pytest.mark.parametrize(("input", "expected"), [ 
    ("3+5", 8), 
    ("2+4", 6), 
    ("6*9", 42), 
]) 
def test_eval(input, expected): 
    assert eval(input) == expected 
2

如果你有以上幾個測試的更多,我會建議一個BDD框架,像behave。您可以指定Gherkin syntax,例如(從鏈接的教程代碼):

Scenario: some scenario 
    Given a set of specific users 
    | name  | department | 
    | Barry  | Beer Cans | 
    | Pudey  | Silly Walks | 
    | Two-Lumps | Silly Walks | 

When we count the number of people in each department 
Then we will find two people in "Silly Walks" 
    But we will find one person in "Beer Cans" 

並解析它的Python代碼,例如:

@given('a set of specific users') 
def step_impl(context): 
    for row in context.table: 
     model.add_user(name=row['name'], department=row['department']) 

編寫Python代碼是相當容易的,並且有許多樣板代碼示例在線。這種技術的優點在於您的測試套件具有高度可重用性,並且可以非常容易地由非程序員進行擴展。

2

不,沒有。這是令人難過的,因爲Spock非常出色。我一直在尋找一年,並思考了如何在Python中創建這樣的DSL,因爲我非常想念它。

Behave和Lettuce會爲您提供BDD風格的語法和成語,但您必須維護與您的場景文件相匹配的單獨步驟文件。很明顯,當你想要做TDD但是具有Spock所能實現的BDD的可讀性時,這很糟糕。

如果你還想Spock風格的模擬,那麼Mox是我找到的最接近的。但是一旦你被Spock寵壞了,它又是一個可憐的替代品。