Skip to content

Commit

Permalink
Update any_test.go
Browse files Browse the repository at this point in the history
  • Loading branch information
aacebo committed Oct 21, 2024
1 parent b2c6cf5 commit b01cf68
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions any_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package owl_test

import (
"encoding/json"
"errors"
"net"
"reflect"
"testing"
"time"

Expand Down Expand Up @@ -65,6 +68,52 @@ func TestAny(t *testing.T) {
})
})

t.Run("rule", func(t *testing.T) {
t.Run("should succeed on valid ipv4 address", func(t *testing.T) {
err := owl.Any().Rule("ipv4", nil, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}

if ip := net.ParseIP(value.String()); ip == nil {
return nil, errors.New("must be a valid ipv4 address")
}

return value.String(), nil
}).Validate("192.168.0.1")

if err != nil {
t.Fatal(err)
}
})

t.Run("should error on invalid ipaddress", func(t *testing.T) {
err := owl.Any().Rule("ipv4", nil, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}

if ip := net.ParseIP(value.String()); ip == nil {
return nil, errors.New("must be a valid ipv4 address")
}

return value.String(), nil
}).Validate("192.168.0")

if err == nil {
t.FailNow()
}

if err.Error() != `{"errors":[{"rule":"ipv4","message":"must be a valid ipv4 address"}]}` {
t.Errorf(
"expected `%s`, received `%s`",
`{"errors":[{"rule":"ipv4","message":"must be a valid ipv4 address"}]}`,
err.Error(),
)
}
})
})

t.Run("json", func(t *testing.T) {
t.Run("serialize", func(t *testing.T) {
schema := owl.Any().Enum(1, true, "hi").Required()
Expand Down Expand Up @@ -129,3 +178,25 @@ func ExampleAny() {
panic(err)
}
}

func ExampleAnySchema_Rule() {
schema := owl.Any().Rule("ipv4", nil, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}

if ip := net.ParseIP(value.String()); ip == nil {
return nil, errors.New("must be a valid ipv4 address")
}

return value.String(), nil
})

if err := schema.Validate("192.168.0.1"); err != nil { // nil
panic(err)
}

if err := schema.Validate("192.168.0"); err != nil { // error
panic(err)
}
}

0 comments on commit b01cf68

Please sign in to comment.