Search code examples
pythonpython-unittestmysql-connector-pythonpython-unittest.mock

Connection unit testing in Python


I am new to Python unit testing and I am not sure how i can create a unit test of this function that returns a connection?

def connection(self):
    connection = mysql.connector.connect(host='localhost', 
                     database='test',
                     user='user', 
                     password='password',
                     auth_plugin='mysql_native_password')
    return connection

Solution

  • You could mock out mysql.connector.connect and ensure that it's called, but honestly this is probably too small a unit to provide any benefits to your unit tests. This is just delegating a call to mysql.connector.connect, which itself should be tested (by the mysql package).

    class TestConnection(unittest.TestCase):
        @unittest.mock('module_under_test.mysql.connector.connect')
        def test_connection(self, mockconnect):
            module_under_test.connection()
            mockconnect.assert_called()
    

    I suppose you could also check to make sure that it always returns something (to keep from future revisions forgetting to return out of the function.

        # inside test_connection as above
            connection = module_under_test.connection()
            self.assertIsNotNone(connection)
            mockconnect.assert_called()