forked from libp2p/go-libp2p-raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec_test.go
116 lines (96 loc) · 1.88 KB
/
codec_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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package libp2praft
import (
"bytes"
"encoding/json"
"io"
"testing"
consensus "github.com/libp2p/go-libp2p-consensus"
)
type marshable struct {
A string
}
func (m *marshable) Marshal(w io.Writer) error {
enc := json.NewEncoder(w)
return enc.Encode(m)
}
func (m *marshable) Unmarshal(r io.Reader) error {
dec := json.NewDecoder(r)
return dec.Decode(m)
}
type testState struct {
A int
B string
C simple
}
type simple struct {
D int
}
func TestEncodeDecodeSnapshot_Marshable(t *testing.T) {
m := &marshable{A: "testing"}
var buf bytes.Buffer
err := EncodeSnapshot(m, &buf)
if err != nil {
t.Fatal(err)
}
if string(buf.Bytes()) != `{"A":"testing"}`+"\n" {
t.Fatal("expected json encoding: ", string(buf.Bytes()))
}
m2 := &marshable{}
err = DecodeSnapshot(consensus.State(m2), &buf)
if err != nil {
t.Fatal(err)
}
if m2.A != m.A {
t.Fatal("bad marshable decoding")
}
}
func TestEncodeDecodeSnapshot(t *testing.T) {
var buf bytes.Buffer
um := &simple{D: 25}
err := EncodeSnapshot(um, &buf)
if err != nil {
t.Fatal(err)
}
um2 := &simple{}
err = DecodeSnapshot(um2, &buf)
if err != nil {
t.Fatal(err)
}
if um2.D != um.D {
t.Fatal("bad unmarshable decoding")
}
buf.Reset()
st := &testState{
A: 5,
B: "hola",
C: simple{
D: 1,
},
}
err = EncodeSnapshot(st, &buf)
if err != nil {
t.Fatal(err)
}
stmp := consensus.State(&testState{})
err = DecodeSnapshot(stmp, &buf)
if err != nil {
t.Fatal(err)
}
newst := stmp.(*testState)
t.Logf("st: %p newst: %p", &st, &newst)
if &st == &newst {
t.Fatal("both states are the same pointer")
}
t.Logf("st: %v newst: %v", &st, &newst)
if st.A != newst.A || st.B != newst.B || st.C.D != newst.C.D {
t.Error("dup object is different")
}
st.B = "adios"
if newst.B != "hola" {
t.Fatal("side modifications")
}
st.C.D = 6
if newst.C.D == 6 {
t.Fatal("side modifications in nested object")
}
}