加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – assertRaises没有捕获IntegrityError,Flask SQLAlchem

发布时间:2020-12-20 11:47:51 所属栏目:Python 来源:网络整理
导读:我的测试没有捕获带有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
我的测试没有捕获带有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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读