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

Fix bug allowing validation of bool types with coerce_numbers_to_str=True #1017

Merged
merged 3 commits into from Oct 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
3 changes: 2 additions & 1 deletion src/input/input_python.rs
Expand Up @@ -246,10 +246,11 @@ impl<'a> Input<'a> for PyAny {
Err(_) => return Err(ValError::new(ErrorTypeDefaults::StringUnicode, self)),
};
Ok(s.into())
} else if coerce_numbers_to_str && {
} else if coerce_numbers_to_str && !PyBool::is_exact_type_of(self) && {
let py = self.py();
let decimal_type: Py<PyType> = get_decimal_type(py);

// only allow int, float, and decimal (not bool)
self.is_instance_of::<PyInt>()
|| self.is_instance_of::<PyFloat>()
|| self.is_instance(decimal_type.as_ref(py)).unwrap_or_default()
Expand Down
10 changes: 10 additions & 0 deletions tests/validators/test_string.py
Expand Up @@ -277,6 +277,16 @@ def test_coerce_numbers_to_str_disabled_in_strict_mode() -> None:
v.validate_json('42')


def test_coerce_numbers_to_str_raises_for_bool() -> None:
config = core_schema.CoreConfig(coerce_numbers_to_str=True)

v = SchemaValidator(core_schema.str_schema(), config)
with pytest.raises(ValidationError):
v.validate_python(True)
with pytest.raises(ValidationError):
v.validate_json(False)


@pytest.mark.parametrize(
('number', 'expected_str'),
[
Expand Down