Files
bt/dht/blacklist_test.go

84 lines
2.0 KiB
Go
Raw Normal View History

2020-06-07 13:43:15 +08:00
// Copyright 2020 xgfone
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dht
import (
2023-03-01 22:50:46 +08:00
"net"
2020-06-07 13:43:15 +08:00
"testing"
"time"
2023-03-01 22:50:46 +08:00
2023-04-01 21:07:18 +08:00
"github.com/xgfone/go-bt/krpc"
2020-06-07 13:43:15 +08:00
)
func (bl *blacklist) portsLen() (n int) {
bl.lock.RLock()
for _, wp := range bl.ips {
n += len(wp.Ports)
}
bl.lock.RUnlock()
return
}
func (bl *blacklist) getIPs() []string {
bl.lock.RLock()
ips := make([]string, 0, len(bl.ips))
for ip := range bl.ips {
ips = append(ips, ip)
}
bl.lock.RUnlock()
return ips
}
func TestMemoryBlacklist(t *testing.T) {
bl := NewMemoryBlacklist(3, time.Second).(*blacklist)
defer bl.Close()
2023-03-01 22:50:46 +08:00
bl.Add(krpc.NewAddr(net.ParseIP("1.1.1.1"), 123))
bl.Add(krpc.NewAddr(net.ParseIP("1.1.1.1"), 456))
bl.Add(krpc.NewAddr(net.ParseIP("1.1.1.1"), 789))
bl.Add(krpc.NewAddr(net.ParseIP("2.2.2.2"), 111))
bl.Add(krpc.NewAddr(net.ParseIP("3.3.3.3"), 0))
bl.Add(krpc.NewAddr(net.ParseIP("4.4.4.4"), 222))
2020-06-07 13:43:15 +08:00
ips := bl.getIPs()
if len(ips) != 3 {
t.Error(ips)
} else {
for _, ip := range ips {
switch ip {
case "1.1.1.1", "2.2.2.2", "3.3.3.3":
default:
t.Error(ip)
}
}
}
if n := bl.portsLen(); n != 4 {
t.Errorf("expect port num 4, but got %d", n)
}
2023-03-01 22:50:46 +08:00
if bl.In(krpc.NewAddr(net.ParseIP("1.1.1.1"), 111)) || !bl.In(krpc.NewAddr(net.ParseIP("1.1.1.1"), 123)) {
2020-06-07 13:43:15 +08:00
t.Fail()
}
2023-03-01 22:50:46 +08:00
if !bl.In(krpc.NewAddr(net.ParseIP("3.3.3.3"), 111)) || bl.In(krpc.NewAddr(net.ParseIP("4.4.4.4"), 222)) {
2020-06-07 13:43:15 +08:00
t.Fail()
}
2023-03-01 22:50:46 +08:00
bl.Del(krpc.NewAddr(net.ParseIP("3.3.3.3"), 0))
if bl.In(krpc.NewAddr(net.ParseIP("3.3.3.3"), 111)) {
2020-06-07 13:43:15 +08:00
t.Fail()
}
}