dragonfromdreams
dragonfromdreams

Reputation: 149

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

Upvotes: 3

Views: 9253

Answers (2)

Adam Erickson
Adam Erickson

Reputation: 6363

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.

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54163

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()

Upvotes: 5

Related Questions