package liturgy import ( "os" "path/filepath" "testing" "time" ) // TestCleanCache exercises CleanCache's file-selection rules: only // ".html"/".json" pairs older than the cutoff are removed; a // recent pair and a non-matching file are left untouched. The cutoff is a // fixed literal (not time.Now-derived) so the test is deterministic; only // the "recent" fixture is anchored to today, and only to make sure it lands // safely on the "keep" side of that fixed cutoff. func TestCleanCache(t *testing.T) { dir := t.TempDir() t.Setenv("XDG_CACHE_HOME", dir) cacheDir := filepath.Join(dir, "lectio") if err := os.MkdirAll(cacheDir, 0o755); err != nil { t.Fatal(err) } recent := time.Now().Format("2006-01-02") files := map[string]string{ "2020-01-01.html": "old", "2020-01-01.json": `[{"Heading":"old"}]`, recent + ".html": "recent", "notes.txt": "not a cache file", } for name, content := range files { if err := os.WriteFile(filepath.Join(cacheDir, name), []byte(content), 0o644); err != nil { t.Fatal(err) } } cutoff := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) removed, freed, err := CleanCache(cutoff) if err != nil { t.Fatalf("CleanCache: %v", err) } if removed != 2 { t.Errorf("removed = %d, want 2", removed) } if freed <= 0 { t.Errorf("freed = %d, want > 0", freed) } for _, gone := range []string{"2020-01-01.html", "2020-01-01.json"} { if _, err := os.Stat(filepath.Join(cacheDir, gone)); !os.IsNotExist(err) { t.Errorf("%s still exists after CleanCache, want removed", gone) } } for _, kept := range []string{recent + ".html", "notes.txt"} { if _, err := os.Stat(filepath.Join(cacheDir, kept)); err != nil { t.Errorf("%s missing after CleanCache, want kept: %v", kept, err) } } } // TestCleanCacheMissingDir checks the documented no-op: a cache dir that // does not exist yet is not an error. func TestCleanCacheMissingDir(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) removed, freed, err := CleanCache(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)) if err != nil { t.Fatalf("CleanCache on missing dir: %v", err) } if removed != 0 || freed != 0 { t.Errorf("CleanCache on missing dir = (%d, %d), want (0, 0)", removed, freed) } }