1

I have a function for my database connection that returns both cursor and connection.

def database_connection():
    resp_dict = json.loads(get_secret())
    endpoint = resp_dict.get('host')
    username = resp_dict.get('username')
    password = resp_dict.get('password')
    database_name = resp_dict.get('dbname')
    port = resp_dict.get('port')
    connection = pymysql.connect(host=endpoint, user=username, passwd=password, db=database_name, port=port)
    cursor = connection.cursor()
    return cursor, connection

def sql_query_insert(insert, user_id, time):
    cursor, connection = database_connection()
    sql_query = "INSERT INTO account_login (" + insert + ", login_date) VALUES ('" + str(user_id) + "' ,'" + time + "')"
    cursor.execute(sql_query)
    connection.commit()
    return connection

I then use this to run various sql queries. Right now I am trying to write some test's for these sql queries but do not want to connection to a real database and want to mock the function database_connection(). However, I am having some trouble mocking the function as it return's two values. This is the test I am trying to build out. (p.s I know this will fail but I am trying to build out the test first before getting my expected values, and I will be updating the sql query insert function after figuring this out as as it is open to sql injections)

    @mock.patch('lambda_function.database_connection', return_value=['cursor', 'connection'])
    def test_sql_query_insert(self):
        result = lambda_function.sql_query_insert("select", "table", "condition")
        self.assertEqual(result, "test")

This is the error I am getting:

insert = 'select', user_id = 'table', time = 'condition'

    def sql_query_insert(insert, user_id, time):
>       cursor, connection = database_connection()
E       ValueError: not enough values to unpack (expected 2, got 0)

../lambda_function.py:52: ValueError
L44TXF
  • 65
  • 3
  • 10
  • You are probably not patching the correct `database_connection`, check [where to patch](https://docs.python.org/3/library/unittest.mock.html#id6). – MrBean Bremen Aug 26 '21 at 17:37

0 Answers0