-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson_test.go
81 lines (64 loc) · 1.45 KB
/
json_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package nine
import (
"bytes"
"errors"
"fmt"
"io"
"testing"
)
func TestJSON(t *testing.T) {
username := "gabrielluizsf"
json := JSON{"username": username}
validateBytes(t, json, username)
}
func TestGenericJSON(t *testing.T) {
username := "gopher"
json := GenericJSON[string, string]{"username": username}
validateBytes(t, json, username)
}
func validateBytes(t *testing.T, json Buffer, username string) {
b, err := json.Bytes()
if err != nil {
t.Fatal(err)
}
result := string(b)
expected := fmt.Sprintf(`{"username":"%s"}`, username)
if result != expected {
t.Fatalf("result: %s expected: %s", result, expected)
}
var user struct {
Username string `json:"username"`
}
if err := DecodeJSON(b, &user); err != nil {
t.Fatal(err)
}
if user.Username != username {
t.Fatal("user not decoded")
}
buf, err := json.Buffer()
if err != nil {
t.Fatal(err)
}
if _, ok := any(buf).(io.Reader); !ok {
t.Fatal("buf does not implement io.Reader")
}
if _, ok := any(buf).(io.Writer); !ok {
t.Fatal("buf does not implement io.Writer")
}
}
func TestBuffer(t *testing.T) {
json := fakeJSON{}
validateBuffer(t, json)
}
func validateBuffer(t *testing.T, json Buffer) {
if _, err := buffer(json); err == nil {
t.Fatal("expected error, got nil")
}
}
type fakeJSON struct{}
func (b fakeJSON) Bytes() ([]byte, error) {
return nil, errors.New("error")
}
func (b fakeJSON) Buffer() (*bytes.Buffer, error) {
return nil, errors.New("error")
}