I have a project with multiple route files, each of which has an APIRouter. I include all routers in my main.py as follows:
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() In customer.py I have this (simplified) code:
from fastapi import APIRouter from pydantic import BaseModel router = APIRouter() class CustomerModel(BaseModel): name: str @router.post('/') def register_new_customer(data: CustomerModel): pass in my receipt.py I have similar code:
from fastapi import APIRouter from pydantic import BaseModel router = APIRouter() class ReceiptModel(BaseModel): price: float @router.post('/') def add_new_receipt(data: ReceiptModel): pass I also have unit tests for both files. 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 and similar for test_customer.py
If i run each file individually, e.g. pytest test_receipt.py or pytest test_customer.py it works fine, but when i run them together, my test_receipt.py fails, saying response.status_code is 422. What happens is that my app adds both POST routes on / path, so when receipt runs the test, it's actually making a call to the customer route and fails validation.
Question: how can I ensure that app is not reused between test files?
I know I can just copy/paste the app.include_router lines from main into the tests (with full paths), and that's what I'm currently doing as a workaround, I was just wondering if there's a way to ensure that app is isolated b/w each test suite.
没有评论:
发表评论