File size: 1,520 Bytes
ca7217f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | package testkit
import (
"encoding/json"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type ValidateFunc func(*testing.T, any)
func logJSONContent() ValidateFunc {
return func(t *testing.T, a any) {
data, err := json.MarshalIndent(a, "", "\t")
require.NoError(t, err)
// Print out JSON data.
t.Logf("%s", data)
}
}
func assertIsValid() ValidateFunc {
return func(t *testing.T, a any) {
if v, ok := a.(interface{ IsValid() bool }); ok {
assert.True(t, v.IsValid())
return
}
// must be a slice.
require.Equal(t, reflect.Slice, reflect.TypeOf(a).Kind())
s := reflect.ValueOf(a)
for i := 0; i < s.Len(); i++ {
x := s.Index(i).Interface()
require.Implements(t, (*interface{ IsValid() bool })(nil), x)
assert.True(t, x.(interface{ IsValid() bool }).IsValid())
}
}
}
func FieldsNotEmpty(fields ...string) ValidateFunc {
return func(t *testing.T, a any) {
for _, field := range fields {
f, err := getStructFieldByName(a, field)
require.NoError(t, err)
assert.NotEmptyf(t, f, "field is empty: %s", field)
}
}
}
func FieldsNotEmptyAny(fields ...string) ValidateFunc {
return func(t *testing.T, a any) {
ok := false
for _, field := range fields {
f, err := getStructFieldByName(a, field)
if err != nil {
continue
}
z := reflect.Zero(reflect.ValueOf(f).Type())
if !reflect.DeepEqual(f, z.Interface()) {
ok = true
}
}
assert.Truef(t, ok, "fields are all empty: %v", fields)
}
}
|