github.com/zak-blake/goa@v1.4.1/middleware/sampler_test.go (about) 1 package middleware 2 3 import ( 4 "math/rand" 5 "testing" 6 "time" 7 ) 8 9 func TestFixedSampler(t *testing.T) { 10 // 0 % 11 subject := NewFixedSampler(0) 12 for i := 0; i < 10; i++ { 13 if subject.Sample() { 14 t.Errorf("%d: Sample() returned true for 0%%", i) 15 } 16 } 17 18 // 100 % 19 subject = NewFixedSampler(100) 20 for i := 0; i < 10; i++ { 21 if !subject.Sample() { 22 t.Errorf("%d: Sample() returned false for 100%%", i) 23 } 24 } 25 26 // 50 % 27 rand.Seed(123) // set seed for reproducibility. 28 trueCount := 0 29 subject = NewFixedSampler(33) 30 for i := 0; i < 100; i++ { 31 if subject.Sample() { 32 trueCount++ 33 } 34 } 35 if trueCount != 30 { 36 t.Errorf("Unexpected trueCount: %d", trueCount) 37 } 38 39 // 66 % 40 trueCount = 0 41 subject = NewFixedSampler(66) 42 for i := 0; i < 100; i++ { 43 if subject.Sample() { 44 trueCount++ 45 } 46 } 47 if trueCount != 67 { 48 t.Errorf("Unexpected trueCount: %d", trueCount) 49 } 50 } 51 52 func TestAdaptiveSampler(t *testing.T) { 53 // initial sampling 54 subject := NewAdaptiveSampler(1, 100) 55 for i := 0; i < 99; i++ { 56 if !subject.Sample() { 57 t.Errorf("%d: Sample() returned false before reaching sample size", i) 58 } 59 } 60 61 // change start time to 1s ago for a more predictable result. 62 trueCount := 0 63 rand.Seed(123) // set seed for reproducibility. 64 now := time.Now() 65 subject.(*adaptiveSampler).start = now.Add(-time.Second) 66 for i := 99; i < 199; i++ { 67 if subject.Sample() { 68 trueCount++ 69 } 70 } 71 72 // sample rate should be 1/s 73 if trueCount != 1 { 74 t.Errorf("Unexpected trueCount: %d", trueCount) 75 } 76 77 // start time should be set to now after rate adjustment. 78 if subject.(*adaptiveSampler).start.Before(now) { 79 t.Errorf("start time was not updated: %v >= %v", subject.(*adaptiveSampler).start, now) 80 } 81 82 // simulate last 100 requests taking 10s. 83 trueCount = 0 84 subject.(*adaptiveSampler).start = time.Now().Add(-time.Second * 10) 85 for i := 199; i < 299; i++ { 86 if subject.Sample() { 87 trueCount++ 88 } 89 } 90 91 // sample rate should be 10/s 92 if trueCount != 10 { 93 t.Errorf("Unexpected trueCount: %d", trueCount) 94 } 95 96 // simulate last 100 requests taking 100s. 97 trueCount = 0 98 subject.(*adaptiveSampler).start = time.Now().Add(-time.Second * 100) 99 for i := 299; i < 399; i++ { 100 if subject.Sample() { 101 trueCount++ 102 } 103 } 104 105 // sampler should max out and sample all requests. 106 if trueCount != 100 { 107 t.Errorf("Unexpected trueCount: %d", trueCount) 108 } 109 }