Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertRaises not catching IntegrityError , Flask SQLAlchemy

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?

like image 624
allenlin1992 Avatar asked May 21 '26 00:05

allenlin1992


1 Answers

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)
like image 70
davidism Avatar answered May 23 '26 13:05

davidism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!