internet_latency_delay_generator_test.go 2.2 KB
Newer Older
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
package bitswap

import (
	"math"
	"math/rand"
	"testing"
	"time"
)

const testSeed = 99

func TestInternetLatencyDelayNextWaitTimeDistribution(t *testing.T) {
	initialValue := 1000 * time.Millisecond
	deviation := 100 * time.Millisecond
	mediumDelay := 1000 * time.Millisecond
	largeDelay := 3000 * time.Millisecond
	percentMedium := 0.2
	percentLarge := 0.4
	buckets := make(map[string]int)
	internetLatencyDistributionDelay := InternetLatencyDelayGenerator(
		mediumDelay,
		largeDelay,
		percentMedium,
		percentLarge,
		deviation,
		rand.New(rand.NewSource(testSeed)))

	buckets["fast"] = 0
	buckets["medium"] = 0
	buckets["slow"] = 0
	buckets["outside_1_deviation"] = 0

	// strategy here is rather than mock randomness, just use enough samples to
	// get approximately the distribution you'd expect
	for i := 0; i < 10000; i++ {
		next := internetLatencyDistributionDelay.NextWaitTime(initialValue)
		if math.Abs((next - initialValue).Seconds()) <= deviation.Seconds() {
			buckets["fast"]++
		} else if math.Abs((next - initialValue - mediumDelay).Seconds()) <= deviation.Seconds() {
			buckets["medium"]++
		} else if math.Abs((next - initialValue - largeDelay).Seconds()) <= deviation.Seconds() {
			buckets["slow"]++
		} else {
			buckets["outside_1_deviation"]++
		}
	}
	totalInOneDeviation := float64(10000 - buckets["outside_1_deviation"])
	oneDeviationPercentage := totalInOneDeviation / 10000
	fastPercentageResult := float64(buckets["fast"]) / totalInOneDeviation
	mediumPercentageResult := float64(buckets["medium"]) / totalInOneDeviation
	slowPercentageResult := float64(buckets["slow"]) / totalInOneDeviation

	// see 68-95-99 rule for normal distributions
	if math.Abs(oneDeviationPercentage-0.6827) >= 0.1 {
		t.Fatal("Failed to distribute values normally based on standard deviation")
	}

	if math.Abs(fastPercentageResult+percentMedium+percentLarge-1) >= 0.1 {
		t.Fatal("Incorrect percentage of values distributed around fast delay time")
	}

	if math.Abs(mediumPercentageResult-percentMedium) >= 0.1 {
		t.Fatal("Incorrect percentage of values distributed around medium delay time")
	}

	if math.Abs(slowPercentageResult-percentLarge) >= 0.1 {
		t.Fatal("Incorrect percentage of values distributed around slow delay time")
	}
}