assertRaises不捕获IntegrityError,Flask SQLAlchemy [英] assertRaises not catching IntegrityError , Flask SQLAlchemy

查看:437
本文介绍了assertRaises不捕获IntegrityError,Flask SQLAlchemy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的测试没有捕捉psycopg2.IntegrityError assertRaises。我正在使用Flask-SQLAlchemy。

  def test_insert_cash_flow(self):
cf = CashFlow()
db.session.add(cf )
self.assertRaises(psycopg2.IntegrityError,db.session.commit)

我的CashFlow SQLAlchemy模型有几个可空= False字段。它说我的测试失败,IntegrityError被打印到屏幕上,但我的assertRaises没有抓住这个。有人怀疑为什么?

解决方案

SQLAlchemy引发 sqlalchemy.exc.IntegrityError ,它包装了底层的异常,而不是数据库驱动的异常。

  sqlalchemy.exc.IntegrityError :( sqlite3。 IntegrityError)NOT NULL约束失败:user.name [SQL:'INSERT INTO user(name)VALUES(?)'] [parameters:(None,)] 

测试正确的异常。

  from sqlalchemy.exc import IntegrityError 
self.assertRaises(IntegrityError,db.session.commit)


My test is not catching psycopg2.IntegrityError with assertRaises. I am using Flask-SQLAlchemy.

def test_insert_cash_flow(self):
    cf = CashFlow()
    db.session.add(cf)
    self.assertRaises(psycopg2.IntegrityError, db.session.commit)

My CashFlow SQLAlchemy model has several nullable=False fields. It says my tests failed and IntegrityError is printed to the screen but my assertRaises does not catch this. Does anyone have any suspicion why?

解决方案

SQLAlchemy raises sqlalchemy.exc.IntegrityError, which wraps the underlying exception, not the exception from the database driver.

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.name [SQL: 'INSERT INTO user (name) VALUES (?)'] [parameters: (None,)]

Test for the correct exception.

from sqlalchemy.exc import IntegrityError
self.assertRaises(IntegrityError, db.session.commit)

这篇关于assertRaises不捕获IntegrityError,Flask SQLAlchemy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆