我想在python中使用unittest来检查方法是否返回了正确类的对象.
Web中的每个示例都显示返回的"类型"测试.
例如,要检查 <type 'list'>
或 <type 'type'>
,我们可以使用:
self.assertIsInstance(result, list)
self.assertIsInstance(result[0], tuple)
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是一个检查的例子 <class'sqlalchemy.orm.query.Query'>
非常感谢任何帮助.谢谢.
Bro*_*ves 31
您可以使用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)
Run Code Online (Sandbox Code Playgroud)
的断言错误test_assert_is(self)
可能会导致人们相信1的类型不是整数但是它的比较和描述整数类型的对象由1表示的对象.这很可能isinstance()
是首选的原因,因为它更复杂的是它的检查和更少的输入,因此通常不易出错.
Viv*_*dey 10
这应该有效:
self.assertIsInstance(result, sqlalchemy.orm.query.Query)
Run Code Online (Sandbox Code Playgroud)
你需要import sqlalchemy
在文件中。