github.com/blend/go-sdk@v1.20240719.1/datadog/rate_sampler_test.go (about) 1 /* 2 3 Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package datadog 9 10 import ( 11 "fmt" 12 "testing" 13 14 "github.com/blend/go-sdk/assert" 15 ) 16 17 func Test_RateSampler(t *testing.T) { 18 assert := assert.New(t) 19 20 // 25% sample (25% pass at infinity) 21 sampler := RateSampler(0.25) 22 23 var passed int 24 for x := 0; x < 102400; x++ { 25 if sampler.Sample(nil) { 26 passed++ 27 } 28 } 29 30 // Since we are sampling incrementally, we cannot guarantee that we would 31 // sample exactly 25% of the population, so we add a buffer here to account 32 // for the errors. The ratio of errors gets smaller the larger the population. 33 expected := int(102400 * 0.25) 34 buffer := 1024 35 assert.True(passed > expected-buffer, fmt.Sprint(passed)) 36 assert.True(passed < expected+buffer, fmt.Sprint(passed)) 37 } 38 39 func Test_RateSampler_FullOn(t *testing.T) { 40 assert := assert.New(t) 41 42 // 100% sample (all pass) 43 sampler := RateSampler(1) 44 45 var passed int 46 for x := 0; x < 1024; x++ { 47 if sampler.Sample(nil) { 48 passed++ 49 } 50 } 51 assert.Equal(passed, 1024) 52 } 53 54 func Test_RateSampler_FullOff(t *testing.T) { 55 assert := assert.New(t) 56 57 // 0% sample (none passes) 58 sampler := RateSampler(0) 59 60 var passed int 61 for x := 0; x < 1024; x++ { 62 if sampler.Sample(nil) { 63 passed++ 64 } 65 } 66 assert.Zero(passed) 67 } 68 69 func Test_RateSampler_FullOff_Negative(t *testing.T) { 70 assert := assert.New(t) 71 72 // Negative sampling rate (none passes) 73 sampler := RateSampler(-1) 74 75 var passed int 76 for x := 0; x < 1024; x++ { 77 if sampler.Sample(nil) { 78 passed++ 79 } 80 } 81 assert.Zero(passed) 82 }