3

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
1
  • What's the point? Commented Nov 12, 2018 at 3:10

2 Answers 2

5

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()
Sign up to request clarification or add additional context in comments.

7 Comments

This provides no value whatsoever. What matters given (limited) context is what the function returns, not how it creates it. To me this test is a clear violation of encapsulation. In fact, a function that calls connect then returns 42 will pass that test, while a function that returns a proper connection through another mean will fail it.
@spectras I agree and mentioned as much in the answer, though I'm not sure how it's a clear violation of encapsulation.
It looks at the inside implementation of connection(). Assuming the point of connection() is to encapsulate the details of creating a connection, encapsulation is broken. To be fair, to make a proper test we should have the documentation of the function. If it says “invoke mysql.connector.connect” then fair enough. But if it just says “create a connection”, that's what should be tested: that it returns a proper connection (isinstance of a specific class, a cursor method can be called on returned object…). How it creates it is irrelevant, unless part of the contract.
@spectras that's a fair assessment. Without a better idea of what connection does it's tough to advise further, however :(. if connection took a path to host, it would be easier to mock out (you could mock a sql database with some test data in your setUp, then open a connection to it and do some stuff with the cursor, asserting its results.
@Banik import unittest.mock
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.