forked from mtusi2026/mtusi2026lab3
74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package hashring
|
|
|
|
import (
|
|
"fmt"
|
|
"testing"
|
|
)
|
|
|
|
// TestExpansionMovesOnlyKeysOwnedByNewNode verifies the consistent hashing invariant.
|
|
func TestExpansionMovesOnlyKeysOwnedByNewNode(t *testing.T) {
|
|
before, err := New([]string{"a", "b"}, 256)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
after, err := New([]string{"c", "b", "a"}, 256)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
moved := 0
|
|
for index := range 100000 {
|
|
key := fmt.Sprint(index)
|
|
oldOwner, newOwner := before.Owner(key), after.Owner(key)
|
|
if oldOwner != newOwner {
|
|
moved++
|
|
if newOwner != "c" {
|
|
t.Fatalf("existing nodes exchanged key %s", key)
|
|
}
|
|
}
|
|
}
|
|
fraction := float64(moved) / 100000
|
|
if fraction < 0.2 || fraction > 0.45 {
|
|
t.Fatalf("unexpected moved fraction: %f", fraction)
|
|
}
|
|
t.Logf("100000 keys: moved=%d fraction=%.5f", moved, fraction)
|
|
}
|
|
|
|
// TestRingRejectsAmbiguousConfiguration checks independent malformed rings.
|
|
func TestRingRejectsAmbiguousConfiguration(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
nodes []string
|
|
replicas int
|
|
}{
|
|
{"empty", nil, 1},
|
|
{"zero replicas", []string{"a"}, 0},
|
|
{"empty node", []string{""}, 1},
|
|
{"duplicate", []string{"a", "a"}, 1},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
if _, err := New(tc.nodes, tc.replicas); err == nil {
|
|
t.Fatal("invalid ring accepted")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestRingIgnoresInputOrder verifies that replicas agree despite configuration ordering.
|
|
func TestRingIgnoresInputOrder(t *testing.T) {
|
|
a, err := New([]string{"a", "b"}, 64)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b, err := New([]string{"b", "a"}, 64)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for index := range 1000 {
|
|
key := fmt.Sprint(index)
|
|
if a.Owner(key) != b.Owner(key) {
|
|
t.Fatal("node order changes ownership")
|
|
}
|
|
}
|
|
}
|