防止Pytest在不同的测试文件之间重用应用对象



我有一个具有多个路由文件的项目,每个路由文件都有一个APIRouter。我在main.py中包括所有路由器,如下所示:

from init import app
import customer
import receipt
app.include_router(customer.router, prefix='/api/customer', tags=["Customer"])
app.include_router(receipt.router, prefix='/api/receipt', tags=["Receipt"])

init.py:

from fastapi import FastAPI
app = FastAPI()

customer.py我有这个(简化)代码:

from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class CustomerModel(BaseModel):
name: str
@router.post('/')
def register_new_customer(data: CustomerModel):
pass

在我的receipt.py我有类似的代码:

from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class ReceiptModel(BaseModel):
price: float
@router.post('/')
def add_new_receipt(data: ReceiptModel):
pass

我还对这两个文件进行了单元测试。test_receipt.py:

from receipt import router
from init import app
app.include_router(router)
client = TestClient(app)
class TestReceiptsRoutes:
def test_can_create_new_receipt(self):
response = client.post('/', json={'price': 10.0})
assert response.status_code == 200

和类似的test_customer.py

如果我单独运行每个文件,例如pytest test_receipt.pypytest test_customer.py,它工作得很好,但是当我一起运行它们时,我的test_receipt.py失败了,说response.status_code422。发生的情况是,我的app/路径上添加了两个POST路由,因此当收据运行测试时,它实际上是在调用客户路由并且验证失败。

问题:我如何确保app在测试文件之间不被重用?

我知道我可以将app.include_router行从主要复制/粘贴到测试中(带完整路径),这就是我目前正在做的解决方案,我只是想知道是否有办法确保应用程序与每个测试套件隔离。

假设app对象是有状态的,它可能有助于重新加载init模块,然后重新导入app

下面是使用fixture的方法:

import pytest
from importlib import reload
import init

@pytest.fixture
def app():
app = reload(init).app
app.include_router(foo.router, ...)
return app

def test_foo(app):
client = TestClient(app)
...

最新更新