During unit testing, connecting to a real DB is unnecessary:
• tests run slowly
• become unstable
• require a working server
It is much better to mock the call to
pandas.read_sql and return dummy dataExample function:
def query_user_data(user_id):
query = f"SELECT id, name FROM users WHERE id = {user_id}"
return pd.read_sql(query, "postgresql://localhost/mydb")
Test with mock:
from unittest.mock import patch
import pandas as pd
@patch("pandas.read_sql")
def test_database_query_mocked(mock_read_sql):
mock_read_sql.return_value = pd.DataFrame(
{"id": [123], "name": ["Alice"]}
)
result = query_user_data(user_id=123)
assert result["name"].iloc[0] == "Alice"
This way you test only the business logic — quickly, reliably, and without unnecessary dependencies
https://t.me/CodeProgrammer
