color/internal/helper/cmp_test.go
2025-03-06 13:01:21 -05:00

86 lines
2.5 KiB
Go

package helper
import (
"math"
"testing"
)
func TestEqFloat64Fuzzy(t *testing.T) {
tests := []struct {
name string
a, b float64
want bool
}{
{"exactly equal", 1, 1, true},
{"nearly equal", 1, math.Nextafter(1, math.Inf(1)), true},
{"zero equal to itself", +0., -0., true},
{"zero not equal to non-zero", 0., 1e-9, false},
{"definitely not equal", 1, 1 + 1e-9, false},
{"infinity equal to itself", math.Inf(1), math.Inf(1), true},
{"infinity not equal to a finite value", math.Inf(1), 1, false},
{"NaN equal to itself", math.NaN(), math.NaN(), true},
{"NaN not equal to a finite value", math.NaN(), 1, false},
{"NaN not equal to infinity", math.NaN(), math.Inf(1), false},
// these are actual numbers encountered that should be equal, but failed the test at some point.
// keeping them around as test cases.
{"testcase1", 0.0015172579307272023, 0.001517257930727202, true},
{"testcase2", 0, -8.131516293641283e-20, true},
{"testcase3", 0, -5.0186702124817295e-20, true},
{"testcase4", 0, -6.776263578034403e-21, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := EqFloat64Fuzzy(tt.a, tt.b); got != tt.want {
t.Errorf("EqFloat64Fuzzy(%v, %v) = %v, want %v", tt.a, tt.b, got, tt.want)
}
// swapping the arguments shouldn't change the outcome.
if got := EqFloat64Fuzzy(tt.b, tt.a); got != tt.want {
t.Errorf("EqFloat64Fuzzy(%v, %v) = %v, want %v", tt.b, tt.a, got, tt.want)
}
// negating the arguments shouldn't change the outcome either
if got := EqFloat64Fuzzy(-tt.a, -tt.b); got != tt.want {
t.Errorf("EqFloat64Fuzzy(%v, %v) = %v, want %v", -tt.a, -tt.b, got, tt.want)
}
if got := EqFloat64Fuzzy(tt.b, tt.a); got != tt.want {
t.Errorf("EqFloat64Fuzzy(%v, %v) = %v, want %v", -tt.b, -tt.a, got, tt.want)
}
})
}
}
func TestEqFloat64SliceFuzzy(t *testing.T) {
tests := []struct {
name string
a, b []float64
want bool
}{
{
"equivalent float slices",
[]float64{1, 2, 3, math.NaN()},
[]float64{1, 2, math.Nextafter(3, math.Inf(1)), math.NaN()},
true,
}, {
"dissimilar float slices",
[]float64{1, 2, 4},
[]float64{1, 3, 4},
false,
}, {
"different lengths",
[]float64{1, 2},
[]float64{1, 2, 3},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := EqFloat64SliceFuzzy(tt.a, tt.b); got != tt.want {
t.Errorf("EqFloat64SliceFuzzy(%v, %v) = %v, want %v", tt.a, tt.b, got, tt.want)
}
})
}
}