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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With