Unit testing Python + MySQLdb warnings

There seems to be several methods out there, based on elevating warnings to errors using warnings.simplefilter. Here’s another method, based on recording warnings in a variable, and checking that the last one is a MySQLdb.Warning. Hopefully to be integrated in INSPIRE.

import MySQLdb
import unittest
import warnings
[...]
class TestTagInsert(unittest.TestCase):
    def test_too_long_tags(self):
        with warnings.catch_warnings(record=True) as warn:
            [Run SQL statement]
            self.assert_(len(warn) == 1) # Ensures that the next statement won't break the testing
            self.assertEqual(
                MySQLdb.Warning,
                warn[-1].category
                )
            #If you also want to check the text of the warning:
            self.assert_(
                'truncated' in str(warn[-1].message))
Advertisements