0

I'm beginning to write some unit tests for my company. I want to start by testing the connection to my database. Function get_database_connection()- which is defined in a module not specified here- connects to my database. Otherwise, an exception is raised and returns None.

import pyodbc
import unittest
from unittest.mock import patch, MagicMock
import package.module
from package.module2 import get_database_connection


@patch("package.module.get_database_connection", MagicMock(return_value=r'Driver=SQL Server;Server=localhost;Database=myDB;Trusted_Connection=yes;'))
def test_get_database_connection():
    assert get_database_connection() is not None
    assert isinstance(get_database_connection(), pyodbc.Connection)

I'm using pytest and unittest frameworks for this project. Though I am new at testing, I was under the impression that the MagicMock object found in the @patch decorator would pass its return value to get_database_connection(). However, running $ pytest -v -s returns the error:

get_database_connection() missing 1 required positional argument: 'parameter1'

What am I missing here? Maybe I am misunderstanding how MagicMock and this library works.

*EDIT: For clarification, the first argument I am passing to @patch is the location where get_database_connection() is used, not where it is defined.

FreyGeospatial
  • 325
  • 4
  • 17
  • 1
    It looks as if `get_database_connection()` requires an argument, and you are not providing one. Without seeing your `get_database_connection` function we can't really say more than that. – larsks Apr 25 '22 at 21:13
  • 1
    You are not calling the patched version, but the one imported into your test module - e.g. in this case the location where you _use_ the function is your test module. Of course, it makes no sense to patch a function and than directly call it in the test, as you will just get a mock, but I guess you are doing it to check if the mocking works... – MrBean Bremen Apr 26 '22 at 04:59

0 Answers0