Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a proper way to test SQLAlchemy code that throw IntegrityError?

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?

like image 849
swdev Avatar asked Oct 10 '13 07:10

swdev


1 Answers

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).

like image 171
codeape Avatar answered Oct 13 '22 03:10

codeape