使用 pytest 测试 class 方法

Testing class methods with pytest

在 pytest 的文档中列出了各种测试用例示例。其中大部分展示了功能测试。但是我缺少一个如何测试 classes 和 class 方法的示例。假设我们要测试的模块 cool.py 中有以下 class:

class SuperCool(object):

    def action(self, x):
        return x * x

tests/test_cool.py中的相应测试class怎么看?

class TestSuperCool():

    def test_action(self, x):
        pass

test_action()如何用于测试action()

要测试 class 方法,您需要做的就是实例化 class,并在该实例上调用该方法:

def test_action(self):
    sc = SuperCool()
    assert sc.action(1) == 1

好吧,一种方法是在测试方法中创建您的对象并从那里与它交互:

def test_action(self, x):
    o = SuperCool()
    assert o.action(2) == 4

您显然可以使用类似于经典 setupteardown 样式的单元测试,使用此处的方法:http://doc.pytest.org/en/latest/xunit_setup.html

我不是 100% 确定它们是如何使用的,因为 pytest 的文档很糟糕

编辑: 是的,很明显,如果你做类似

class TestSuperCool():
    def setup(self):
        self.sc = SuperCool()

    ... 

    # test using self.sc down here

我只会使用任何装置来创建测试环境(如数据库连接)或数据参数化。

如果你的数据比较琐碎,可以在testcase里面定义:

def test_action_without_fixtures():
    sc = SuperCool()
    sc.element = 'snow'
    sc.melt()
    assert sc.element == 'water'

参数化示例:

@pytest.mark.parametrize("element, expected", [('snow', 'water'), ('tin', 'solder')])
def test_action_with_parametrization(element, expected):
    sc = SuperCool()
    sc.element = element
    sc.melt()
    assert sc.element == expected