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

Improve error message for NameEmail #6939

Merged
merged 1 commit into from Aug 16, 2023
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
6 changes: 5 additions & 1 deletion pydantic/networks.py
Expand Up @@ -250,7 +250,11 @@ def __get_pydantic_core_schema__(
import_email_validator()
return core_schema.general_after_validator_function(
cls._validate,
core_schema.union_schema([core_schema.is_instance_schema(cls), core_schema.str_schema()]),
core_schema.union_schema(
[core_schema.is_instance_schema(cls), core_schema.str_schema()],
custom_error_type='name_email_type',
custom_error_message='Input is not a valid NameEmail',
),
serialization=core_schema.to_string_ser_schema(),
)

Expand Down
6 changes: 6 additions & 0 deletions tests/test_networks.py
Expand Up @@ -820,3 +820,9 @@ class Model(BaseModel):
assert str(Model(v='foo bar <foobaR@example.com>').v) == 'foo bar <foobaR@example.com>'
assert NameEmail('foo bar', 'foobaR@example.com') == NameEmail('foo bar', 'foobaR@example.com')
assert NameEmail('foo bar', 'foobaR@example.com') != NameEmail('foo bar', 'different@example.com')

with pytest.raises(ValidationError) as exc_info:
Model(v=1)
assert exc_info.value.errors() == [
{'input': 1, 'loc': ('v',), 'msg': 'Input is not a valid NameEmail', 'type': 'name_email_type'}
]
Comment on lines +826 to +828
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On current main branch, you get:

[{'ctx': {'class': 'NameEmail'},
  'input': 1,
  'loc': ('v', 'is-instance[NameEmail]'),
  'msg': 'Input should be an instance of NameEmail',
  'type': 'is_instance_of',
  'url': 'https://errors.pydantic.dev/2.1/v/is_instance_of'},
 {'input': 1,
  'loc': ('v', 'str'),
  'msg': 'Input should be a valid string',
  'type': 'string_type',
  'url': 'https://errors.pydantic.dev/2.1/v/string_type'}]