github.com/metacurrency/holochain@v0.1.0-alpha-26.0.20200915073418-5c83169c9b5b/utils_test.go (about) 1 package holochain 2 3 import ( 4 "bytes" 5 "fmt" 6 . "github.com/smartystreets/goconvey/convey" 7 "testing" 8 "time" 9 ) 10 11 func TestUtilsEncodeDecode(t *testing.T) { 12 var data, data1 struct { 13 A int 14 B string 15 } 16 data.A = 314 17 data.B = "fish" 18 Convey("json", t, func() { 19 var b bytes.Buffer 20 err := Encode(&b, "json", data) 21 So(err, ShouldBeNil) 22 So(fmt.Sprintf("%v", string(b.Bytes())), ShouldEqual, "{\n \"A\": 314,\n \"B\": \"fish\"\n}\n") 23 err = Decode(&b, "json", &data1) 24 So(err, ShouldBeNil) 25 So(data.A, ShouldEqual, data1.A) 26 So(data.B, ShouldEqual, data1.B) 27 }) 28 data1.A = 0 29 data1.B = "" 30 Convey("yaml", t, func() { 31 var b bytes.Buffer 32 err := Encode(&b, "yaml", data) 33 So(err, ShouldBeNil) 34 So(fmt.Sprintf("%v", string(b.Bytes())), ShouldEqual, "A: 314\nB: fish\n") 35 err = Decode(&b, "yaml", &data1) 36 So(err, ShouldBeNil) 37 So(data.A, ShouldEqual, data1.A) 38 So(data.B, ShouldEqual, data1.B) 39 }) 40 data1.A = 0 41 data1.B = "" 42 Convey("toml", t, func() { 43 var b bytes.Buffer 44 err := Encode(&b, "toml", data) 45 So(err, ShouldBeNil) 46 So(fmt.Sprintf("%v", string(b.Bytes())), ShouldEqual, "A = 314\nB = \"fish\"\n") 47 err = Decode(&b, "toml", &data1) 48 So(err, ShouldBeNil) 49 So(data.A, ShouldEqual, data1.A) 50 So(data.B, ShouldEqual, data1.B) 51 }) 52 } 53 54 func TestUtilsDecodeFile(t *testing.T) { 55 var data, data1 struct { 56 A int 57 B string 58 } 59 data.A = 314 60 data.B = "fish" 61 var b bytes.Buffer 62 err := Encode(&b, "json", data) 63 if err != nil { 64 panic(err) 65 } 66 67 d := SetupTestDir() 68 defer CleanupTestDir(d) 69 70 if err := WriteFile(b.Bytes(), d, "testfile.json"); err != nil { 71 panic(err) 72 } 73 74 Convey("it should decode from a file", t, func() { 75 err = DecodeFile(&data1, d, "testfile.json") 76 So(err, ShouldBeNil) 77 So(data1.A, ShouldEqual, data.A) 78 So(data1.B, ShouldEqual, data.B) 79 }) 80 } 81 82 func TestTicker(t *testing.T) { 83 counter := make(chan int) 84 i := 0 85 stopper := Ticker(10*time.Millisecond, func() { 86 counter <- i + 1 87 }) 88 89 go func() { 90 c := <-counter 91 92 if c == 1 { 93 t.Log("it ticked once") 94 } 95 96 if c == 2 { 97 stopper <- true 98 t.Log("it ticked twice") 99 return 100 } 101 102 if c > 2 { 103 stopper <- true 104 t.Error("it ticked more than twice without ticking twice") 105 return 106 } 107 }() 108 } 109 110 func TestEncodingFormat(t *testing.T) { 111 Convey("it should return valid formats", t, func() { 112 So(EncodingFormat("dog.json"), ShouldEqual, "json") 113 So(EncodingFormat("/fish/cow/dog.yaml"), ShouldEqual, "yaml") 114 So(EncodingFormat("fish.toml"), ShouldEqual, "toml") 115 So(EncodingFormat("fish.xml"), ShouldEqual, "") 116 }) 117 }