File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
kadai4/hioki-daichi/jsonhelper Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Package jsonhelper is a collection of convenient functions for manipulating JSON.
3
+ */
4
+ package jsonhelper
5
+
6
+ import (
7
+ "bytes"
8
+ "encoding/json"
9
+ "io"
10
+ )
11
+
12
+ // ToJSON converts v to JSON.
13
+ func ToJSON (v interface {}) (string , error ) {
14
+ var buf bytes.Buffer
15
+ encoder := newEncoderFunc (& buf )
16
+ if err := encoder .Encode (v ); err != nil {
17
+ return "" , err
18
+ }
19
+ return buf .String (), nil
20
+ }
21
+
22
+ // for testing
23
+ type encoder interface {
24
+ Encode (v interface {}) error
25
+ }
26
+
27
+ // for testing
28
+ var newEncoderFunc = func (w io.Writer ) encoder {
29
+ return json .NewEncoder (w )
30
+ }
Original file line number Diff line number Diff line change
1
+ package jsonhelper
2
+
3
+ import (
4
+ "errors"
5
+ "io"
6
+ "testing"
7
+ )
8
+
9
+ func TestJsonhelper_ToJSON (t * testing.T ) {
10
+ foo := struct {
11
+ Bar string `json:"bar"`
12
+ Baz int `json:"baz"`
13
+ }{
14
+ Bar : "barbar" ,
15
+ Baz : 1 ,
16
+ }
17
+
18
+ actual , err := ToJSON (foo )
19
+ if err != nil {
20
+ t .Fatalf ("err %s" , err )
21
+ }
22
+ expected := "{\" bar\" :\" barbar\" ,\" baz\" :1}\n "
23
+ if actual != expected {
24
+ t .Errorf (`unexpected : expected: "%s" actual: "%s"` , expected , actual )
25
+ }
26
+ }
27
+
28
+ func TestJsonhelper_ToJSON_Error (t * testing.T ) {
29
+ expected := errInMock
30
+
31
+ newEncoderFunc = func (w io.Writer ) encoder { return & mockEncoder {} }
32
+
33
+ _ , actual := ToJSON (struct {}{})
34
+ if actual != expected {
35
+ t .Errorf (`unexpected : expected: "%s" actual: "%s"` , expected , actual )
36
+ }
37
+ }
38
+
39
+ var errInMock = errors .New ("error in mock" )
40
+
41
+ type mockEncoder struct {}
42
+
43
+ func (m * mockEncoder ) Encode (v interface {}) error { return errInMock }
You can’t perform that action at this time.
0 commit comments