admin管理员组文章数量:1125736
I have a FastAPI web service using the Controller-Service-Repository pattern. I'm wondering about the best approach for implementing unit tests.
Here's my current code structure:
[Model]
class UserInfo(SQLModel, table=True):
__tablename__ = 'user_info'
__table_args__ = {'schema': 'Auth'}
id: int | None = Field(default=None, primary_key=True)
name: str = Field(nullable=False)
username: str = Field(nullable=False)
email: str = Field(nullable=False)
role: str = Field(nullable=False)
tenant_id: int = Field(nullable=False)
activate: bool = Field(nullable=False)
[Repository]
def get_user_info_repository(tenant_id: str) -> list[UserInfo]:
with Session(engine) as session:
statement = select(UserInfo).where(UserInfo.tenant_id == tenant_id)
result = session.exec(statement)
return result.all()
[Service]
def get_user_info_service(tenant_id: str) -> list[UserInfo]:
user_list = get_user_info_repository(tenant_id)
return user_list
[Schema]
class UserResponse(SQLModel):
username: str
name: str
email: str
role: str
tenant_id: str
activate: bool
class UserInfoResponse(SQLModel):
user_limit: int
users: list[UserResponse]
[Controller]
@app.get("/user_info", response_model=UserInfoResponse)
def user_info():
response = get_user_info_service("Test_Account")
return UserInfoResponse(users=response)
My questions are:
- Should I write unit tests for each layer (Controller, Service, Repository) and mock their dependencies? Or is it sufficient to just test the Controller layer using
TestClient
? - Should unit tests include or avoid cross-layer testing scenarios? (For example, should I test Controller+Service together or always test them separately?)
- Since my Service layer is just passing through data without any business logic, should I still write unit test case for it?
本文标签:
版权声明:本文标题:python - How to implement unit tests in a FastAPI application using Controller-Service-Repository pattern? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736673757a1947063.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论