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
|
package cbreaker
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
"github.com/vulcand/oxy/v2/internal/holsterv4/clock"
"github.com/vulcand/oxy/v2/testutils"
"github.com/vulcand/oxy/v2/utils"
)
func TestRampUp(t *testing.T) {
done := testutils.FreezeTime()
defer done()
duration := 10 * clock.Second
rc := newRatioController(duration, &utils.NoopLogger{})
allowed, denied := 0, 0
for i := 0; i < int(duration/clock.Millisecond); i++ {
ratio := sendRequest(&allowed, &denied, rc)
expected := rc.targetRatio()
diff := math.Abs(expected - ratio)
t.Log("Ratio", ratio)
t.Log("Expected", expected)
t.Log("Diff", diff)
assert.EqualValues(t, 0, round(diff, 0.5, 1))
clock.Advance(clock.Millisecond)
}
}
func sendRequest(allowed, denied *int, rc *ratioController) float64 {
if rc.allowRequest() {
*allowed++
} else {
*denied++
}
if *allowed+*denied == 0 {
return 0
}
return float64(*allowed) / float64(*allowed+*denied)
}
func round(val float64, roundOn float64, places int) float64 {
pow := math.Pow(10, float64(places))
digit := pow * val
_, div := math.Modf(digit)
var round float64
if div >= roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
return round / pow
}
|