Py学习  »  Python

Python:用具体的实现细节测试抽象类

awy • 2 年前 • 663 次点击  

我有一个包含以下内容的类: @abstractmethod 和正常的实现方法,我想知道我应该如何测试正常的实现。

快速示例:我想测试 zoo_str 方法,尽管它依赖于抽象 description 方法如果我有100只动物,那么在狮子类、羚羊类、河马类等动物中写一个测试似乎太过分了。做这件事的最佳方式是什么?我的直觉告诉我应该试着去模仿 描述 ,但我无法安装该类,如果抽象方法是私有的,则会崩溃( _description ).

class Animal:
    @abstractmethod
    def description(self) -> str:
        pass

    def zoo_str(self) -> str:
         return self.description() + "Get more info at zoo.com!"
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128960
 
663 次点击  
文章 [ 3 ]  |  最新文章 2 年前
teprrr
Reply   •   1 楼
teprrr    2 年前

下面是一个使用变体(基于 https://stackoverflow.com/a/63777635 )展示如何测试所有 Animal 子类:

@pytest.mark.parametrize("cls", Animal.__subclasses__())
def test_animals(mocker, cls):
    mocker.patch.multiple(cls, __abstractmethods__=set())
    inst = cls()
    assert inst.zoo_str() == f"{inst.description()}Get more info at zoo.com!"
b0lle
Reply   •   2 楼
b0lle    2 年前

您可以简单地使用多重继承:

# test_animals.py
import unittest

from animals import Animal


class TestAnimal(unittest.TestCase, Animal):

    def description(self) -> str:
        return "Unittest"

    def test_zoo_str(self) -> None:
        assert self.zoo_str() == "UnittestGet more info at zoo.com!"
chepner
Reply   •   3 楼
chepner    2 年前

只需创建一个子类。

class TestAnimal(Animal):
    def description(self):
        return "foo"


assert TestAnimal().zoo_str() == "fooGet more info at zoo.com!"