Files
NTrace-core/trace/mtr_stats_test.go
T
tsosunchia 77abf1b515 Refactor MTR signal handling and context management
- Unified signal handling in MTR CLI using `signal.NotifyContext(...)` for Ctrl-C/SIGTERM, removing the need for separate `sigCh` and goroutine.
- Updated `runMTRTUI`, `runMTRReport`, and `runMTRRaw` functions to utilize the new context management.
- Enhanced `mtrUI` to safely call `cancel()` only if it is not nil.
- Modified `IPDBOneClient` to clone HTTP clients with timeout settings, ensuring proper timeout handling without modifying global state.
- Adjusted raw aggregation keys in the frontend to collapse based on TTL, improving display of timeout/success results.
- Added context support in various tracer functions to allow cancellation and timeout handling.
- Improved error handling and test coverage for MTR operations, ensuring robustness against nil results and empty responses.
- Refined DNS resolver functions to use mutexes for thread-safe access to the geo resolver override.
2026-03-06 14:07:58 +08:00

781 lines
19 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package trace
import (
"math"
"net"
"testing"
"time"
"github.com/nxtrace/NTrace-core/ipgeo"
)
func mkHop(ttl int, ip string, rtt time.Duration) Hop {
return Hop{
Success: true,
Address: &net.IPAddr{IP: net.ParseIP(ip)},
TTL: ttl,
RTT: rtt,
}
}
func mkTimeoutHop(ttl int) Hop {
return Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
}
}
func mkResult(hopsByTTL ...[]Hop) *Result {
res := &Result{
Hops: make([][]Hop, len(hopsByTTL)),
}
copy(res.Hops, hopsByTTL)
return res
}
func roundN(v float64, n int) float64 {
pow := math.Pow(10, float64(n))
return math.Round(v*pow) / pow
}
func TestSinglePath(t *testing.T) {
agg := NewMTRAggregator()
res1 := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 10*time.Millisecond)},
[]Hop{mkHop(2, "2.2.2.2", 20*time.Millisecond)},
)
agg.Update(res1, 1)
res2 := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 12*time.Millisecond)},
[]Hop{mkHop(2, "2.2.2.2", 18*time.Millisecond)},
)
agg.Update(res2, 1)
res3 := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 14*time.Millisecond)},
[]Hop{mkHop(2, "2.2.2.2", 22*time.Millisecond)},
)
stats := agg.Update(res3, 1)
if len(stats) != 2 {
t.Fatalf("expected 2 rows, got %d", len(stats))
}
s := stats[0]
if s.TTL != 1 {
t.Errorf("TTL: want 1, got %d", s.TTL)
}
if s.Snt != 3 {
t.Errorf("Snt: want 3, got %d", s.Snt)
}
if s.Received != 3 {
t.Errorf("Received: want 3, got %d", s.Received)
}
if s.Loss != 0 {
t.Errorf("Loss: want 0, got %f", s.Loss)
}
if s.Last != 14 {
t.Errorf("Last: want 14, got %f", s.Last)
}
if s.Best != 10 {
t.Errorf("Best: want 10, got %f", s.Best)
}
if s.Wrst != 14 {
t.Errorf("Wrst: want 14, got %f", s.Wrst)
}
if roundN(s.Avg, 4) != 12 {
t.Errorf("Avg: want 12, got %f", s.Avg)
}
if roundN(s.StDev, 4) != 2.0 {
t.Errorf("StDev: want 2.0, got %f", s.StDev)
}
s2 := stats[1]
if s2.TTL != 2 {
t.Errorf("TTL: want 2, got %d", s2.TTL)
}
if s2.Snt != 3 {
t.Errorf("Snt: want 3, got %d", s2.Snt)
}
if roundN(s2.Avg, 4) != 20 {
t.Errorf("Avg: want 20, got %f", s2.Avg)
}
if roundN(s2.StDev, 4) != 2.0 {
t.Errorf("StDev: want 2.0, got %f", s2.StDev)
}
}
func TestMultiPath(t *testing.T) {
agg := NewMTRAggregator()
res1 := mkResult(
[]Hop{
mkHop(1, "10.0.0.1", 5*time.Millisecond),
mkHop(1, "10.0.0.2", 8*time.Millisecond),
},
)
stats := agg.Update(res1, 2)
if len(stats) != 2 {
t.Fatalf("expected 2 rows for multipath, got %d", len(stats))
}
if stats[0].TTL != 1 || stats[1].TTL != 1 {
t.Errorf("both rows should be TTL=1")
}
ips := map[string]bool{stats[0].IP: true, stats[1].IP: true}
if !ips["10.0.0.1"] || !ips["10.0.0.2"] {
t.Errorf("expected both IPs")
}
res2 := mkResult([]Hop{mkHop(1, "10.0.0.1", 6*time.Millisecond)})
stats = agg.Update(res2, 1)
for _, s := range stats {
if s.IP == "10.0.0.1" && s.Snt != 2 {
t.Errorf("10.0.0.1 sent: want 2, got %d", s.Snt)
}
if s.IP == "10.0.0.2" && s.Snt != 1 {
t.Errorf("10.0.0.2 sent: want 1, got %d", s.Snt)
}
}
}
func TestErrorMix(t *testing.T) {
// 同 TTL: 2 次成功 (IP=1.1.1.1) + 1 次 timeout。
// 单路径归并后应只剩 1 行,Snt=3,Received=2,Loss≈33.3%。
agg := NewMTRAggregator()
res := mkResult(
[]Hop{
mkHop(1, "1.1.1.1", 10*time.Millisecond),
mkHop(1, "1.1.1.1", 20*time.Millisecond),
mkTimeoutHop(1),
},
)
stats := agg.Update(res, 3)
if len(stats) != 1 {
t.Fatalf("expected 1 row after merge, got %d", len(stats))
}
s := stats[0]
if s.IP != "1.1.1.1" {
t.Errorf("IP: want 1.1.1.1, got %q", s.IP)
}
if s.Snt != 3 {
t.Errorf("Snt: want 3, got %d", s.Snt)
}
if s.Received != 2 {
t.Errorf("Received: want 2, got %d", s.Received)
}
wantLoss := roundN(100.0/3.0, 1) // 33.3
gotLoss := roundN(s.Loss, 1)
if gotLoss != wantLoss {
t.Errorf("Loss: want %.1f%%, got %.1f%%", wantLoss, gotLoss)
}
}
func TestGeoPropagation(t *testing.T) {
agg := NewMTRAggregator()
geoData := &ipgeo.IPGeoData{Country: "US", City: "San Francisco"}
hop := mkHop(1, "1.1.1.1", 10*time.Millisecond)
hop.Geo = geoData
res := mkResult([]Hop{hop})
stats := agg.Update(res, 1)
if len(stats) != 1 {
t.Fatalf("expected 1 row, got %d", len(stats))
}
if stats[0].Geo == nil {
t.Fatal("expected geo data, got nil")
}
if stats[0].Geo.Country != "US" {
t.Errorf("Country: want US, got %s", stats[0].Geo.Country)
}
}
func TestStDevSingleSample(t *testing.T) {
agg := NewMTRAggregator()
res := mkResult([]Hop{mkHop(1, "1.1.1.1", 10*time.Millisecond)})
stats := agg.Update(res, 1)
if len(stats) != 1 {
t.Fatalf("expected 1 row, got %d", len(stats))
}
if stats[0].StDev != 0 {
t.Errorf("StDev with 1 sample: want 0, got %f", stats[0].StDev)
}
}
func TestAllTimeout(t *testing.T) {
agg := NewMTRAggregator()
res := mkResult([]Hop{mkTimeoutHop(1), mkTimeoutHop(1), mkTimeoutHop(1)})
stats := agg.Update(res, 3)
if len(stats) != 1 {
t.Fatalf("expected 1 row, got %d", len(stats))
}
s := stats[0]
if s.Snt != 3 {
t.Errorf("Snt: want 3, got %d", s.Snt)
}
if s.Received != 0 {
t.Errorf("Received: want 0, got %d", s.Received)
}
if s.Loss != 100 {
t.Errorf("Loss: want 100, got %f", s.Loss)
}
if s.Avg != 0 || s.Best != 0 || s.Wrst != 0 || s.StDev != 0 {
t.Errorf("all RTT should be 0 for all-timeout")
}
}
func TestUpdate_NilResult(t *testing.T) {
agg := NewMTRAggregator()
if got := agg.Update(nil, 1); got != nil {
t.Fatalf("Update(nil, 1) = %v, want nil", got)
}
if got := agg.Update(&Result{}, 1); got != nil {
t.Fatalf("Update(empty result, 1) = %v, want nil", got)
}
}
func TestHostnamePropagation(t *testing.T) {
agg := NewMTRAggregator()
hop := mkHop(1, "1.1.1.1", 10*time.Millisecond)
hop.Hostname = "one.one.one.one"
res := mkResult([]Hop{hop})
stats := agg.Update(res, 1)
if len(stats) != 1 {
t.Fatalf("expected 1 row, got %d", len(stats))
}
if stats[0].Host != "one.one.one.one" {
t.Errorf("Host: want one.one.one.one, got %s", stats[0].Host)
}
}
func TestMTRAggregator_Reset(t *testing.T) {
agg := NewMTRAggregator()
res := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 10*time.Millisecond)},
[]Hop{mkHop(2, "2.2.2.2", 20*time.Millisecond)},
)
agg.Update(res, 1)
agg.Update(res, 1)
// Reset 后 Snapshot 应为空
agg.Reset()
snap := agg.Snapshot()
if len(snap) != 0 {
t.Fatalf("expected 0 rows after Reset, got %d", len(snap))
}
// Reset 后继续 Update 应正常工作,Snt 从 1 重新开始
stats := agg.Update(res, 1)
if len(stats) != 2 {
t.Fatalf("expected 2 rows after re-update, got %d", len(stats))
}
if stats[0].Snt != 1 {
t.Errorf("Snt after reset: want 1, got %d", stats[0].Snt)
}
}
func TestMTRAggregator_CloneIsolation(t *testing.T) {
agg := NewMTRAggregator()
res1 := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 10*time.Millisecond)},
)
agg.Update(res1, 1)
// Clone
clone := agg.Clone()
// 修改原始聚合器
res2 := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 20*time.Millisecond)},
)
agg.Update(res2, 1)
// Clone 快照应只有 1 次发送
cloneSnap := clone.Snapshot()
if len(cloneSnap) != 1 {
t.Fatalf("clone: expected 1 row, got %d", len(cloneSnap))
}
if cloneSnap[0].Snt != 1 {
t.Errorf("clone Snt: want 1, got %d", cloneSnap[0].Snt)
}
// 原始聚合器应有 2 次发送
origSnap := agg.Snapshot()
if origSnap[0].Snt != 2 {
t.Errorf("original Snt: want 2, got %d", origSnap[0].Snt)
}
// 修改 Clone 不影响原始
res3 := mkResult(
[]Hop{mkHop(1, "1.1.1.1", 30*time.Millisecond)},
)
clone.Update(res3, 1)
cloneSnap = clone.Snapshot()
if cloneSnap[0].Snt != 2 {
t.Errorf("clone Snt after update: want 2, got %d", cloneSnap[0].Snt)
}
origSnap = agg.Snapshot()
if origSnap[0].Snt != 2 {
t.Errorf("original Snt should still be 2, got %d", origSnap[0].Snt)
}
}
// TestUnknownMergedAfterLaterReply_SinglePath 验证跨轮次归并:
// Round1: TTL1 timeout → Round2: TTL1 reply(IP=A)。
// 结果应只有 A 一行,Snt=2,Received=1,Loss=50%。
func TestUnknownMergedAfterLaterReply_SinglePath(t *testing.T) {
agg := NewMTRAggregator()
// Round 1: timeout
r1 := mkResult([]Hop{mkTimeoutHop(1)})
stats := agg.Update(r1, 1)
if len(stats) != 1 {
t.Fatalf("round1: expected 1 row, got %d", len(stats))
}
// Round 2: real reply
r2 := mkResult([]Hop{mkHop(1, "10.0.0.1", 15*time.Millisecond)})
stats = agg.Update(r2, 1)
if len(stats) != 1 {
t.Fatalf("round2: expected 1 row after merge, got %d", len(stats))
}
s := stats[0]
if s.IP != "10.0.0.1" {
t.Errorf("IP: want 10.0.0.1, got %q", s.IP)
}
if s.Snt != 2 {
t.Errorf("Snt: want 2, got %d", s.Snt)
}
if s.Received != 1 {
t.Errorf("Received: want 1, got %d", s.Received)
}
if s.Loss != 50 {
t.Errorf("Loss: want 50, got %f", s.Loss)
}
}
// TestUnknownPreserved_Multipath 验证多路径下 unknown 不被归并。
func TestUnknownPreserved_Multipath(t *testing.T) {
agg := NewMTRAggregator()
res := mkResult(
[]Hop{
mkHop(1, "10.0.0.1", 5*time.Millisecond),
mkHop(1, "10.0.0.2", 8*time.Millisecond),
mkTimeoutHop(1),
},
)
stats := agg.Update(res, 3)
// 应有 3 行:10.0.0.1、10.0.0.2、unknown
if len(stats) != 3 {
t.Fatalf("expected 3 rows for multipath+timeout, got %d", len(stats))
}
ips := map[string]bool{}
hasUnknown := false
for _, s := range stats {
if s.IP != "" {
ips[s.IP] = true
}
if s.IP == "" && s.Host == "" {
hasUnknown = true
}
}
if !ips["10.0.0.1"] || !ips["10.0.0.2"] {
t.Error("expected both known IPs")
}
if !hasUnknown {
t.Error("expected unknown row preserved in multipath scenario")
}
}
// ---------------------------------------------------------------------------
// ClearHop 测试
// ---------------------------------------------------------------------------
func TestMTRAggregator_ClearHop_RemovesData(t *testing.T) {
agg := NewMTRAggregator()
// Record stats at TTL 5
res := mkResult(
nil, nil, nil, nil,
[]Hop{mkHop(5, "10.0.0.99", 5*time.Millisecond)},
)
agg.Update(res, 1)
// Verify TTL 5 exists
snap := agg.Snapshot()
found := false
for _, s := range snap {
if s.TTL == 5 {
found = true
}
}
if !found {
t.Fatal("expected TTL 5 in snapshot before ClearHop")
}
// Clear TTL 5
agg.ClearHop(5)
// Verify TTL 5 is gone
snap = agg.Snapshot()
for _, s := range snap {
if s.TTL == 5 {
t.Error("TTL 5 should not exist after ClearHop")
}
}
}
func TestMTRAggregator_ClearHop_NoopIfMissing(t *testing.T) {
agg := NewMTRAggregator()
// Record stats at TTL 3 only
res := mkResult(
nil, nil,
[]Hop{mkHop(3, "10.0.0.3", 3*time.Millisecond)},
)
agg.Update(res, 1)
// Clear non-existent TTL — should not panic
agg.ClearHop(99)
// TTL 3 should still exist
snap := agg.Snapshot()
found := false
for _, s := range snap {
if s.TTL == 3 {
found = true
}
}
if !found {
t.Error("TTL 3 should still exist after clearing non-existent TTL")
}
}
func TestMTRAggregator_ClearHop_DoesNotAffectOtherTTLs(t *testing.T) {
agg := NewMTRAggregator()
// Record stats at TTLs 3 and 5
res := mkResult(
nil, nil,
[]Hop{mkHop(3, "10.0.0.3", 3*time.Millisecond)},
nil,
[]Hop{mkHop(5, "10.0.0.5", 5*time.Millisecond)},
)
agg.Update(res, 1)
// Clear TTL 5
agg.ClearHop(5)
// TTL 3 should still have its data
snap := agg.Snapshot()
for _, s := range snap {
if s.TTL == 3 {
if s.IP != "10.0.0.3" {
t.Errorf("TTL 3 IP = %q, want 10.0.0.3", s.IP)
}
if s.Snt != 1 {
t.Errorf("TTL 3 Snt = %d, want 1", s.Snt)
}
return
}
}
t.Error("TTL 3 not found in snapshot after clearing TTL 5")
}
// ---------------------------------------------------------------------------
// MigrateStats 测试
// ---------------------------------------------------------------------------
func TestMTRAggregator_MigrateStats_MovesToNewTTL(t *testing.T) {
agg := NewMTRAggregator()
// Record stats at TTL 12
res := mkResult(
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
[]Hop{mkHop(12, "8.8.8.8", 10*time.Millisecond)},
)
agg.Update(res, 1)
// Verify TTL 12 has data
snap := agg.Snapshot()
hasTTL12 := false
for _, s := range snap {
if s.TTL == 12 && s.IP == "8.8.8.8" {
hasTTL12 = true
}
}
if !hasTTL12 {
t.Fatal("expected stats at TTL 12 before migration")
}
// Migrate TTL 12 → TTL 7
agg.MigrateStats(12, 7, 0) // maxPerHop=0 → no cap
// TTL 12 should be gone, TTL 7 should have the data
snap = agg.Snapshot()
for _, s := range snap {
if s.TTL == 12 {
t.Errorf("TTL 12 should have been removed after migration, found IP=%s", s.IP)
}
if s.TTL == 7 && s.IP == "8.8.8.8" {
if s.Snt != 1 {
t.Errorf("TTL 7: expected Snt=1, got %d", s.Snt)
}
return // success
}
}
t.Error("TTL 7 should have migrated data from TTL 12")
}
func TestMTRAggregator_MigrateStats_MergesIntoExisting(t *testing.T) {
agg := NewMTRAggregator()
// Record 2 probes at TTL 7 (the new final)
for i := 0; i < 2; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", 5*time.Millisecond)}
agg.Update(res, 1)
}
// Record 3 probes at TTL 12 (the old final)
for i := 0; i < 3; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[11] = []Hop{mkHop(12, "8.8.8.8", 10*time.Millisecond)}
agg.Update(res, 1)
}
// Migrate 12 → 7 without cap
agg.MigrateStats(12, 7, 0)
snap := agg.Snapshot()
for _, s := range snap {
if s.TTL == 12 {
t.Error("TTL 12 should be gone after migration")
}
if s.TTL == 7 && s.IP == "8.8.8.8" {
// Merged: 2 (existing) + 3 (migrated) = 5
if s.Snt != 5 {
t.Errorf("TTL 7: expected Snt=5 (2+3), got %d", s.Snt)
}
return
}
}
t.Error("TTL 7 should have merged data")
}
func TestMTRAggregator_MigrateStats_NoopIfFromEmpty(t *testing.T) {
agg := NewMTRAggregator()
// Record at TTL 7
res := &Result{Hops: make([][]Hop, 8)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", 5*time.Millisecond)}
agg.Update(res, 1)
// Migrate from non-existent TTL 12 — should be no-op
agg.MigrateStats(12, 7, 0)
snap := agg.Snapshot()
for _, s := range snap {
if s.TTL == 7 && s.IP == "8.8.8.8" && s.Snt == 1 {
return // unchanged, correct
}
}
t.Error("TTL 7 data should be unchanged after noop migration")
}
func TestMTRAggregator_MigrateStats_CapsAtMaxPerHop(t *testing.T) {
agg := NewMTRAggregator()
// Record 2 probes at TTL 7
for i := 0; i < 2; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", 5*time.Millisecond)}
agg.Update(res, 1)
}
// Record 3 probes at TTL 12
for i := 0; i < 3; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[11] = []Hop{mkHop(12, "8.8.8.8", 10*time.Millisecond)}
agg.Update(res, 1)
}
// Migrate with maxPerHop=3: merged total would be 5, capped to 3.
agg.MigrateStats(12, 7, 3)
snap := agg.Snapshot()
for _, s := range snap {
if s.TTL == 12 {
t.Error("TTL 12 should be gone after migration")
}
if s.TTL == 7 && s.IP == "8.8.8.8" {
if s.Snt != 3 {
t.Errorf("TTL 7: expected Snt=3 (capped from 5), got %d", s.Snt)
}
return
}
}
t.Error("TTL 7 should have capped merged data")
}
func TestMTRAggregator_MigrateStats_CapsReceived(t *testing.T) {
agg := NewMTRAggregator()
// 2 sent, 2 received at TTL 7
for i := 0; i < 2; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", 5*time.Millisecond)}
agg.Update(res, 1)
}
// 3 sent, 3 received at TTL 12
for i := 0; i < 3; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[11] = []Hop{mkHop(12, "8.8.8.8", 10*time.Millisecond)}
agg.Update(res, 1)
}
// maxPerHop=2: sent capped to 2, received capped to min(5,2)=2
agg.MigrateStats(12, 7, 2)
snap := agg.Snapshot()
for _, s := range snap {
if s.TTL == 7 && s.IP == "8.8.8.8" {
if s.Snt != 2 {
t.Errorf("TTL 7: expected Snt=2 (capped), got %d", s.Snt)
}
// Loss should be 0% (received capped to sent=2)
if s.Loss > 0.01 {
t.Errorf("TTL 7: expected Loss ~0%%, got %.2f%%", s.Loss)
}
// Avg must stay consistent after proportional RTT scaling.
// Pre-merge: 2×5ms + 3×10ms = 40ms total over 5 samples → avg = 8ms.
// Proportional scaling preserves avg even after cap.
expectedAvg := 8.0 // (2*5 + 3*10) / 5 = 8ms
if s.Avg < expectedAvg-0.1 || s.Avg > expectedAvg+0.1 {
t.Errorf("TTL 7: expected Avg ~%.1fms (proportional), got %.4fms", expectedAvg, s.Avg)
}
return
}
}
t.Error("TTL 7 should have capped data")
}
func TestMTRAggregator_MigrateStats_CapsPreservesAvgStDev(t *testing.T) {
agg := NewMTRAggregator()
// 3 probes at TTL 7: all 4ms
for i := 0; i < 3; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", 4*time.Millisecond)}
agg.Update(res, 1)
}
// 3 probes at TTL 12: all 4ms (same RTT for zero-variance check)
for i := 0; i < 3; i++ {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[11] = []Hop{mkHop(12, "8.8.8.8", 4*time.Millisecond)}
agg.Update(res, 1)
}
// Pre-cap: 6 probes all 4ms → avg=4, stdev=0
// After cap to 3: avg must still be 4, stdev must still be 0.
agg.MigrateStats(12, 7, 3)
snap := agg.Snapshot()
for _, s := range snap {
if s.TTL == 7 && s.IP == "8.8.8.8" {
if s.Snt != 3 {
t.Errorf("expected Snt=3, got %d", s.Snt)
}
if s.Avg < 3.9 || s.Avg > 4.1 {
t.Errorf("expected Avg ~4.0ms, got %.4fms", s.Avg)
}
if s.StDev > 0.1 {
t.Errorf("expected StDev ~0, got %.4f", s.StDev)
}
return
}
}
t.Error("expected TTL 7 data")
}
func TestMTRAggregator_MigrateStats_CapsPreservesNonZeroStDev(t *testing.T) {
agg := NewMTRAggregator()
// Build a merged accumulator with mixed RTTs and verify Avg + StDev
// are preserved when received is capped.
//
// TTL 7: 2ms, 4ms (2 probes)
// TTL 12: 6ms, 8ms, 10ms (3 probes)
// Merged: [2, 4, 6, 8, 10] → 5 probes
// avg = 30/5 = 6.0
// sample var = ((2-6)² + (4-6)² + (6-6)² + (8-6)² + (10-6)²) / 4
// = (16+4+0+4+16) / 4 = 10.0
// stdev = sqrt(10) ≈ 3.1623
rtts7 := []time.Duration{2 * time.Millisecond, 4 * time.Millisecond}
for _, rtt := range rtts7 {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", rtt)}
agg.Update(res, 1)
}
rtts12 := []time.Duration{6 * time.Millisecond, 8 * time.Millisecond, 10 * time.Millisecond}
for _, rtt := range rtts12 {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[11] = []Hop{mkHop(12, "8.8.8.8", rtt)}
agg.Update(res, 1)
}
// Snapshot before cap to get the "ground truth" Avg & StDev.
agg.MigrateStats(12, 7, 0) // merge without cap first
snapBefore := agg.Snapshot()
var avgBefore, stdevBefore float64
for _, s := range snapBefore {
if s.TTL == 7 && s.IP == "8.8.8.8" {
avgBefore = s.Avg
stdevBefore = s.StDev
}
}
if avgBefore < 5.9 || avgBefore > 6.1 {
t.Fatalf("pre-cap Avg wrong: got %.4f, expected ~6.0", avgBefore)
}
// Now build the same scenario fresh, but cap to 3.
agg2 := NewMTRAggregator()
for _, rtt := range rtts7 {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[6] = []Hop{mkHop(7, "8.8.8.8", rtt)}
agg2.Update(res, 1)
}
for _, rtt := range rtts12 {
res := &Result{Hops: make([][]Hop, 12)}
res.Hops[11] = []Hop{mkHop(12, "8.8.8.8", rtt)}
agg2.Update(res, 1)
}
agg2.MigrateStats(12, 7, 3) // cap received from 5 → 3
snapAfter := agg2.Snapshot()
for _, s := range snapAfter {
if s.TTL == 7 && s.IP == "8.8.8.8" {
if s.Snt != 3 {
t.Errorf("expected Snt=3, got %d", s.Snt)
}
// Avg must be preserved.
if s.Avg < avgBefore-0.1 || s.Avg > avgBefore+0.1 {
t.Errorf("Avg drifted: expected ~%.4f, got %.4f", avgBefore, s.Avg)
}
// StDev must be preserved (non-zero variance scenario).
if stdevBefore > 0.1 {
if s.StDev < stdevBefore-0.15 || s.StDev > stdevBefore+0.15 {
t.Errorf("StDev drifted: expected ~%.4f, got %.4f", stdevBefore, s.StDev)
}
}
return
}
}
t.Error("expected TTL 7 data after capped migration")
}