محاكاة التبعيات في اختبارات FastAPI
تعلّم كيفية عزل نقاط نهاية FastAPI في الاختبارات عبر تجاوز التبعيات ومحاكاة الخدمات الخارجية.
محاكاة التبعيات في اختبارات FastAPI درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في FastAPI Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Mock Dependencies?
When testing a FastAPI endpoint, you often want to isolate the route logic from external systems like databases, payment gateways, or third-party APIs.
Mocking replaces those slow or unreliable parts with predictable fakes so your tests stay fast and deterministic.
FastAPI Dependency Overrides
FastAPI exposes app.dependency_overrides, a dictionary that maps a real dependency to a fake one during testing.
This is the cleanest way to swap a database session or auth check without touching production code.
app.dependency_overrides[get_db] = override_get_dbA Dependency to Override
Imagine an endpoint that depends on a database session.
from fastapi import Depends
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{uid}")
def read_user(uid: int, db=Depends(get_db)):
return db.query(User).get(uid)Providing a Fake Session
In your test, define a function that yields an in-memory or test session, then register it as an override.
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_dbClearing Overrides
Always clear overrides after a test so they do not leak into other tests.
Use app.dependency_overrides.clear() in teardown or a pytest fixture finalizer.
app.dependency_overrides.clear()Mocking with unittest.mock
For non-dependency code such as a helper that calls an external API, use unittest.mock.patch to replace the function.
from unittest.mock import patch
with patch("app.services.send_email") as mock_send:
mock_send.return_value = True
response = client.post("/signup", json=payload)
mock_send.assert_called_once()Using MagicMock Return Values
A MagicMock lets you script return values and inspect how it was called.
from unittest.mock import MagicMock
fake_client = MagicMock()
fake_client.charge.return_value = {"status": "ok"}Mocking Async Functions
FastAPI is async-friendly. To mock an async dependency, use AsyncMock so awaiting it works correctly.
from unittest.mock import AsyncMock
mock_repo = AsyncMock()
mock_repo.get_user.return_value = {"id": 1, "name": "Ada"}Mocking Auth Dependencies
To bypass authentication in a test, override the auth dependency to return a fake user.
def fake_current_user():
return User(id=1, role="admin")
app.dependency_overrides[get_current_user] = fake_current_userVerifying Mock Calls
Mocks record every interaction. Assert that your code called the dependency the expected way.
mock_send.assert_called_once_with(to="a@b.com")
assert mock_repo.save.call_count == 1Fixture-Based Overrides
Wrap overrides in a pytest fixture for reuse and automatic cleanup.
import pytest
@pytest.fixture
def client_with_db():
app.dependency_overrides[get_db] = override_get_db
yield TestClient(app)
app.dependency_overrides.clear()Quick Check
Test your mocking knowledge.
Recap
You learned how to isolate FastAPI endpoints in tests:
- dependency_overrides swaps dependencies like DB sessions or auth
- patch / MagicMock / AsyncMock fake external functions
- Always clear overrides after each test
Mocking keeps tests fast, deterministic, and focused on your own logic.
الأسئلة الشائعة
هل درس «محاكاة التبعيات في اختبارات FastAPI» مجاني؟
نعم — نص درس «محاكاة التبعيات في اختبارات FastAPI» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
ماذا ستتعلم في «محاكاة التبعيات في اختبارات FastAPI»؟
تعلّم كيفية عزل نقاط نهاية FastAPI في الاختبارات عبر تجاوز التبعيات ومحاكاة الخدمات الخارجية. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «محاكاة التبعيات في اختبارات FastAPI»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟
نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- اختبار الوحدات باستخدام Pytest
- اختبار تكامل نقاط نهاية FastAPI
- تصحيح أخطاء تطبيقات FastAPI
- محاكاة التبعيات في اختبارات FastAPI