Skip to content

Commit

Permalink
Raise validation error when unhashable items added to a set (#1619)
Browse files Browse the repository at this point in the history
Co-authored-by: JONEMI21 <michael.jones2@kingfisher.com>
  • Loading branch information
mikeedjones and JONEMI21 authored Feb 6, 2025
1 parent 0862ea5 commit f7fb50b
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 3 deletions.
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

0 comments on commit f7fb50b

Please sign in to comment.