用于检查实例类型的 Python 测试

标签 python testing

我想在 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/

相关文章:

python - 用纯python计算NN的梯度

python - 动态设置wx.GridBagSizer的大小

c - C中的CPU数量限制

c# - 在不调试的情况下将测试日志写入 Visual Studio 输出 Pane ?

python - 无法导入 tensorflow_probability

python - 改变 python bokeh PreText() 的颜色

testing - 如何单击溢出 :hidden in cucumber/capybara 的元素

python - PyTest:测试if语句中调用了哪个函数

unit-testing - 在多个go模块的父目录中运行 `go test`

python - Pylons 导入 Psycopg2 错误