Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you assert database error using Python's unittest?

I am running Python 2.6.5, so I use unittest2 module, which is the future port of the unittest module in 2.7 and 3.X. I am performing the following integration test:

def test_hits_constraint_raise(self):
    obj = Table1(...)
    self.sess.add(obj)
    self.sess.flush()

    # assert condition raises
    self.assertFailure(IntegrityError, sess.add, obj)

Instead, it hits error.

======================================================================
ERROR: test_hits_constraint_raise (__main__.TestModels)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_models.py", line 76, in test4_create_exercise_same_id_constraint_raise
    self.sess.flush()
  File "build/bdist.linux-i686/egg/sqlalchemy/orm/scoping.py", line 114, in do
    return getattr(self.registry(), name)(*args, **kwargs)
      .........
  File "build/bdist.linux-i686/egg/sqlalchemy/engine/default.py", line 331, in do_execute
    cursor.execute(statement, parameters)
IntegrityError: (IntegrityError) column exercise_id is not unique u'INSERT INTO TABLE1 (attribute1_name, attribute2_name) VALUES (?, ?)' ('value1', 'value2')

----------------------------------------------------------------------
Ran 4 tests in 0.531s

FAILED (errors=1)

Is the only way to do is use @unittest2.expectedFailure? That one will run fine. But I want to know exactly what kind of error was raised.

----------------------------------------------------------------------
Ran 4 tests in 0.513s

OK (expected failures=1)
like image 761
User007 Avatar asked Jun 26 '26 10:06

User007


1 Answers

You can use assertRaises as a with statement context:

with unittest.assertRaises(IntegrityError):
    sess.add(obj)

More details.

like image 118
Daniel Roseman Avatar answered Jun 29 '26 00:06

Daniel Roseman