3

我正在运行 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)
4

1 回答 1

4

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

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

更多细节

于 2012-07-27T21:18:32.777 回答