有没有一个类似spock的Python测试库

2024-10-01 11:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾经和Spock一起工作过,很喜欢“where”子句,它允许您使用多个输入和输出轻松地练习测试用例。例如:

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也有类似的东西吗?在


Tags: andofnamelangdef测试用例wherelength
3条回答

我也是Java/Groowy世界中Spock框架的超级粉丝。在搜索中类似于Python。在我的搜索中,我找到了nimoy,看起来很有前途。在

官方页面示例:

from nimoy.specification import Specification

class MySpec(Specification):

    def my_feature_method(self):
        with given:
            a = value_of_a
            b = value_of_b

        with expect:
            (a * b) == expected_value

        with where:
            value_of_a | value_of_b | expected_value
            1          | 10         | 10
            2          | 20         | 40

还有作者blog post为什么它会诞生。在

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

如果您有多个测试,我将推荐一个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代码,例如:

^{pr2}$

编写Python代码相当容易,网上有许多样板代码示例。这种技术的优点在于,您的测试套件具有高度的可重用性,并且可以很容易地由非程序员进行扩展。在

相关问题 更多 >