Skip to content

Commit

Permalink
test: add unit test for custom formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
smacker committed Jul 26, 2024
1 parent 8033e05 commit 71fac32
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1300,6 +1300,28 @@ func TestValidate(t *testing.T) {
}
}

func TestValidateCustomFormatter(t *testing.T) {
originalFormatter := huma.ErrorFormatter
defer func() {
huma.ErrorFormatter = originalFormatter
}()

huma.ErrorFormatter = func(format string, a ...any) string {
return fmt.Sprintf("custom: %v", a)
}

registry := huma.NewMapRegistry("#/components/schemas/", huma.DefaultSchemaNamer)
s := registry.Schema(reflect.TypeOf(struct {
Value string `json:"value" format:"email"`
}{}), true, "TestInput")
pb := huma.NewPathBuffer([]byte(""), 0)
res := &huma.ValidateResult{}

huma.Validate(registry, s, pb, huma.ModeReadFromServer, map[string]any{"value": "alice"}, res)
assert.Len(t, res.Errors, 1)
assert.Equal(t, "custom: [mail: missing '@' or angle-addr] (value: alice)", res.Errors[0].Error())
}

func ExampleModelValidator() {
// Define a type you want to validate.
type Model struct {
Expand Down

0 comments on commit 71fac32

Please sign in to comment.