Skip to content

Set info.data and info.field_name for dataclass field validators #454

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

Merged
merged 2 commits into from
Mar 17, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/validators/dataclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ impl Validator for DataclassArgsValidator {
let mut errors: Vec<ValLineError> = Vec::new();
let mut used_keys: AHashSet<&str> = AHashSet::with_capacity(self.fields.len());

let extra = Extra {
data: Some(output_dict),
..*extra
};

macro_rules! set_item {
($field:ident, $value:expr) => {{
let py_name = $field.py_name.as_ref(py);
Expand All @@ -147,6 +152,10 @@ impl Validator for DataclassArgsValidator {
($args:ident, $get_method:ident, $get_macro:ident, $slice_macro:ident) => {{
// go through fields getting the value from args or kwargs and validating it
for (index, field) in self.fields.iter().enumerate() {
let extra = Extra {
field_name: Some(&field.name),
..extra
};
Copy link
Collaborator

Choose a reason for hiding this comment

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

This seems necessary, but do we have any benchmarks that would pick up on performance impact of this? Not sure it matters.

let mut pos_value = None;
if let Some(args) = $args.args {
if !field.kw_only {
Expand Down Expand Up @@ -175,7 +184,7 @@ impl Validator for DataclassArgsValidator {
(Some(pos_value), None) => {
match field
.validator
.validate(py, pos_value, extra, slots, recursion_guard)
.validate(py, pos_value, &extra, slots, recursion_guard)
{
Ok(value) => set_item!(field, value),
Err(ValError::LineErrors(line_errors)) => {
Expand All @@ -192,7 +201,7 @@ impl Validator for DataclassArgsValidator {
(None, Some(kw_value)) => {
match field
.validator
.validate(py, kw_value, extra, slots, recursion_guard)
.validate(py, kw_value, &extra, slots, recursion_guard)
{
Ok(value) => set_item!(field, value),
Err(ValError::LineErrors(line_errors)) => {
Expand Down
165 changes: 165 additions & 0 deletions tests/validators/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,3 +421,168 @@ def test_dataclass_exact_validation(input_value, expected):
v = SchemaValidator(schema)
foo = v.validate_python(input_value)
assert dataclasses.asdict(foo) == expected


def test_dataclass_field_after_validator():
@dataclasses.dataclass
class Foo:
a: int
b: str

@classmethod
def validate_b(cls, v: str, info: core_schema.ModelFieldValidationInfo) -> str:
assert v == 'hello'
assert info.field_name == 'b'
assert info.data == {'a': 1}
return 'hello world!'

schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.int_schema()),
core_schema.dataclass_field(
name='b',
schema=core_schema.field_after_validation_function(Foo.validate_b, core_schema.str_schema()),
),
],
),
)

v = SchemaValidator(schema)
foo = v.validate_python({'a': 1, 'b': b'hello'})
assert dataclasses.asdict(foo) == {'a': 1, 'b': 'hello world!'}


def test_dataclass_field_plain_validator():
@dataclasses.dataclass
class Foo:
a: int
b: str

@classmethod
def validate_b(cls, v: bytes, info: core_schema.ModelFieldValidationInfo) -> str:
assert v == b'hello'
assert info.field_name == 'b'
assert info.data == {'a': 1}
return 'hello world!'

schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.int_schema()),
core_schema.dataclass_field(
name='b', schema=core_schema.field_plain_validation_function(Foo.validate_b)
),
],
),
)

v = SchemaValidator(schema)
foo = v.validate_python({'a': 1, 'b': b'hello'})
assert dataclasses.asdict(foo) == {'a': 1, 'b': 'hello world!'}


def test_dataclass_field_before_validator():
@dataclasses.dataclass
class Foo:
a: int
b: str

@classmethod
def validate_b(cls, v: bytes, info: core_schema.ModelFieldValidationInfo) -> bytes:
assert v == b'hello'
assert info.field_name == 'b'
assert info.data == {'a': 1}
return b'hello world!'

schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.int_schema()),
core_schema.dataclass_field(
name='b',
schema=core_schema.field_before_validation_function(Foo.validate_b, core_schema.str_schema()),
),
],
),
)

v = SchemaValidator(schema)
foo = v.validate_python({'a': 1, 'b': b'hello'})
assert dataclasses.asdict(foo) == {'a': 1, 'b': 'hello world!'}


def test_dataclass_field_wrap_validator1():
@dataclasses.dataclass
class Foo:
a: int
b: str

@classmethod
def validate_b(
cls, v: bytes, nxt: core_schema.CallableValidator, info: core_schema.ModelFieldValidationInfo
) -> str:
assert v == b'hello'
v = nxt(v)
assert v == 'hello'
assert info.field_name == 'b'
assert info.data == {'a': 1}
return 'hello world!'

schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.int_schema()),
core_schema.dataclass_field(
name='b',
schema=core_schema.field_wrap_validation_function(Foo.validate_b, core_schema.str_schema()),
),
],
),
)

v = SchemaValidator(schema)
foo = v.validate_python({'a': 1, 'b': b'hello'})
assert dataclasses.asdict(foo) == {'a': 1, 'b': 'hello world!'}


def test_dataclass_field_wrap_validator2():
@dataclasses.dataclass
class Foo:
a: int
b: str

@classmethod
def validate_b(
cls, v: bytes, nxt: core_schema.CallableValidator, info: core_schema.ModelFieldValidationInfo
) -> bytes:
assert v == b'hello'
assert info.field_name == 'b'
assert info.data == {'a': 1}
return nxt(b'hello world!')

schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.int_schema()),
core_schema.dataclass_field(
name='b',
schema=core_schema.field_wrap_validation_function(Foo.validate_b, core_schema.str_schema()),
),
],
),
)

v = SchemaValidator(schema)
foo = v.validate_python({'a': 1, 'b': b'hello'})
assert dataclasses.asdict(foo) == {'a': 1, 'b': 'hello world!'}