forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fmtutil_test.go
46 lines (39 loc) · 1.01 KB
/
fmtutil_test.go
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
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")
}
})
}