如何使用Python的unittest声明数据库错误?

时间:2012-07-27 20:59:54

标签: python unit-testing

我正在运行Python 2.6.5,所以我使用unittest2模块,这是2.7和3.X中unittest模块的未来端口。我正在执行以下集成测试:

def test_hits_constraint_raise(self):
    obj = Table1(...)
    self.sess.add(obj)
    self.sess.flush()

    # assert condition raises
    self.assertFailure(IntegrityError, sess.add, obj)

相反,它会遇到错误。

======================================================================
ERROR: test_hits_constraint_raise (__main__.TestModels)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_models.py", line 76, in test4_create_exercise_same_id_constraint_raise
    self.sess.flush()
  File "build/bdist.linux-i686/egg/sqlalchemy/orm/scoping.py", line 114, in do
    return getattr(self.registry(), name)(*args, **kwargs)
      .........
  File "build/bdist.linux-i686/egg/sqlalchemy/engine/default.py", line 331, in do_execute
    cursor.execute(statement, parameters)
IntegrityError: (IntegrityError) column exercise_id is not unique u'INSERT INTO TABLE1 (attribute1_name, attribute2_name) VALUES (?, ?)' ('value1', 'value2')

----------------------------------------------------------------------
Ran 4 tests in 0.531s

FAILED (errors=1)

唯一的办法是使用@unittest2.expectedFailure吗?那一个会运行正常。 但我想确切地知道引起了什么样的错误。

----------------------------------------------------------------------
Ran 4 tests in 0.513s

OK (expected failures=1)

1 个答案:

答案 0 :(得分:4)

您可以将assertRaises用作with语句上下文:

with unittest.assertRaises(IntegrityError):
    sess.add(obj)

More details