我想在 python 中使用 unittest 来检查方法是否返回正确类的对象。
网络中的每个示例都显示返回的“类型”测试。
例如,检查 <type 'list'>
或 <type 'type'>
,我们可以使用:
self.assertIsInstance(result, list)
self.assertIsInstance(result[0], tuple)
我正在寻找的是检查 <class'sqlalchemy.orm.query.Query'>
的示例
不胜感激。谢谢。
最佳答案
您可以使用 assertIsInstance()
,大概使用 isinstance()
这是测试类型的推荐功能。您还可以根据上下文将 assertIs()
或 assertTrue()
与 type()
结合使用:
#assert.py
import unittest
class TestType(unittest.TestCase):
def setUp(self):
self.number = 1
def test_assert_true(self):
self.assertTrue(type(self.number) is int)
def test_assert_is_instance(self):
self.assertIsInstance(self.number, int)
def test_assert_is_with_type(self):
self.assertIs(type(self.number), int)
def test_assert_is(self):
self.assertIs(self.number, int)
if __name__ == '__main__':
unittest.main()
$ python assert.py
test_assert_is (__main__.TestType) ... FAIL
test_assert_is_instance (__main__.TestType) ... ok
test_assert_is_with_type (__main__.TestType) ... ok
test_assert_true (__main__.TestType) ... ok
======================================================================
FAIL: test_assert_is (__main__.TestType)
----------------------------------------------------------------------
Traceback (most recent call last):
File "assert.py", line 19, in test_assert_is
self.assertIs(self.number, int)
AssertionError: 1 is not <type 'int'>
----------------------------------------------------------------------
Ran 4 tests in 0.000s
FAILED (failures=1)
test_assert_is(self)
的断言错误可能导致人们认为 1 的类型不是整数,但它是在比较 1 表示的对象和描述整数类型的对象。这很可能是为什么首选 isinstance()
的原因,因为它对检查的内容更加冗长且涉及的输入更少,因此通常更不容易出错。
关于用于检查实例类型的 Python 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33657463/