I recently did this for a custom class I created that wraps the Oracle MySQL Connector for Python. I would do something like the following:
import unittest
import mysql.connector
class TestConnection(unittest.TestCase):
"""Oracle MySQL for Python Connector tests."""
connection = None
def setUp(self):
config = {
user = 'user',
password = 'password',
host = 'localhost',
database = 'test',
auth_plugin = 'mysql_native_password'
}
self.connection = mysql.connector.connect(**config)
def tearDown(self):
if self.connection is not None and self.connection.is_connected():
self.connection.close()
def test_connection(self):
self.assertTrue(self.connection.is_connected())
if __name__ == '__main__':
unittest.main()
This solution is based on the setUp() and tearDown() methods provided by unittest that are executed before and after each test, respectively. This allows us to connect to the database, run a simple connection test, then close the connection. This ensures that there are no hanging connections after the completion of unit tests.