TGViewer
Machine Learning with Python Machine Learning with Python @codeprogrammer · 68.5K subscribers
Post #4627 5.42K
How to test code without a real database

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 data

Example 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
  • ❤ 13
  • 👍 2
  • 🔥 2
More from @codeprogrammer
  1. Oct 9, 2026🔖 Official PyTorch Tutorials This collection includes: 🫡 PyTorch fundamentals and torch.…
  2. Oct 7, 2026A distinctive bot for subscribing to courses on the most popular educational platforms acr…
  3. Oct 7, 2026Understanding algorithms changes the way you write code. 🧠 This playlist teaches you exac…
  4. Oct 6, 2026🛠 Built an AI app with Cursor, Claude Code or Lovable? Publish it on Zibby (zibby.run), a…
  5. Oct 5, 2026🚀 ChatGPT Plus & Gemini AI Pro🤖 ChatGPT Plus — 1 Month: $8 ✨ Gemini AI Pro — 18 Months:…
  6. Oct 4, 2026I found a great resource for interactive learning about machine learning and AI – VizLearn…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →