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

Raise validation error when unhashable items added to a set #1619

Merged
merged 9 commits into from
Feb 6, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions python/pydantic_core/core_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -4037,6 +4037,7 @@ def definition_reference_schema(
'list_type',
'tuple_type',
'set_type',
'set_item_not_hashable',
'bool_type',
'bool_parsing',
'int_type',
Expand Down
2 changes: 2 additions & 0 deletions src/errors/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ error_types! {
// ---------------------
// set errors
SetType {},
SetItemNotHashable {},
// ---------------------
// bool errors
BoolType {},
Expand Down Expand Up @@ -513,6 +514,7 @@ impl ErrorType {
Self::ListType {..} => "Input should be a valid list",
Self::TupleType {..} => "Input should be a valid tuple",
Self::SetType {..} => "Input should be a valid set",
Self::SetItemNotHashable {..} => "Set items should be hashable",
Self::BoolType {..} => "Input should be a valid boolean",
Self::BoolParsing {..} => "Input should be a valid boolean, unable to interpret input",
Self::IntType {..} => "Input should be a valid integer",
Expand Down
24 changes: 21 additions & 3 deletions src/input/return_enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,25 @@ impl BuildSet for Bound<'_, PyFrozenSet> {
}
}

fn validate_add<'py>(
py: Python<'py>,
set: &impl BuildSet,
item: impl BorrowInput<'py>,
state: &mut ValidationState<'_, 'py>,
validator: &CombinedValidator,
) -> ValResult<()> {
let validated_item = validator.validate(py, item.borrow_input(), state)?;
match set.build_add(validated_item) {
Ok(()) => Ok(()),
Err(err) => {
if err.matches(py, py.get_type::<PyTypeError>())? {
return Err(ValError::new(ErrorTypeDefaults::SetItemNotHashable, item));
}
Err(err)?
}
}
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn validate_iter_to_set<'py>(
py: Python<'py>,
Expand All @@ -216,9 +235,8 @@ pub(crate) fn validate_iter_to_set<'py>(
false => PartialMode::Off,
};
let item = item_result.map_err(|e| any_next_error!(py, e, input, index))?;
match validator.validate(py, item.borrow_input(), state) {
Ok(item) => {
set.build_add(item)?;
match validate_add(py, set, item, state, validator) {
Ok(()) => {
if let Some(max_length) = max_length {
if set.build_len() > max_length {
return Err(ValError::new(
Expand Down
1 change: 1 addition & 0 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ def f(input_value, info):
('iteration_error', 'Error iterating over object, error: foobar', {'error': 'foobar'}),
('list_type', 'Input should be a valid list', None),
('tuple_type', 'Input should be a valid tuple', None),
('set_item_not_hashable', 'Set items should be hashable', None),
('set_type', 'Input should be a valid set', None),
('bool_type', 'Input should be a valid boolean', None),
('bool_parsing', 'Input should be a valid boolean, unable to interpret input', None),
Expand Down
16 changes: 16 additions & 0 deletions tests/validators/test_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,22 @@ def test_set_multiple_errors():
]


def test_list_with_unhashable_items():
v = SchemaValidator({'type': 'set'})

class Unhashable:
__hash__ = None

unhashable = Unhashable()

with pytest.raises(ValidationError) as exc_info:
v.validate_python([{'a': 'b'}, unhashable])
assert exc_info.value.errors(include_url=False) == [
{'type': 'set_item_not_hashable', 'loc': (0,), 'msg': 'Set items should be hashable', 'input': {'a': 'b'}},
{'type': 'set_item_not_hashable', 'loc': (1,), 'msg': 'Set items should be hashable', 'input': unhashable},
]


def generate_repeats():
for i in 1, 2, 3:
yield i
Expand Down
Loading