Skip to content

feat: Fix Deployment DAUs to work with local timezones #7647

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
May 30, 2023
Merged
Prev Previous commit
Next Next commit
Add unit test for closest
  • Loading branch information
Emyrk committed May 23, 2023
commit 1949217a53adadb0377b920f08a1a9e33c820fcb
92 changes: 92 additions & 0 deletions coderd/metricscache/metrics_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package metricscache

import (
"github.com/stretchr/testify/require"
"testing"
)

func TestClosest(t *testing.T) {
t.Parallel()

testCases := []struct {
Name string
Keys []int
Input int
Expected int
NotFound bool
}{
{
Name: "Empty",
Input: 10,
NotFound: true,
},
{
Name: "Equal",
Keys: []int{1, 2, 3, 4, 5, 6, 10, 12, 15},
Input: 10,
Expected: 10,
},
{
Name: "ZeroOnly",
Keys: []int{0},
Input: 10,
Expected: 0,
},
{
Name: "NegativeOnly",
Keys: []int{-10, -5},
Input: 10,
Expected: -5,
},
{
Name: "CloseBothSides",
Keys: []int{-10, -5, 0, 5, 8, 12},
Input: 10,
Expected: 8,
},
{
Name: "CloseNoZero",
Keys: []int{-10, -5, 5, 8, 12},
Input: 0,
Expected: -5,
},
{
Name: "CloseLeft",
Keys: []int{-10, -5, 0, 5, 8, 12},
Input: 20,
Expected: 12,
},
{
Name: "CloseRight",
Keys: []int{-10, -5, 0, 5, 8, 12},
Input: -20,
Expected: -10,
},
{
Name: "ChooseZero",
Keys: []int{-10, -5, 0, 5, 8, 12},
Input: 2,
Expected: 0,
},
}

for _, tc := range testCases {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()

m := make(map[int]int)
for _, k := range tc.Keys {
m[k] = k
}

found, _, ok := closest(m, tc.Input)
if tc.NotFound {
require.False(t, ok, "should not be found")
} else {
require.True(t, ok)
require.Equal(t, tc.Expected, found, "closest")
}
})
}
}
6 changes: 5 additions & 1 deletion coderd/metricscache/metricscache.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,14 @@ func closest[V any](values map[int]V, offset int) (int, V, bool) {
var closestV V
diff := math.MaxInt
for k, v := range values {
if abs(k-offset) < diff {
newDiff := abs(k - offset)
// Take the closest value that is also the smallest value. We do this
// to make the output deterministic
if newDiff < diff || (newDiff == diff && k < closest) {
// new closest
closest = k
closestV = v
diff = newDiff
}
}
return closest, closestV, true
Expand Down