Pytest patterns for Python APIs -- httpx AsyncClient, conftest fixtures, database isolation, parametrize edge cases, error response testing, auth flows, factory fixtures
99
99%
Does it follow best practices?
Impact
100%
1.23xAverage score across 5 eval scenarios
Passed
No known issues
A small e-commerce startup has built a FastAPI service to manage their product catalog. The service exposes endpoints to list products, fetch a product by ID, and create new products. The engineering team has been manually testing with curl but now wants to introduce automated tests before onboarding a second developer.
You have been asked to set up the initial test infrastructure: the configuration file, the dependencies, and a conftest.py with a reusable client fixture. Write at least two meaningful tests for the existing API to verify the setup works end-to-end.
Produce the following files:
pyproject.toml — includes pytest configuration with async support enabledrequirements-test.txt or an updated pyproject.toml dependencies section listing the test packages neededtests/conftest.py — contains the reusable test client fixturetests/test_products.py — contains at least two tests exercising the APIThe following files are provided as inputs. Extract them before beginning.
=============== FILE: app/main.py =============== from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Optional, List
app = FastAPI()
_products = [ {"id": 1, "name": "Widget A", "price": 9.99, "stock": 100}, {"id": 2, "name": "Widget B", "price": 19.99, "stock": 50}, ] _next_id = 3
class ProductCreate(BaseModel): name: str price: float stock: int = 0
@app.get("/products") async def list_products(): return {"data": _products}
@app.get("/products/{product_id}") async def get_product(product_id: int): for p in _products: if p["id"] == product_id: return {"data": p} raise HTTPException(status_code=404, detail="Product not found")
@app.post("/products", status_code=201) async def create_product(body: ProductCreate): global _next_id product = {"id": _next_id, "name": body.name, "price": body.price, "stock": body.stock} _products.append(product) _next_id += 1 return {"data": product}