Skip to content

Commit

Permalink
up: update action yml, add more unit tests for sub pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 20, 2022
1 parent de42d06 commit 83643b9
Show file tree
Hide file tree
Showing 22 changed files with 168 additions and 13 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ jobs:

- name: Run staticcheck
uses: reviewdog/action-staticcheck@v1
if: ${{ matrix.os == 'ubuntu-latest' and matrix.go_version == '1.18' }}
if: ${{ matrix.os == 'ubuntu-latest' && matrix.go_version == '1.18' }}
with:
github_token: ${{ secrets.github_token }}
# Change reviewdog reporter if you need [github-pr-check,github-check,github-pr-review].
Expand Down
2 changes: 1 addition & 1 deletion dump/dumper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func newStd() *Dumper {
}

func TestNewDefaultOptions(t *testing.T) {
opts := NewDefaultOptions(os.Stdout, 2)
opts := NewDefaultOptions(nil, 2)

assert.Equal(t, "<normal>text value</>", opts.ColorTheme.value("text value"))
}
Expand Down
22 changes: 22 additions & 0 deletions errorx/errorx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ func TestWithPrev_errorx_l2(t *testing.T) {
}

func TestStacked_goerr(t *testing.T) {
assert.Nil(t, errorx.Stacked(nil))

err1 := errorx.Raw("first error message")
assert.Error(t, err1)

Expand Down Expand Up @@ -184,13 +186,21 @@ func TestWrap(t *testing.T) {
fmt.Println("----------------S------------------")
err = errorx.Wrap(err, "second error message")
assert.Error(t, err)
_, ok := err.(*errorx.ErrorX)
assert.True(t, ok)
fmt.Println(err)

var ex *errorx.ErrorX
assert.True(t, errorx.To(err, &ex))
assert.Nil(t, ex.CallerFunc())
assert.Equal(t, "unknown", ex.Location())
assert.Equal(t, "", ex.StackString())
assert.Equal(t, "second error message", ex.Message())

ex, ok = errorx.ToErrorX(err)
assert.True(t, ok)
assert.Equal(t, "second error message", ex.Message())

fmt.Println("----------------T------------------")
err = errorx.Wrap(err, "third error message")
assert.Error(t, err)
Expand All @@ -200,6 +210,18 @@ func TestWrap(t *testing.T) {

assert.Equal(t, "first error message", errorx.Cause(err).Error())
assert.Contains(t, errorx.Unwrap(err).Error(), "second error message")

err = errorx.Wrap(nil, "error message")
assert.Error(t, err)
_, ok = err.(*errorx.ErrorX)
assert.False(t, ok)
_, ok = errorx.ToErrorX(err)
assert.False(t, ok)
}

func TestCause(t *testing.T) {
assert.Nil(t, errorx.Cause(nil))
assert.Nil(t, errorx.Unwrap(nil))
}

func TestWrapf(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions errorx/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,11 @@ type ErrStackOpt struct {
// default option
var stdOpt = newErrOpt()

// ResetStdOpt config
func ResetStdOpt() {
stdOpt = newErrOpt()
}

func newErrOpt() *ErrStackOpt {
return &ErrStackOpt{
SkipDepth: 3,
Expand Down
51 changes: 51 additions & 0 deletions errorx/stack_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package errorx

import (
"bytes"
"reflect"
"testing"

"github.com/stretchr/testify/assert"
)

func TestErrStackOpt(t *testing.T) {
defer ResetStdOpt()

assert.Equal(t, 3, stdOpt.SkipDepth)
assert.Equal(t, 8, stdOpt.TraceDepth)

Config(SkipDepth(5), TraceDepth(12))
assert.Equal(t, 5, stdOpt.SkipDepth)
assert.Equal(t, 12, stdOpt.TraceDepth)

}

func TestFuncForPC(t *testing.T) {
fn := FuncForPC(uintptr(0))
assert.Nil(t, fn)

fn = FuncForPC(reflect.ValueOf(Config).Pointer())
assert.Contains(t, fn.Location(), "gookit/goutil/errorx.Config()")
assert.Contains(t, fn.String(), "gookit/goutil/errorx/stack.go")

bs, err := fn.MarshalText()
assert.NoError(t, err)
str := string(bs)
assert.Contains(t, str, "gookit/goutil/errorx.Config()")
assert.Contains(t, str, "gookit/goutil/errorx/stack.go")
}

func TestStack_Format(t *testing.T) {
st := new(stack)
assert.Equal(t, 0, st.StackLen())

buf := new(bytes.Buffer)
_, err := st.WriteTo(buf)
assert.NoError(t, err)
assert.Equal(t, "", buf.String())
assert.Equal(t, uintptr(0), st.CallerPC())

st = callersStack(1, 5)
assert.True(t, st.StackLen() > 0)
assert.NotEmpty(t, st.StackFrames())
}
6 changes: 6 additions & 0 deletions errorx/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ func Unwrap(err error) error {
// Previous alias of Unwrap()
func Previous(err error) error { return Unwrap(err) }

// ToErrorX convert check
func ToErrorX(err error) (ex *ErrorX, ok bool) {
ex, ok = err.(*ErrorX)
return
}

// Has check err has contains target, or err is eq target.
// alias of errors.Is()
func Has(err, target error) bool {
Expand Down
3 changes: 2 additions & 1 deletion fmtutil/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func PrettyJSON(v interface{}) (string, error) {
return string(out), err
}

// StringsToInts string slice to int slice. alias of the arrutil.StringsToInts()
// StringsToInts string slice to int slice.
// Deprecated: please use the arrutil.StringsToInts()
func StringsToInts(ss []string) (ints []int, err error) {
for _, str := range ss {
iVal, err := strconv.Atoi(str)
Expand Down
8 changes: 8 additions & 0 deletions fmtutil/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func TestDataSize(t *testing.T) {
{346, "346B"},
{3467, "3.39K"},
{346778, "338.65K"},
{12346778, "11.77M"},
{1200346778, "1.12G"},
}

Expand All @@ -41,6 +42,13 @@ func TestPrettyJSON(t *testing.T) {
}
}

func TestArgsWithSpaces(t *testing.T) {
assert.Equal(t, "", fmtutil.ArgsWithSpaces(nil))
assert.Equal(t, "", fmtutil.ArgsWithSpaces([]interface{}{}))
assert.Equal(t, "abc", fmtutil.ArgsWithSpaces([]interface{}{"abc"}))
assert.Equal(t, "23 abc", fmtutil.ArgsWithSpaces([]interface{}{23, "abc"}))
}

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

Expand Down
1 change: 1 addition & 0 deletions fsutil/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func TestCommon(t *testing.T) {

// IsZipFile
assert.False(t, fsutil.IsZipFile("testdata/test.jpg"))
assert.Equal(t, "test.jpg", fsutil.PathName("testdata/test.jpg"))

assert.Equal(t, "test.jpg", fsutil.Name("path/to/test.jpg"))

Expand Down
4 changes: 2 additions & 2 deletions fsutil/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ func Dir(fpath string) string {
return filepath.Dir(fpath)
}

// PathName get file/dir name from fullpath
// PathName get file/dir name from full path
func PathName(fpath string) string {
return path.Base(fpath)
}

// Name get file/dir name from fullpath
// Name get file/dir name from full path
func Name(fpath string) string {
return filepath.Base(fpath)
}
Expand Down
2 changes: 1 addition & 1 deletion fsutil/operate.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func DeleteIfFileExist(fPath string) error {
func Unzip(archive, targetDir string) (err error) {
reader, err := zip.OpenReader(archive)
if err != nil {
return
return err
}

if err = os.MkdirAll(targetDir, DefaultDirPerm); err != nil {
Expand Down
4 changes: 4 additions & 0 deletions fsutil/operate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,7 @@ func TestMustCopyFile(t *testing.T) {
fsutil.MustCopyFile(srcPath, dstPath)
assert.Equal(t, []byte("hello"), fsutil.GetContents(dstPath))
}

func TestUnzip(t *testing.T) {
assert.Error(t, fsutil.Unzip("/path-not-exists", ""))
}
3 changes: 1 addition & 2 deletions jsonutil/jsonutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ func EncodeUnescapeHTML(v interface{}) ([]byte, error) {
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)

err := enc.Encode(v)
if err != nil {
if err := enc.Encode(v); err != nil {
return nil, err
}

Expand Down
5 changes: 5 additions & 0 deletions jsonutil/jsonutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ func TestEncode(t *testing.T) {
bts, err = jsonutil.Encode(&testUser)
assert.NoError(t, err)
assert.Equal(t, `{"name":"inhere","age":200}`, string(bts))

bts, err = jsonutil.EncodeUnescapeHTML(&testUser)
assert.NoError(t, err)
assert.Equal(t, `{"name":"inhere","age":200}
`, string(bts))
}

func TestEncodeUnescapeHTML(t *testing.T) {
Expand Down
6 changes: 3 additions & 3 deletions maputil/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ func ToStringMap(src map[string]interface{}) map[string]string {

// HttpQueryString convert map[string]interface{} data to http query string.
func HttpQueryString(data map[string]interface{}) string {
ss := make([]string, len(data))
ss := make([]string, 0, len(data))
for k, v := range data {
ss = append(ss, k+"="+strutil.MustString(v))
ss = append(ss, k+"="+strutil.QuietString(v))
}

return strings.Join(ss, "&")
Expand All @@ -53,7 +53,7 @@ func ToString(mp map[string]interface{}) string {
buf = append(buf, k...)
buf = append(buf, ':')

str, _ := strutil.AnyToString(val, false)
str := strutil.QuietString(val)
buf = append(buf, str...)
buf = append(buf, ',', ' ')
}
Expand Down
18 changes: 18 additions & 0 deletions maputil/convert_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package maputil_test

import (
"fmt"
"testing"

"github.com/gookit/goutil/dump"
Expand All @@ -24,6 +25,23 @@ func TestToStringMap(t *testing.T) {
assert.Equal(t, ret["b"], "23")
}

func TestHttpQueryString(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}
str := maputil.HttpQueryString(src)

fmt.Println(str)
assert.Contains(t, str, "b=23")
assert.Contains(t, str, "a=v0")
}

func TestToString2(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}

s := maputil.ToString2(src)
assert.Contains(t, s, "b:23")
assert.Contains(t, s, "a:v0")
}

func TestToString(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}

Expand Down
1 change: 0 additions & 1 deletion maputil/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ func (f *MapFormatter) FormatTo(w io.Writer) {

// Format to string
func (f *MapFormatter) String() string {
f.Format()
return f.Format()
}

Expand Down
12 changes: 12 additions & 0 deletions maputil/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,24 @@ import (
"testing"

"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/testutil"
"github.com/stretchr/testify/assert"
)

func TestNewFormatter(t *testing.T) {
mp := map[string]interface{}{"a": "v0", "b": 23}

mf := maputil.NewFormatter(mp)
assert.Contains(t, mf.String(), "b:23")

buf := testutil.NewTestWriter()
mf = maputil.NewFormatter(mp).WithFn(func(f *maputil.MapFormatter) {
f.Indent = " "
})
mf.FormatTo(buf)
assert.Contains(t, buf.String(), "\n ")
fmt.Println(buf.String())

s := maputil.FormatIndent(mp, " ")
fmt.Println(s)
assert.Contains(t, s, "\n ")
Expand Down
5 changes: 4 additions & 1 deletion maputil/smap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestSMap(t *testing.T) {
func TestSMap_usage(t *testing.T) {
mp := maputil.SMap{
"k1": "23",
"k2": "ab",
Expand All @@ -16,8 +16,10 @@ func TestSMap(t *testing.T) {
}

assert.True(t, mp.Has("k1"))
assert.True(t, mp.HasValue("true"))
assert.True(t, mp.Bool("k3"))
assert.False(t, mp.IsEmpty())
assert.False(t, mp.HasValue("not-exist"))

val, ok := mp.Value("k2")
assert.True(t, ok)
Expand All @@ -34,6 +36,7 @@ func TestSMap(t *testing.T) {
// slice
assert.Equal(t, []int{1, 2}, mp.Ints("k4"))
assert.Equal(t, []string{"1", "2"}, mp.Strings("k4"))
assert.Nil(t, mp.Strings("not-exist"))

// not exists
assert.False(t, mp.Bool("notExists"))
Expand Down
14 changes: 14 additions & 0 deletions mathutil/mathutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,23 @@ import (
"github.com/stretchr/testify/assert"
)

func TestMaxFloat(t *testing.T) {
assert.Equal(t, float64(3), mathutil.MaxFloat(2, 3))
}

func TestMaxI64(t *testing.T) {
assert.Equal(t, 3, mathutil.MaxInt(2, 3))
assert.Equal(t, 3, mathutil.MaxInt(3, 2))
assert.Equal(t, int64(3), mathutil.MaxI64(2, 3))
assert.Equal(t, int64(3), mathutil.MaxI64(3, 2))
}

func TestSwapMaxInt(t *testing.T) {
x, y := mathutil.SwapMaxInt(2, 34)
assert.Equal(t, 34, x)
assert.Equal(t, 2, y)

x64, y64 := mathutil.SwapMaxI64(2, 34)
assert.Equal(t, int64(34), x64)
assert.Equal(t, int64(2), y64)
}
5 changes: 5 additions & 0 deletions mathutil/number_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import (
"github.com/stretchr/testify/assert"
)

func TestIsNumeric(t *testing.T) {
assert.True(t, mathutil.IsNumeric('3'))
assert.False(t, mathutil.IsNumeric('a'))
}

func TestPercent(t *testing.T) {
assert.Equal(t, float64(34), mathutil.Percent(34, 100))
assert.Equal(t, float64(0), mathutil.Percent(34, 0))
Expand Down
2 changes: 2 additions & 0 deletions mathutil/random_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ func TestRandomInt(t *testing.T) {
val = RandomIntWithSeed(min, max, seed)
assert.True(t, val >= min)
}

assert.True(t, RandInt(min, max) > 999)
}

0 comments on commit 83643b9

Please sign in to comment.