github.com/aergoio/aergo@v1.3.1/p2p/p2putil/util_test.go (about) 1 /* 2 * @file 3 * @copyright defined in aergo/LICENSE.txt 4 */ 5 6 package p2putil 7 8 import ( 9 "fmt" 10 "github.com/aergoio/aergo/types" 11 "net/url" 12 "strconv" 13 "sync" 14 "sync/atomic" 15 "testing" 16 "time" 17 18 "github.com/aergoio/aergo/internal/enc" 19 "github.com/gofrs/uuid" 20 lru "github.com/hashicorp/golang-lru" 21 addrutil "github.com/libp2p/go-addr-util" 22 ma "github.com/multiformats/go-multiaddr" 23 mnet "github.com/multiformats/go-multiaddr-net" 24 "github.com/stretchr/testify/assert" 25 ) 26 27 const SampleAddrString = "/ip4/172.21.11.12/tcp/3456" 28 const NetAddrString = "172.21.11.12:3456" 29 30 func TestGetIP(t *testing.T) { 31 t.Skip("skip test cause infinite loop in Goland IDE") 32 33 addrInput, _ := ma.NewMultiaddr(SampleAddrString) 34 35 netAddr, err := mnet.ToNetAddr(addrInput) 36 if err != nil { 37 t.Errorf("Invalid func %s", err.Error()) 38 } 39 fmt.Printf("net Addr : %s", netAddr.String()) 40 if NetAddrString != netAddr.String() { 41 t.Errorf("Expected %s, but actually %s", NetAddrString, netAddr) 42 } 43 44 addrInput, _ = ma.NewMultiaddr(SampleAddrString + "/ipfs/16Uiu2HAkvvhjxVm2WE9yFBDdPQ9qx6pX9taF6TTwDNHs8VPi1EeR") 45 netAddr, err = mnet.ToNetAddr(addrInput) 46 if nil == err { 47 t.Errorf("Error expected, but not") 48 } 49 50 } 51 func TestLookupAddress(t *testing.T) { 52 ip, err := ExternalIP() 53 if err != nil { 54 fmt.Println(err) 55 } 56 fmt.Println(ip) 57 58 } 59 60 func TestAddrUtil(t *testing.T) { 61 addrs, err := addrutil.InterfaceAddresses() 62 if err != nil { 63 t.Errorf("Test Error: %s", err.Error()) 64 } 65 fmt.Printf("Addrs : %s\n", addrs) 66 fmt.Println("Over") 67 } 68 69 /* 70 func Test_debugLogReceiveMsg(t *testing.T) { 71 logger := log.NewLogger("test.p2p") 72 peerID, _ := types.IDB58Decode("16Uiu2HAkvvhjxVm2WE9yFBDdPQ9qx6pX9taF6TTwDNHs8VPi1EeR") 73 peer := &remotePeerImpl{meta: p2pcommon.PeerMeta{ID: peerID}, name: ShortForm(peerID) + "@1"} 74 msgID := uuid.Must(uuid.NewV4()).String() 75 dummyArray := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} 76 type args struct { 77 protocol p2pcommon.SubProtocol 78 additional interface{} 79 } 80 tests := []struct { 81 name string 82 args args 83 }{ 84 {"nil", args{subproto.PingRequest, nil}}, 85 {"int", args{subproto.PingResponse, len(msgID)}}, 86 {"pointer", args{subproto.StatusRequest, &logger}}, 87 {"array", args{subproto.StatusRequest, dummyArray}}, 88 {"string", args{subproto.StatusRequest, "string addition"}}, 89 {"obj", args{subproto.PingRequest, P2P{}}}, 90 {"lazy", args{subproto.PingRequest, log.DoLazyEval(func() string { 91 return "Length is " + strconv.Itoa(len(dummyArray)) 92 })}}, 93 // TODO: Add test cases. 94 } 95 for _, tt := range tests { 96 t.Run(tt.name, func(t *testing.T) { 97 DebugLogReceiveMsg(logger, tt.args.protocol, msgID, peer, tt.args.additional) 98 }) 99 } 100 } 101 */ 102 func Test_Encode(t *testing.T) { 103 tests := []struct { 104 name string 105 in []byte 106 out string 107 }{ 108 {"TEmpty", []byte(""), ""}, 109 {"TNil", nil, ""}, 110 {"TOnlyone", []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, "11111111111111111111111111111111"}, 111 } 112 for _, test := range tests { 113 t.Run(test.name, func(t *testing.T) { 114 got := enc.ToString(test.in) 115 assert.Equal(t, test.out, got) 116 if len(test.out) > 0 { 117 gotBytes, err := enc.ToBytes(test.out) 118 assert.Nil(t, err) 119 assert.Equal(t, test.in, gotBytes) 120 } 121 }) 122 } 123 } 124 125 // experiment, and manually checked it 126 func TestExperiment_TimerBehavior(t *testing.T) { 127 t.Skip(" experiment, do manual check") 128 counter := int32(0) 129 ticked := make(chan int32) 130 duration := time.Millisecond * 50 131 target := time.AfterFunc(duration, func() { 132 fmt.Printf("Timer fired! %d \n", atomic.LoadInt32(&counter)) 133 atomic.AddInt32(&counter, 1) 134 ticked <- counter 135 }) 136 assert.Equal(t, int32(1), <-ticked) 137 fmt.Println("Waking up") 138 stopResult := target.Stop() 139 assert.Equal(t, false, stopResult) 140 for i := 2; i < 10; i++ { 141 target.Reset(duration * 2) 142 assert.Equal(t, int32(i), <-ticked) 143 } 144 } 145 146 func TestFailNormalMapInConcurrent(t *testing.T) { 147 t.Skip(" experiment, do manual check") 148 iterSize := 10000 149 target := make(map[string]string) 150 wg := sync.WaitGroup{} 151 waitChan := make(chan int) 152 wg.Add(1) 153 go func() { 154 for i := 0; i < iterSize; i++ { 155 target[strconv.Itoa(i)] = "var " + strconv.Itoa(i) 156 if i == (iterSize >> 2) { 157 wg.Done() 158 } 159 } 160 }() 161 162 go func() { 163 wg.Wait() 164 // for key, val := range target { 165 // fmt.Printf("%s is %s\n", key, val) 166 // } 167 fmt.Printf("%d values after ", len(target)) 168 waitChan <- 0 169 }() 170 171 <-waitChan 172 fmt.Printf("Remains %d\n", len(target)) 173 } 174 175 func TestSyncMap(t *testing.T) { 176 iterSize := 1000 177 target := sync.Map{} 178 wg := sync.WaitGroup{} 179 waitChan := make(chan int) 180 wg.Add(1) 181 go func() { 182 for i := 0; i < iterSize; i++ { 183 target.Store(strconv.Itoa(i), "var "+strconv.Itoa(i)) 184 if i == (iterSize >> 2) { 185 wg.Done() 186 } 187 } 188 }() 189 190 go func() { 191 wg.Wait() 192 // target.Range(func(key interface{}, val interface{}) bool { 193 // fmt.Printf("%s is %s\n", key, val) 194 // return true 195 // }) 196 waitChan <- 0 197 }() 198 199 <-waitChan 200 fmt.Printf("Remains %d\n", func(m *sync.Map) int { 201 keys := make([]string, 0, iterSize*2) 202 m.Range(func(key interface{}, val interface{}) bool { 203 keys = append(keys, key.(string)) 204 return true 205 }) 206 // fmt.Println(keys) 207 return len(keys) 208 }(&target)) 209 } 210 211 var dummyPeerID types.PeerID 212 var dummyPeerID2 types.PeerID 213 214 func init() { 215 dummyPeerID, _ = types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm") 216 dummyPeerID2, _ = types.IDB58Decode("16Uiu2HAmU8Wc925gZ5QokM4sGDKjysdPwRCQFoYobvoVnyutccCD") 217 } 218 219 func TestComparePeerID(t *testing.T) { 220 samplePeerID := dummyPeerID 221 samplePeerID2 := dummyPeerID2 222 shorterPeerID := types.PeerID(string(([]byte(samplePeerID))[:len(string(samplePeerID))-1])) 223 fmt.Println("Sample1", []byte(string(samplePeerID))) 224 fmt.Println("Sample2", []byte(string(samplePeerID2))) 225 fmt.Println("Shorter", []byte(string(shorterPeerID))) 226 tests := []struct { 227 name string 228 p1 types.PeerID 229 p2 types.PeerID 230 want int 231 }{ 232 {"TP1", samplePeerID, samplePeerID2, 1}, 233 {"TP2", samplePeerID, shorterPeerID, 1}, 234 {"TZ", samplePeerID, samplePeerID, 0}, 235 // TODO: Add test cases. 236 } 237 for _, tt := range tests { 238 t.Run(tt.name, func(t *testing.T) { 239 if got := ComparePeerID(tt.p1, tt.p2); sign(got) != tt.want { 240 t.Errorf("ComparePeerID() = %v, want %v", got, tt.want) 241 } 242 if got := ComparePeerID(tt.p2, tt.p1); sign(got) != tt.want*(-1) { 243 t.Errorf("ComparePeerID() = %v, want %v", got, tt.want*(-1)) 244 } 245 }) 246 } 247 } 248 249 func sign(value int) int { 250 if value > 0 { 251 return 1 252 } else if value == 0 { 253 return 0 254 } else { 255 return -1 256 } 257 } 258 259 func TestLRUCache(t *testing.T) { 260 size := 100 261 target, _ := lru.New(10) 262 263 var testSlice [16]byte 264 265 t.Run("TArray", func(t *testing.T) { 266 // var samples = make([]([hashSize]byte), size) 267 for i := 0; i < size; i++ { 268 copy(testSlice[:], uuid.Must(uuid.NewV4()).Bytes()) 269 target.Add(testSlice, i) 270 271 assert.True(t, target.Len() <= 10) 272 } 273 }) 274 } 275 276 func TestParseURI(t *testing.T) { 277 tests := []struct { 278 name string 279 280 arg string 281 282 wantErr bool 283 wantIP bool 284 wantPort bool 285 }{ 286 {"Thttp", "http://172.121.33.4:1111", false, true, true}, 287 {"Thttps", "https://172.121.33.4:1111", false, true, true}, 288 {"TMultiAddr", "/ip4/172.121.33.4/tcp/1111", false, false, false}, 289 } 290 for _, tt := range tests { 291 t.Run(tt.name, func(t *testing.T) { 292 got, err := url.ParseRequestURI(tt.arg) 293 if err != nil { 294 t.Logf("Got addr %v", got) 295 } 296 if (err != nil) != tt.wantErr { 297 t.Errorf("ParseRequestURI() err %v , wantErr %v", err, tt.wantErr) 298 } 299 if !tt.wantErr { 300 if (len(got.Host) >0 ) != tt.wantIP { 301 t.Errorf("ParseRequestURI() Host %v , want %v", got.Host, tt.wantIP) 302 } 303 if (len(got.Port()) >0 ) != tt.wantPort { 304 t.Errorf("ParseRequestURI() Port %v , want %v", got.Port(), tt.wantPort) 305 } 306 } 307 308 }) 309 } 310 }