简体   繁体   中英

Testing FastAPI TestClient returns 422 on requests

I'm trying to test my code and can't figure out what I'm doing wrong. I'm using FastAPI with pydantic's Base Model.

# Model
class Cat(BaseModel):
    breed: str
    location_of_origin: str
    coat_length: int
    body_type: str
    pattern: str
# Cat creation 
@app.post("/cats", status_code=status.HTTP_201_CREATED)
async def add_cat(cat: Cat,
                  breed: str,
                  location_of_origin: str,
                  coat_length: int,
                  body_type: str,
                  pattern: str):

    new_cat = cat.dict()
    new_cat['breed'] = breed
    ...
    cats.append(new_cat)
    return new_cat

The cat is created without errors using the API.

# Tests
from starlette.testclient import TestClient
from app.main import app

data = {
    'breed': 'Ragdoll',
    'location_of_origin': 'United States',
    'coat_length': 4,
    'body_type': 'Medium',
    'pattern': 'Chocolate Point'
}


def test_add_cat():
    response = client.post("/cats", json=data)
    assert response.status_code == 201
    assert data in response.json() == data

When I run the test, it gives me these errors:

def test_add_cat():
        response = client.post("/cats", json=data)
>       assert response.status_code == 201
E       assert 422 == 201
E        +  where 422 = <Response [422]>.status_code

tests\test_app.py:23: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_app.py::test_add_cat - assert 422 == 201
============================== 1 failed in 0.62s ==============================

The problem is with your function definition. You are specifying a parameter cat of type cat and also duplicate parameters to create the cat. You should just have the cat parameter. Try with this:

# Cat creation 
@app.post("/cats", status_code=status.HTTP_201_CREATED)
async def add_cat(cat: Cat):
    return cat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM