-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload_test.go
102 lines (85 loc) · 2.8 KB
/
load_test.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"testing"
"os"
"path/filepath"
"time"
"encoding/json"
"strings"
)
func TestLoadMetadata(t *testing.T) {
dir, err := os.MkdirTemp("", "")
if (err != nil) {
t.Fatalf("failed to create a temporary directory; %v", err)
}
t.Run("success", func(t *testing.T) {
path := filepath.Join(dir, "A")
err = os.WriteFile(path, []byte("{ \"a\": 1 }"), 0644)
if err != nil {
t.Fatalf("failed to create a mock file; %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
loaded := loadMetadata(path, info)
if loaded.Failure != nil {
t.Fatal(loaded.Failure)
}
if loaded.Path != path || len(loaded.User) == 0 || len(loaded.Raw) == 0 || time.Now().Sub(loaded.Time) < 0 {
t.Fatalf("unexpected values from loaded metadata %v", *loaded)
}
conv, ok := loaded.Parsed.(map[string]interface{})
if !ok {
t.Fatal("unexpected parsed object")
}
found, ok := conv["a"]
if !ok {
t.Fatal("unexpected parsed object")
}
target, ok := found.(json.Number)
if !ok || target != "1" {
t.Fatal("unexpected parsed object")
}
})
t.Run("reading failure", func(t *testing.T) {
path := filepath.Join(dir, "missing")
loaded := loadMetadata(path, nil)
if loaded.Failure == nil || !strings.Contains(loaded.Failure.Error(), "failed to read") {
t.Fatal("expected a reading error")
}
})
t.Run("parsing failure", func(t *testing.T) {
path := filepath.Join(dir, "B")
err = os.WriteFile(path, []byte("{ whee }"), 0644)
if err != nil {
t.Fatalf("failed to create a mock file; %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
loaded := loadMetadata(path, info)
if loaded.Failure == nil || !strings.Contains(loaded.Failure.Error(), "failed to parse") {
t.Fatal("expected a parsing error")
}
})
t.Run("symlink okay", func(t *testing.T) {
path := filepath.Join(dir, "C")
err = os.Symlink(filepath.Join(dir, "A"), path)
if err != nil {
t.Fatalf("failed to create a symlink; %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
loaded := loadMetadata(path, info)
if loaded.Failure != nil {
t.Fatal(loaded.Failure)
}
if loaded.Path != path || len(loaded.User) == 0 || len(loaded.Raw) == 0 || time.Now().Sub(loaded.Time) < 0 {
t.Fatalf("unexpected values from symlink-loaded metadata %v", *loaded)
}
})
}