Suppress Python MySQL Connector DeprecationWarning and ResourceWarnings In Unittests

September - 2021

I ran into warnings using mysql.connector. The looked liked this:

/Users/user/workshop/venv/lib/python3.9/site-packages/mysql/connector/connection_cext.py:513: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats
  self._cmysql.query(query,
../usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py:353: ResourceWarning: unclosed <ssl.SSLSocket fd=8, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('###.###.###.###', 676767), raddr=('###.###.###.###', 443)>
  obj, end = self.scan_once(s, idx)
ResourceWarning: Enable tracemalloc to get the object allocation traceback

And sometimes:

sys:1: ResourceWarning: unclosed <ssl.SSLSocket fd=8, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('###.###.###.###', 676767), raddr=('###.###.###.###', 443)>

The fix was to import the warnings module, create a ignore_warnings function and add it as a decorator. Like this:

#!/usr/bin/env python3

import keyring
import mysql.connector
import unittest
import warnings 

from thing_to_test import ThingToTest 

def ignore_warnings(test_method):
    def test_run(self, *args, **kwargs):
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            test_method(self, *args, **kwargs)
    return test_run


class GenrePopulatorTest(unittest.TestCase):

    @ignore_warnings
    def setUp(self):
 
        global cnx
        cnx = mysql.connector.connect(
            database=keyring.get_password('mysql-database', 'local_username'),
            host=keyring.get_password('mysql-host', 'local_username'),
            user=keyring.get_password('mysql-username', 'local_username'),
            password=keyring.get_password('mysql-password', 'local_username')
        )

        
    def tearDown(self):
        cnx.close()

    @ignore_warnings
    def test_something_here(self):
        expected = 3
        query = ("SELECT COUNT(*) FROM table")
        cursor = cnx.cursor()
        cursor.execute(query)
        result = cursor.fetchone()[0]
        self.assertEqual(expected, result)

if __name__ == '__main__':
    unittest.main(failfast=True)

With that in place, the warnings were suppressed and I'd get just the results of the unittests.

Here's the post that gave me the solution.