My python app uses pyodbc to connect to the database. I would like to mock the database in my tests.
When running tests on the build server import pyodbc
throws ImportError: libodbc.so.2: cannot open shared object file: No such file or directory
because unixODBC is not installed.
Is there a way to mock the pyodbc import before importing the main file into the test or do we have to install unixODBC in the build server (works but feels unnecessary)?
main.py
import pyodbc
def function_to_test():
...
test_main.py
from main import function_to_test # this throws
...
If you're importing pyodbc
at any point without mocking it, it needs the unixODBC
libs.
However, you can mock an entire module prior to loading it with the following:
import sys
import unittest
from unittest.mock import NonCallableMagicMock
mock_pyodbc = NonCallableMagicMock()
sys.modules["pyodbc"] = mock_pyodbc
from main import function_to_test # imports and uses pyodbc
# your tests