goext/timeext/diff_test.go

84 lines
2.5 KiB
Go
Raw Normal View History

2024-07-04 16:24:49 +02:00
package timeext
import (
"math"
"testing"
"time"
)
func TestYearDifferenceWithSameYearAndDay(t *testing.T) {
t1 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
expected := 0.0
result := YearDifference(t1, t2, time.UTC)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func TestYearDifferenceWithOneYearApart(t *testing.T) {
t1 := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
expected := 1.0
result := YearDifference(t1, t2, time.UTC)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func TestYearDifferenceWithDifferentMonths(t *testing.T) {
t1 := time.Date(2020, 6, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
expected := 0.4166666666666667 // Approximation of 5/12 months
result := YearDifference(t1, t2, time.UTC)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func TestYearDifferenceAcrossYears(t *testing.T) {
t1 := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2020, 6, 1, 0, 0, 0, 0, time.UTC)
expected := 0.5833333333333334 // Approximation of 7/12 months
result := YearDifference(t1, t2, time.UTC)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func TestYearDifferenceWithTimezone(t *testing.T) {
tz, _ := time.LoadLocation("America/New_York")
t1 := time.Date(2021, 1, 1, 0, 0, 0, 0, tz)
t2 := time.Date(2020, 6, 1, 0, 0, 0, 0, tz)
expected := 0.5833333333333334 // Same as UTC but ensuring timezone is considered
result := YearDifference(t1, t2, tz)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func TestYearDifferenceWithNegativeDifference(t *testing.T) {
t1 := time.Date(2020, 1, 1, 0, 0, 0, 0, TimezoneBerlin)
t2 := time.Date(2021, 1, 1, 0, 0, 0, 0, TimezoneBerlin)
expected := -1.0
result := YearDifference(t1, t2, TimezoneBerlin)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func TestYearDifferenceWithNegativeDifference2(t *testing.T) {
t1 := time.Date(2020, 7, 1, 0, 0, 0, 0, TimezoneBerlin)
t2 := time.Date(2021, 7, 1, 0, 0, 0, 0, TimezoneBerlin)
expected := -1.0
result := YearDifference(t1, t2, TimezoneBerlin)
if !epsilonEquals(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
func epsilonEquals(a, b float64) bool {
epsilon := 0.01
return math.Abs(a-b) < epsilon
}