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.