I have read this Q&A, and already try to catch exception on my code that raise an IntegrityError exception, this way :
self.assertRaises(IntegrityError, db.session.commit())
But somehow my unit test still failed and stop with IntegrityError exception. I expect it to say OK as I already expect to have exception in my unit test. This was cause by code that tries to insert row having the same unique field values.
Any idea?
One of these will to the trick:
# ... only if version >= 2.7
with self.assertRaises(IntegrityError):
db.session.commit()
Or:
self.assertRaises(IntegrityError, db.session.commit)
The difference between your example and the correct way is:
# Your example: You call db.session.commit(), this will raise an exception before
# assertRaises is called
self.assertRaises(IntegrityError, db.session.commit())
# Correct way: Pass what should be called to assertRaises,
# let assertRaises invoke it and check for exception
self.assertRaises(IntegrityError, db.session.commit)
I prefer to use assertRaises as a context manager (using with
).
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