Skip to content

Commit

Permalink
Merge pull request #19 from pasqal-io/yoric/validator
Browse files Browse the repository at this point in the history
[Fix] After validation, let's not forget to copy the validated result
  • Loading branch information
Yoric authored Jan 20, 2025
2 parents ea81c70 + 76df7aa commit b6187ef
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion deserialize/deserialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,9 @@ func makeStructDeserializerFromReflect(path string, typ reflect.Type, options in
mightValidate := resultPtr.Interface()
if validator, ok := mightValidate.(validation.Validator); ok {
err = validator.Validate()
if err != nil {
if err == nil {
outPtr.Set(result) // Note: Wait, are we copying everything here?
} else {
// Validation error, abort struct construction, wrap the error so that we can catch it.
err = validation.WrapError(path, err)
result = reflect.Zero(typ)
Expand Down
23 changes: 23 additions & 0 deletions deserialize/deserialize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1580,3 +1580,26 @@ func TestKVDeserializeUnderlyingPrimitiveSlices(t *testing.T) {
assert.NilError(t, err)
assert.DeepEqual(t, *deserialized, sample)
}

// --- Testing side-effects during validation.

type TestValidateModifyStruct struct {
A string
}

func (t *TestValidateModifyStruct) Validate() error {
t.A = strings.ToLower(t.A)
return nil
}

func TestValidateModify(t *testing.T) {
kvlist := make(map[string][]string)
kvlist["A"] = []string{"ABC"}

deserializer, err := deserialize.MakeKVListDeserializer[TestValidateModifyStruct](deserialize.JSONOptions(""))
assert.NilError(t, err)
deserialized, err := deserializer.DeserializeKVList(kvlist)
assert.NilError(t, err)
fmt.Println(*deserialized)
assert.Equal(t, deserialized.A, "abc")
}

0 comments on commit b6187ef

Please sign in to comment.