summaryrefslogtreecommitdiff
path: root/internal/liturgy/clean_test.go
blob: d9ab4fc9b281887dd26b83209e86e3060d8998cc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package liturgy

import (
	"os"
	"path/filepath"
	"testing"
	"time"
)

// TestCleanCache exercises CleanCache's file-selection rules: date-prefixed
// cache files (modern ".html"/".json" and traditional ".trad.<lang>.json")
// older than the cutoff are removed; recent files 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" fixtures are anchored to
// today, and only to make sure they land 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":         "<html>old</html>",
		"2020-01-01.json":         `[{"Heading":"old"}]`,
		"2020-01-01.trad.pl.json": `[{"info":{},"sections":[]}]`,
		recent + ".html":          "<html>recent</html>",
		recent + ".trad.pl.json":  `[{"info":{},"sections":[]}]`,
		"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 != 3 {
		t.Errorf("removed = %d, want 3", removed)
	}
	if freed <= 0 {
		t.Errorf("freed = %d, want > 0", freed)
	}

	for _, gone := range []string{"2020-01-01.html", "2020-01-01.json", "2020-01-01.trad.pl.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", recent + ".trad.pl.json", "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)
	}
}