3

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?

allenlin1992
  • 1,920
  • 3
  • 16
  • 28
  • Strange ... indeed. Have you try to use self.assertRaises within a with statement, has outlined in the documentation? https://docs.python.org/2/library/unittest.html – ohe Dec 21 '15 at 21:31
  • Are you sure you have `db.session.commit` and not `db.session.commit()`? – alecxe Dec 21 '15 at 21:32
  • Related or duplicate: http://stackoverflow.com/q/19289291/771848. – alecxe Dec 21 '15 at 21:32
  • Yes I have tried using the with statement, with the same failure. And yes I am sure I have db.session.commit without () – allenlin1992 Dec 21 '15 at 21:35

1 Answers1

8

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)
davidism
  • 121,510
  • 29
  • 395
  • 339