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

Avoid using ? with get_item to handle unhashable inputs properly #1089

Merged
merged 4 commits into from Nov 22, 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
5 changes: 4 additions & 1 deletion src/validators/literal.rs
Expand Up @@ -136,7 +136,10 @@ impl<T: Debug> LiteralLookup<T> {
}
// must be an enum or bytes
if let Some(expected_py) = &self.expected_py {
if let Some(v) = expected_py.as_ref(py).get_item(input)? {
// We don't use ? to unpack the result of `get_item` in the next line because unhashable
// inputs will produce a TypeError, which in this case we just want to treat equivalently
// to a failed lookup
if let Ok(Some(v)) = expected_py.as_ref(py).get_item(input) {
let id: usize = v.extract().unwrap();
return Ok(Some((input, &self.values[id])));
}
Expand Down
32 changes: 32 additions & 0 deletions tests/validators/test_union.py
Expand Up @@ -771,3 +771,35 @@ class BinaryEnum(IntEnum):
assert validator.validate_python(1) is not BinaryEnum.ONE
assert validator.validate_python(BinaryEnum.ZERO) is BinaryEnum.ZERO
assert validator.validate_python(BinaryEnum.ONE) is BinaryEnum.ONE


def test_model_and_literal_union() -> None:
# see https://github.com/pydantic/pydantic/issues/8183
class ModelA:
pass

validator = SchemaValidator(
{
'type': 'union',
'choices': [
{
'type': 'model',
'cls': ModelA,
'schema': {
'type': 'model-fields',
'fields': {
'a': {'type': 'model-field', 'schema': {'type': 'int'}},
},
},
},
{'type': 'literal', 'expected': [True]},
],
}
)

# validation against Literal[True] fails bc of the unhashable dict
# A ValidationError is raised, not a ValueError, which allows the validation against the union to continue
m = validator.validate_python({'a': 42})
assert isinstance(m, ModelA)
assert m.a == 42
assert validator.validate_python(True) is True