我的测试没有捕获带有assertRaises的psycopg2.IntegrityError.我正在使用Flask-SQLAlchemy.
def test_insert_cash_flow(self): cf = CashFlow() db.session.add(cf) self.assertRaises(psycopg2.IntegrityError, db.session.commit)
我的CashFlow SQLAlchemy模型有几个nullable = False字段.它说我的测试失败了,并且IntegrityError被打印到屏幕上,但我的assertRaises没有抓住这个.有人怀疑为什么?
SQLAlchemy引发sqlalchemy.exc.IntegrityError
,它包装了底层异常,而不是数据库驱动程序的异常.
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.name [SQL: 'INSERT INTO user (name) VALUES (?)'] [parameters: (None,)]
测试正确的异常.
from sqlalchemy.exc import IntegrityError self.assertRaises(IntegrityError, db.session.commit)