-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_test.go
46 lines (41 loc) · 1.02 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
package geko_test
import (
"encoding/json"
"errors"
"reflect"
"testing"
)
// This file only contains helper function
// real tests for json processing are placed in test file of each types.
type s struct {
S string `json:"s"`
}
func marshalWillReportError[T error](t *testing.T, v any) {
_, err := json.Marshal(v)
if err == nil {
t.Fatalf("Marshal %s type without error", reflect.TypeOf(v).Name())
}
var typeErr T
if !errors.As(err, &typeErr) {
t.Fatalf(
"Marshal %s type error is not %s",
reflect.TypeOf(v).Elem().Name(),
reflect.TypeOf(typeErr).Elem().Name(),
)
}
}
func unmarshalWillReportError[T error](t *testing.T, data string, v any) {
typ := reflect.TypeOf(v).Elem().Name()
err := json.Unmarshal([]byte(data), &v)
if err == nil {
t.Fatalf("Unmarshal *%s type without error", typ)
}
var typeErr T
if !errors.As(err, &typeErr) {
t.Logf("Unmarshal error: %s", err.Error())
t.Fatalf(
"Unmarshal *%s type error is not excepted type, it's %s", typ,
reflect.TypeOf(err).Elem().Name(),
)
}
}