Test Backend หลายสิบตัวใน PR เดียว: กลยุทธ์การทดสอบสำหรับ FastAPI
การเขียน test suite ที่ครอบคลุมสำหรับ FastAPI backend ใน pull request เดียวที่มุ่งเน้นต้องการการคิดล่วงหน้าเกี่ยวกับ fixture pattern การ isolation และวิธีการ test ความกังวลต่าง ๆ โดยไม่ต้องทำซ้ำโค้ดมากเกินไป บทความนี้บันทึก fixture pattern ที่ทำให้ test isolation มีประสิทธิภาพ, authentication testing ข้ามหลาย role, และการ test ข้อมูล time-series ที่ขึ้นอยู่กับ timestamp ปัจจุบัน
Fixture Architecture
Fixture หลักที่ทำงานได้ดีสำหรับ FastAPI + SQLAlchemy:
@pytest.fixture(scope="session")
def engine():
engine = create_engine(settings.TEST_DATABASE_URL)
Base.metadata.create_all(engine)
yield engine
Base.metadata.drop_all(engine)
@pytest.fixture(scope="function")
def db(engine):
connection = engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
yield session
session.close()
transaction.rollback()
connection.close()
scope="function" พร้อม transaction rollback หมายความว่าแต่ละ test เริ่มต้นด้วย database ที่สะอาด ไม่ต้องการ teardown เพิ่มเติม
Authentication Testing
สำหรับ endpoint ที่ต้องการ authentication ใน FastAPI, override dependency ใน test:
def override_get_current_user(role: str = "user"):
async def _override():
return User(id="test-user-id", role=role, email="[email protected]")
return _override
@pytest.fixture
def admin_client(client):
app.dependency_overrides[get_current_user] = override_get_current_user("admin")
yield client
app.dependency_overrides.clear()