Skip to content

Commit

Permalink
✅ test: all - add more unit test cases for some util func
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 16, 2023
1 parent a3c2084 commit f929fe1
Show file tree
Hide file tree
Showing 12 changed files with 260 additions and 10 deletions.
53 changes: 53 additions & 0 deletions byteutil/byteutil_test.go
Expand Up @@ -3,12 +3,23 @@ package byteutil_test
import (
"errors"
"testing"
"time"

"github.com/gookit/goutil/byteutil"
"github.com/gookit/goutil/testutil/assert"
"github.com/gookit/goutil/timex"
)

func TestRandom(t *testing.T) {
bs, err := byteutil.Random(10)
assert.NoError(t, err)
assert.Len(t, bs, 10)

bs, err = byteutil.Random(0)
assert.NoError(t, err)
assert.Len(t, bs, 0)
}

func TestFirstLine(t *testing.T) {
bs := []byte("hi\ninhere")
assert.Eq(t, []byte("hi"), byteutil.FirstLine(bs))
Expand All @@ -34,12 +45,54 @@ func TestMd5(t *testing.T) {
assert.NotEmpty(t, byteutil.Md5([]int{12, 34}))
}

func TestToString(t *testing.T) {
assert.Eq(t, "123", byteutil.String([]byte("123")))
assert.Eq(t, "123", byteutil.ToString([]byte("123")))
}

func TestAppendAny(t *testing.T) {
assert.Eq(t, []byte("123"), byteutil.AppendAny(nil, 123))
assert.Eq(t, []byte("123"), byteutil.AppendAny([]byte{}, 123))
assert.Eq(t, []byte("123"), byteutil.AppendAny([]byte("1"), 23))
assert.Eq(t, []byte("1<nil>"), byteutil.AppendAny([]byte("1"), nil))
assert.Eq(t, "3600000000000", string(byteutil.AppendAny([]byte{}, timex.OneHour)))

tests := []struct {
dst []byte
v any
exp []byte
}{
{nil, 123, []byte("123")},
{[]byte{}, 123, []byte("123")},
{[]byte("1"), 23, []byte("123")},
{[]byte("1"), nil, []byte("1<nil>")},
{[]byte{}, timex.OneHour, []byte("3600000000000")},
{[]byte{}, int8(123), []byte("123")},
{[]byte{}, int16(123), []byte("123")},
{[]byte{}, int32(123), []byte("123")},
{[]byte{}, int64(123), []byte("123")},
{[]byte{}, uint(123), []byte("123")},
{[]byte{}, uint8(123), []byte("123")},
{[]byte{}, uint16(123), []byte("123")},
{[]byte{}, uint32(123), []byte("123")},
{[]byte{}, uint64(123), []byte("123")},
{[]byte{}, float32(123), []byte("123")},
{[]byte{}, float64(123), []byte("123")},
{[]byte{}, "123", []byte("123")},
{[]byte{}, []byte("123"), []byte("123")},
{[]byte{}, []int{1, 2, 3}, []byte("[1 2 3]")},
{[]byte{}, []string{"1", "2", "3"}, []byte("[1 2 3]")},
{[]byte{}, true, []byte("true")},
{[]byte{}, errors.New("error msg"), []byte("error msg")},
}

for _, tt := range tests {
assert.Eq(t, tt.exp, byteutil.AppendAny(tt.dst, tt.v))
}

tim, err := time.Parse(time.RFC3339, "2019-01-01T00:00:00Z")
assert.NoError(t, err)
assert.Eq(t, []byte("2019-01-01T00:00:00Z"), byteutil.AppendAny(nil, tim))
}

func TestCut(t *testing.T) {
Expand Down
46 changes: 46 additions & 0 deletions fmtutil/fmtutil_test.go
@@ -0,0 +1,46 @@
package fmtutil_test

import (
"bytes"
"testing"

"github.com/gookit/goutil/fmtutil"
"github.com/gookit/goutil/testutil/assert"
)

func TestStringOrJSON(t *testing.T) {
t.Run("string input", func(t *testing.T) {
input := "Hello, world!"
expected := []byte(input)
actual, err := fmtutil.StringOrJSON(input)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !bytes.Equal(expected, actual) {
t.Errorf("expected %q, but got %q", expected, actual)
}
})

t.Run("JSON input", func(t *testing.T) {
input := map[string]any{
"foo": "bar",
"baz": 123,
}

actual, err := fmtutil.StringOrJSON(input)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

assert.StrContains(t, string(actual), `"foo": "bar"`)
assert.StrContains(t, string(actual), `"baz": 123`)
})

t.Run("invalid JSON input", func(t *testing.T) {
input := make(chan int) // channel is not JSON-serializable
_, err := fmtutil.StringOrJSON(input)
if err == nil {
t.Error("expected error, but got nil")
}
})
}
48 changes: 48 additions & 0 deletions fsutil/finder/config_test.go
@@ -0,0 +1,48 @@
package finder_test

import (
"testing"

"github.com/gookit/goutil/fsutil/finder"
"github.com/gookit/goutil/testutil/assert"
)

func TestBasic_func(t *testing.T) {
assert.Eq(t, finder.FlagBoth, finder.ToFlag("b"))
assert.Eq(t, finder.FlagBoth, finder.ToFlag("both"))
assert.Eq(t, finder.FlagFile, finder.ToFlag(""))
assert.Eq(t, finder.FlagFile, finder.ToFlag("file"))
assert.Eq(t, finder.FlagDir, finder.ToFlag("dir"))
}

func TestFinder_Config(t *testing.T) {
ff := finder.NewEmpty().ConfigFn(func(c *finder.Config) {
c.IncludeNames = []string{"name1"}
})

ff.AddScan("/some/path/dir").
FileAndDir().
WithExts([]string{".go"}).
WithFileExt(".mod").
WithoutFile(".keep").
CacheResult(false)

assert.NotEmpty(t, ff.Config())
}

func TestConfig_NewFinder(t *testing.T) {
c := finder.NewConfig()
c.IncludePaths = []string{"path/to"}
c.ExcludePaths = []string{"exclude/path"}
c.ExcludeDirs = []string{"dir1"}
c.IncludeExts = []string{".go"}
c.ExcludeFiles = []string{".keep"}

ff := c.NewFinder()
ff.UseAbsPath(true).
CacheResult(true).
WithoutDotFile(true)
ff.IncludeExt(".txt")

assert.NotEmpty(t, ff.Config())
}
3 changes: 0 additions & 3 deletions netutil/netutil.go
Expand Up @@ -36,14 +36,12 @@ func InternalIP() (ip string) {
if addr.IsValid() {
return addr.String()
}

return ""
}

// InternalIPv4 get internal IPv4
func InternalIPv4() (ip string) {
addr := netip.IPv4Unspecified()

if addr.IsValid() {
return addr.String()
}
Expand All @@ -53,7 +51,6 @@ func InternalIPv4() (ip string) {
// InternalIPv6 get internal IPv6
func InternalIPv6() (ip string) {
addr := netip.IPv6Unspecified()

if addr.IsValid() {
return addr.String()
}
Expand Down
2 changes: 2 additions & 0 deletions netutil/netutil_test.go
Expand Up @@ -9,4 +9,6 @@ import (

func TestInternalIP(t *testing.T) {
assert.NotEmpty(t, netutil.InternalIP())
assert.NotEmpty(t, netutil.InternalIPv4())
assert.NotEmpty(t, netutil.InternalIPv6())
}
52 changes: 52 additions & 0 deletions reflects/README.md
Expand Up @@ -16,6 +16,58 @@ go get github.com/gookit/goutil/reflects

## Usage

```go
import "github.com/gookit/goutil/reflects"

// get struct field value
reflects.GetFieldValue(obj, "Name")
```

## Functions API

> **Note**: doc by run `go doc ./reflects`
```go
func BaseTypeVal(v reflect.Value) (value any, err error)
func ConvSlice(oldSlRv reflect.Value, newElemTyp reflect.Type) (rv reflect.Value, err error)
func EachMap(mp reflect.Value, fn func(key, val reflect.Value))
func EachStrAnyMap(mp reflect.Value, fn func(key string, val any))
func Elem(v reflect.Value) reflect.Value
func FlatMap(rv reflect.Value, fn FlatFunc)
func HasChild(v reflect.Value) bool
func Indirect(v reflect.Value) reflect.Value
func IsAnyInt(k reflect.Kind) bool
func IsArrayOrSlice(k reflect.Kind) bool
func IsEmpty(v reflect.Value) bool
func IsEmptyValue(v reflect.Value) bool
func IsEqual(src, dst any) bool
func IsFunc(val any) bool
func IsIntx(k reflect.Kind) bool
func IsNil(v reflect.Value) bool
func IsSimpleKind(k reflect.Kind) bool
func IsUintX(k reflect.Kind) bool
func Len(v reflect.Value) int
func SetRValue(rv, val reflect.Value)
func SetUnexportedValue(rv reflect.Value, value any)
func SetValue(rv reflect.Value, val any) error
func SliceElemKind(typ reflect.Type) reflect.Kind
func SliceSubKind(typ reflect.Type) reflect.Kind
func String(rv reflect.Value) string
func ToString(rv reflect.Value) (str string, err error)
func UnexportedValue(rv reflect.Value) any
func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error)
func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error)
func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error)
type BKind uint
func ToBKind(kind reflect.Kind) BKind
func ToBaseKind(kind reflect.Kind) BKind
type FlatFunc func(path string, val reflect.Value)
type Type interface{ ... }
func TypeOf(v any) Type
type Value struct{ ... }
func ValueOf(v any) Value
func Wrap(rv reflect.Value) Value
```

## Testings

Expand Down
4 changes: 2 additions & 2 deletions reflects/check.go
Expand Up @@ -32,12 +32,12 @@ func IsAnyInt(k reflect.Kind) bool {
return k >= reflect.Int && k <= reflect.Uintptr
}

// IsIntx check is intX or uintX type
// IsIntx check is intX type
func IsIntx(k reflect.Kind) bool {
return k >= reflect.Int && k <= reflect.Int64
}

// IsUintX check is intX or uintX type
// IsUintX check is uintX type
func IsUintX(k reflect.Kind) bool {
return k >= reflect.Uint && k <= reflect.Uintptr
}
Expand Down
26 changes: 25 additions & 1 deletion reflects/check_test.go
Expand Up @@ -32,14 +32,18 @@ func TestIsEqual(t *testing.T) {

is.False(reflects.IsEqual(nil, "abc"))
is.False(reflects.IsEqual("abc", nil))

is.False(reflects.IsEqual("abc", 123))
is.True(reflects.IsEqual(123, 123))
is.True(reflects.IsEqual([]byte{}, []byte{}))
is.True(reflects.IsEqual([]byte("abc"), []byte("abc")))
is.False(reflects.IsEqual([]byte("abc"), 123))
}

func TestIsEmpty(t *testing.T) {
is := assert.New(t)

is.True(reflects.IsEmpty(reflect.ValueOf(nil)))
is.True(reflects.IsEmpty(reflect.ValueOf(false)))
is.True(reflects.IsEmpty(reflect.ValueOf("")))
is.True(reflects.IsEmpty(reflect.ValueOf([]string{})))
is.True(reflects.IsEmpty(reflect.ValueOf(map[int]string{})))
Expand All @@ -59,6 +63,7 @@ func TestIsEmptyValue(t *testing.T) {

is.True(reflects.IsEmptyValue(reflect.ValueOf(nil)))
is.True(reflects.IsEmptyValue(reflect.ValueOf("")))
is.True(reflects.IsEmptyValue(reflect.ValueOf(false)))
is.True(reflects.IsEmptyValue(reflect.ValueOf([]string{})))
is.True(reflects.IsEmptyValue(reflect.ValueOf(map[int]string{})))
is.True(reflects.IsEmptyValue(reflect.ValueOf(0)))
Expand All @@ -70,6 +75,9 @@ func TestIsEmptyValue(t *testing.T) {
}
rv := reflect.ValueOf(T{}).Field(0)
is.True(reflects.IsEmptyValue(rv))

rv = reflect.ValueOf(&T{v: "abc"})
is.False(reflects.IsEmptyValue(rv))
}

func TestIsSimpleKind(t *testing.T) {
Expand All @@ -92,3 +100,19 @@ func TestIsSimpleKind(t *testing.T) {
})
}
}

func TestIsAnyInt(t *testing.T) {
// test for IsAnyInt
assert.True(t, reflects.IsAnyInt(reflect.Int))
assert.True(t, reflects.IsAnyInt(reflect.Int8))
assert.True(t, reflects.IsAnyInt(reflect.Uint))
assert.False(t, reflects.IsAnyInt(reflect.Func))

// test for IsIntx
assert.True(t, reflects.IsIntx(reflect.Int))
assert.False(t, reflects.IsIntx(reflect.Uint))

// test for IsUintX()
assert.True(t, reflects.IsUintX(reflect.Uint16))
assert.False(t, reflects.IsUintX(reflect.Int))
}
2 changes: 1 addition & 1 deletion strutil/textutil/textutil.go
@@ -1,4 +1,4 @@
// Package textutil provide some extra text handle util
// Package textutil provide some extensions text handle util functions.
package textutil

import (
Expand Down
1 change: 1 addition & 0 deletions sysutil/sysutil_test.go
Expand Up @@ -10,6 +10,7 @@ import (
)

func TestBasic_usage(t *testing.T) {
assert.NotEmpty(t, sysutil.BinDir())
assert.NotEmpty(t, sysutil.BinDir())
assert.NotEmpty(t, sysutil.BinFile())
}
Expand Down
3 changes: 0 additions & 3 deletions sysutil/user_nonwin.go
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows

package sysutil

Expand All @@ -12,7 +11,6 @@ import (
// ChangeUserByName change work user by new username.
func ChangeUserByName(newUname string) (err error) {
u := MustFindUser(newUname)

// syscall.Setlogin(newUname)
return ChangeUserUidGid(strutil.IntOrPanic(u.Uid), strutil.IntOrPanic(u.Gid))
}
Expand All @@ -27,6 +25,5 @@ func ChangeUserUidGid(newUID int, newGid int) (err error) {
err = syscall.Setgid(newGid)
}
}

return
}

0 comments on commit f929fe1

Please sign in to comment.