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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s