internal/feed/normalize/dates_test.go

package normalize

import (
	"testing"
	"time"
)

func TestParseFlexible(t *testing.T) {
	t.Parallel()
	cases := []struct {
		name    string
		in      string
		wantErr bool
	}{
		{"rfc3339", "2025-01-02T03:04:05Z", false},
		{"rfc1123z", "Thu, 02 Jan 2025 03:04:05 +0000", false},
		{"date_only", "2025-01-02", false},
		{"slashes", "2025/01/02", false},
		{"empty", "", true},
		{"garbage", "not a date", true},
	}
	for _, tc := range cases {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			_, err := ParseFlexible(tc.in)
			if (err != nil) != tc.wantErr {
				t.Errorf("err = %v, wantErr = %v", err, tc.wantErr)
			}
		})
	}
}

func TestFormatRoundTrip(t *testing.T) {
	t.Parallel()
	now := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC)
	if got := FormatRFC3339(now); got != "2025-01-02T03:04:05Z" {
		t.Errorf("rfc3339 = %q", got)
	}
	if got := FormatRFC1123Z(now); got != "Thu, 02 Jan 2025 03:04:05 +0000" {
		t.Errorf("rfc1123z = %q", got)
	}
	if got := FormatHumanDate(now); got != "Jan 2, 2025" {
		t.Errorf("human = %q", got)
	}
}

func TestFormatZeroTime(t *testing.T) {
	t.Parallel()
	var zero time.Time
	if FormatRFC3339(zero) != "" || FormatRFC1123Z(zero) != "" || FormatHumanDate(zero) != "" {
		t.Error("zero time should format to empty string")
	}
}

func TestSortDescending(t *testing.T) {
	t.Parallel()
	t.Helper()
	ts := []time.Time{
		time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
		time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
		time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
	}
	SortDescending(ts)
	if ts[0].Year() != 2025 || ts[2].Year() != 2023 {
		t.Errorf("sort order wrong: %v", ts)
	}
}

func TestTruncateToDay(t *testing.T) {
	t.Parallel()
	in := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC)
	got := TruncateToDay(in)
	if !got.Equal(time.Date(2025, 1, 2, 0, 0, 0, 0, time.UTC)) {
		t.Errorf("got %v", got)
	}
}