首页 > 解决方案 > 在 Python3 中同时对内容的类型和类型进行单元测试

问题描述

假设我有这样的功能:

def f(x):
    return (1, 2, 3)

如果我想单元测试返回类型是一个元组,我可以像这样使用 assertIsInstance() :

class TestF(unittest.TestCase):
    def test_return_type(self):
        result = f(10)
        self.assertIsInstance(result, tuple, "Must return tuple")

如果我想检查 f 返回正好是 3 个整数的元组怎么办?显然我可以通过额外的测试单独检查返回的长度和内容,但是有没有更整洁的方法来做到这一点?就像是:

def test_return_type(self):
    result = f(10)
    self.assertIsInstance(result, (int, int, int), "Must return a tuple of 3 ints")

有没有内置的东西可以让我在没有额外工作的情况下做到这一点?

标签: python-3.xpython-unittest

解决方案


推荐阅读