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
76
77
78
79
80
81
82
83
84
85
86
87
88
|
package item
import (
"bytes"
"log"
"os"
"path/filepath"
"strings"
"testing"
)
// Regression: an item file whose declared id: disagrees with its filename was
// silently loaded under the filename with no diagnostic. ItemStore must warn,
// because the author has no other sign that the id they wrote is ignored.
func captureLog(t *testing.T, fn func()) string {
t.Helper()
var buf bytes.Buffer
old := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(old)
fn()
return buf.String()
}
func writeItemFile(t *testing.T, dir, name, body string) {
t.Helper()
path := filepath.Join(dir, "items", name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
func TestItemStoreWarnsOnDeclaredIDMismatch(t *testing.T) {
dir := t.TempDir()
writeItemFile(t, dir, "foo.yaml", "id: bar\nname: Foo\n")
s := NewItemStore(dir)
out := captureLog(t, func() {
def, err := s.Load("foo")
if err != nil {
t.Fatalf("load: %v", err)
}
if def.ID != "foo" {
t.Fatalf("filename must win: ID = %q, want foo", def.ID)
}
})
if !strings.Contains(out, "declares id") {
t.Fatalf("expected an id-mismatch warning, got log %q", out)
}
}
func TestItemStoreDoesNotWarnWhenIDMatchesOrAbsent(t *testing.T) {
dir := t.TempDir()
writeItemFile(t, dir, "foo.yaml", "id: foo\nname: Foo\n")
writeItemFile(t, dir, "baz.yaml", "name: Baz\n")
s := NewItemStore(dir)
out := captureLog(t, func() {
if _, err := s.Load("foo"); err != nil {
t.Fatal(err)
}
if _, err := s.Load("baz"); err != nil {
t.Fatal(err)
}
})
if strings.Contains(out, "declares id") {
t.Fatalf("unexpected id-mismatch warning: %q", out)
}
}
func TestItemStoreLoadAllWarnsOnDeclaredIDMismatch(t *testing.T) {
dir := t.TempDir()
writeItemFile(t, dir, "foo.yaml", "id: bar\nname: Foo\n")
s := NewItemStore(dir)
out := captureLog(t, func() {
if _, err := s.LoadAll(); err != nil {
t.Fatal(err)
}
})
if !strings.Contains(out, "declares id") {
t.Fatalf("expected an id-mismatch warning from LoadAll, got %q", out)
}
}
|