Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests to ensure a ValidationError is raised #9954

Closed

Conversation

marielejeune
Copy link

@marielejeune marielejeune commented Jul 27, 2023

These tests were added to cover a new Response validation case.

Second tests fails as there is a bug in Pydantic v2.1.1.

See:

@dmontagu
Copy link
Collaborator

I would argue this is not a bug in pydantic but a misuse of a performance-oriented validation escape hatch. You should only use model_construct if you are confident that you are creating the model in a valid way, as the whole point is to elide validation for the sake of performance. If you have bugs in your application code caused by that, I would advise against the use of model_construct. Also, the main reason to use model_construct is for performance, and given the massive performance improvements in pydantic v2, it may be worth benchmarking whether there are even any noticeable performance benefits to the use of model_construct anyway. In at least some cases (especially for shallow/simple models), model_construct can be comparable or worse in performance than model_validate anyway.

The reason this would have worked in earlier versions of FastAPI/pydantic was the use of the "secure cloned field", whose purpose was to prevent extra fields from being included at serialization time. But this came at the price of a massive performance overhead caused by revalidating data that in principle was already known to be valid.

We made specific changes in pydantic v2 to render the secure cloned field unnecessary, in particular, serializing models based on their schema rather than through recursive calls to the field attributes' dump methods, and accepting subclass instances as allowed for fields without revalidation, and this is responsible for significant performance improvements in versions of FastAPI using pydantic v2.

As a consequence, there are now issues with invalidly-constructed models not being validated properly, but again, I would consider this a misuse of model_construct rather than a bug in pydantic/fastapi.

@tiangolo
Copy link
Member

tiangolo commented Aug 4, 2023

Amazing writeup as always @dmontagu, thanks! And thanks @marielejeune, I think that would probably answer it, if you have more questions/problems, please create a new discussion question. 🤓

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants