Calmcode - fastapi: testing one

Adding some unit tests via the FastAPI testing client.

1 2 3 4 5 6 7 8 9

Before running pytest you may want to confirm it is installed.

pip install pytest

The files we use in this video are displayed below.

import time
import asyncio

from pydantic import BaseModel, validator
from fastapi import FastAPI

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

    def price_must_be_positive(cls, value):
        if value <= 0:
            raise ValueError(f"we expect price >= 0, we received {value}")
        return value

def root():
    return {"message": "hello world again"}

def read_user(user_id: str):
    return {"user_id": user_id}"/items/")
def create_item(item: Item):
    return item

def sleep_slow():
    r = time.sleep(1)
    return {"status": "done"}

async def sleep_fast():
    r = await asyncio.sleep(1)
    return {"status": "done"}

from starlette.testclient import TestClient

from app import app

client = TestClient(app)

def test_root_endpoint():
    resp = client.get("/")
    assert resp.status_code == 200
    assert resp.json() == {"message": "hello world again"}

def test_users_endpoint():
    resp = client.get("/users/1")
    assert resp.status_code == 200
    assert resp.json() == {"user_id": "1"}