Skip to content

TestClient: how to test overwrites in the Config of an input (pydantic) model? #4643

@camold

Description

@camold

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

###### fastapi_extra.py
import fastapi
from pydantic import BaseModel


class MyModel(BaseModel):
    i: int

    class Config:
        extra = "ignore"


def create_app():

    app = fastapi.FastAPI()

    @app.post("/")
    def test(m: MyModel):
        return [m.i, MyModel.Config.extra]

    return app

########### test_fastapi_extra.py
import pytest
from fastapi.testclient import TestClient

import fastapi_extra

# overwrite from "ignore" to "forbid"
fastapi_extra.MyModel.Config.extra = "forbid"


@pytest.fixture
def test_app():
    yield TestClient(fastapi_extra.create_app())


def test_root(test_app):
    # send a message with an additional attribute
    r = test_app.post("/", json={"i": 2, "foo": "bar"})
    assert r.json() == [2, "forbid"]
    assert r.status_code == 200  # this should be 422 then!

Description

I would like to ensure that the models/queries used in my pytests are up to date with the code. Hence, the goal was to set the Config.extra parameter to "forbid" in the pytests.

Note that the original application requires "ignore" to not break production. So "forbid" should only be used within the tests.

pytest test_fastapi_extra.py
should raise an error but does not... so weirdly enough the model config is set to "forbid" but the extra fields do not cause an unprocessable entity error.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.74.1

Python Version

3.9.7

Additional Context

pydantic 1.9.0
pytest 7.0.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions