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

Set additionalProperties to False on Extra.forbid models #796

Merged
merged 1 commit into from Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/796-Code0x58.rst
@@ -0,0 +1 @@
Set ``additionalProperties`` to false in schema for models with extra fields disallowed.
2 changes: 2 additions & 0 deletions pydantic/schema.py
Expand Up @@ -593,6 +593,8 @@ def model_type_schema(
out_schema = {'type': 'object', 'properties': properties}
if required:
out_schema['required'] = required
if model.__config__.extra == 'forbid':
out_schema['additionalProperties'] = False
return out_schema, definitions, nested_models


Expand Down
18 changes: 17 additions & 1 deletion tests/test_schema.py
Expand Up @@ -11,7 +11,7 @@

import pytest

from pydantic import BaseModel, Schema, ValidationError, validator
from pydantic import BaseModel, Extra, Schema, ValidationError, validator
from pydantic.color import Color
from pydantic.networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, NameEmail, stricturl
from pydantic.schema import (
Expand Down Expand Up @@ -1475,3 +1475,19 @@ class Config:
'required': ['a'],
'examples': [{'a': 'Foo'}],
}


def test_model_with_extra_forbidden():
class Model(BaseModel):
a: str

class Config:
extra = Extra.forbid

assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
'additionalProperties': False,
}