Repository navigation
Expand file tree
/
Copy pathtestdata_test.go
More file actions
262 lines (222 loc) · 7.89 KB
/
Copy pathtestdata_test.go
File metadata and controls
262 lines (222 loc) · 7.89 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package peerdb_test
import (
"context"
"encoding/json"
"io/fs"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gitlab.com/tozd/go/errors"
"gitlab.com/tozd/identifier"
"gitlab.com/peerdb/peerdb"
"gitlab.com/peerdb/peerdb/internal/xeno"
"gitlab.com/peerdb/peerdb/transform"
)
// testDataDir is the directory the populate command is pointed at to populate with the test data set.
const testDataDir = "testdata"
// attachmentLinkRe matches the links test data documents point at their attachments with. The
// identifier is derived from the file's path, so a link can be checked against the files which are
// really there.
var attachmentLinkRe = regexp.MustCompile(`/f/([0-9A-Za-z]{22})`)
func testDataContext(t *testing.T) context.Context {
t.Helper()
logger := zerolog.New(zerolog.NewConsoleWriter()).Level(zerolog.WarnLevel)
return logger.WithContext(t.Context())
}
// TestTestDataLoads verifies that every class has test data and that the data unmarshals into the
// class's struct. Unmarshaling rejects unknown fields, so this catches drift between the field
// definitions and the test data: a renamed field, or a field changing between a single value and a
// list of values.
func TestTestDataLoads(t *testing.T) {
t.Parallel()
for _, class := range peerdb.TestingTestDataClasses {
t.Run(class.Directory, func(t *testing.T) {
t.Parallel()
documents, errE := class.Load(t.Context(), filepath.Join(testDataDir, class.Directory))
require.NoError(t, errE, "% -+#.1v", errE)
assert.NotEmpty(t, documents, "no test data documents loaded")
})
}
}
// TestTestDataTransforms verifies that the test data transforms into documents together with the core
// and test data schema documents. Transforming enforces the cardinality and the value type of every
// field, so this is the same check the populate command does.
func TestTestDataTransforms(t *testing.T) {
t.Parallel()
ctx := testDataContext(t)
documents, errE := peerdb.TestingLoadTestData(ctx, *zerolog.Ctx(ctx), testDataDir)
require.NoError(t, errE, "% -+#.1v", errE)
all, transformed, errE := peerdb.TestingGenerateTestDataDocs(ctx, *zerolog.Ctx(ctx), documents)
require.NoError(t, errE, "% -+#.1v", errE)
assert.Len(t, transformed, len(all))
assert.Greater(t, len(transformed), len(documents))
}
// TestTestDataReferences verifies that the test data has no duplicate document ID and that every
// reference in it points at a document which exists, either in the test data itself or among the core
// and test data schema documents. A dangling reference does not fail populating, but it leaves the
// data with a link nothing resolves.
func TestTestDataReferences(t *testing.T) {
t.Parallel()
ctx := testDataContext(t)
testData, errE := peerdb.TestingLoadTestData(ctx, *zerolog.Ctx(ctx), testDataDir)
require.NoError(t, errE, "% -+#.1v", errE)
generated, _, errE := peerdb.TestingGenerateTestDataDocs(ctx, *zerolog.Ctx(ctx), nil)
require.NoError(t, errE, "% -+#.1v", errE)
known := map[string]bool{}
for _, doc := range append(slices.Clone(generated), testData...) {
id, errE := transform.ExtractDocumentID(doc)
require.NoError(t, errE, "% -+#.1v", errE)
key := strings.Join(id, "/")
assert.False(t, known[key], "duplicate document ID %q", key)
known[key] = true
}
for path, contents := range testDataJSONFiles(t) {
var doc map[string]any
require.NoError(t, json.Unmarshal(contents, &doc), "%s", path)
for _, reference := range references(doc) {
assert.True(t, known[reference], "%s: reference to unknown document %q", path, reference)
}
}
}
// TestTestDataAttachments verifies that every attachment link in the test data points at a file which
// is there, that every file is linked from somewhere, and that every attachment is named after the
// file it points at. Without the name the interface has nothing to show for the attachment but the
// link itself.
func TestTestDataAttachments(t *testing.T) {
t.Parallel()
root := filepath.Join(testDataDir, peerdb.TestingTestDataFilesDirectory)
linked := map[string]string{}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return errors.WithStack(err)
}
if d.IsDir() {
return nil
}
name, err := filepath.Rel(root, p)
if err != nil {
return errors.WithStack(err)
}
linked[identifier.From(xeno.Namespace, xeno.FilesStorage, name).String()] = name
return nil
})
require.NoError(t, err)
assert.NotEmpty(t, linked, "no attachments")
used := map[string]bool{}
for path, contents := range testDataJSONFiles(t) {
for _, match := range attachmentLinkRe.FindAllStringSubmatch(string(contents), -1) {
assert.Contains(t, linked, match[1], "%s: link to unknown attachment %q", path, match[0])
used[match[1]] = true
}
var doc map[string]any
require.NoError(t, json.Unmarshal(contents, &doc), "%s", path)
for _, attachment := range attachments(doc) {
id := strings.TrimPrefix(attachment.Link, "/f/")
assert.Equal(t, filepath.Base(linked[id]), attachment.Name, "%s: attachment %q is named for another file", path, attachment.Link)
}
}
for id, name := range linked {
assert.True(t, used[id], "attachment %q is not linked from any document", name)
}
}
// testDataJSONFiles returns the contents of every test data document, keyed by its path.
func testDataJSONFiles(t *testing.T) map[string][]byte {
t.Helper()
files := map[string][]byte{}
for _, class := range peerdb.TestingTestDataClasses {
directory := filepath.Join(testDataDir, class.Directory)
entries, err := os.ReadDir(directory)
require.NoError(t, err)
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
continue
}
path := filepath.Join(directory, entry.Name())
contents, err := os.ReadFile(path) //nolint:gosec
require.NoError(t, err)
files[path] = contents
}
}
return files
}
// attachment is one attachment found in a test data document: the link it points at the file with,
// and the name it gives that file.
type attachment struct {
Link string
Name string
}
// attachments collects every attachment in the document. An attachment is a value which is a link
// into the file storage, whatever field it sits in.
func attachments(doc map[string]any) []attachment {
found := []attachment{}
var walk func(value any)
walk = func(value any) {
switch v := value.(type) {
case map[string]any:
if link, ok := v["value"].(string); ok && strings.HasPrefix(link, "/f/") {
name, _ := v["name"].(string)
found = append(found, attachment{Link: link, Name: name})
}
for _, sub := range v {
walk(sub)
}
case []any:
for _, sub := range v {
walk(sub)
}
}
}
walk(doc)
return found
}
// references collects every reference in the document, as a slash-joined document ID. The document's
// own ID is not a reference, so the top-level "id" is skipped.
func references(doc map[string]any) []string {
found := []string{}
var walk func(value any, isDocumentID bool)
walk = func(value any, isDocumentID bool) {
switch v := value.(type) {
case map[string]any:
for key, sub := range v {
// A reference is an object whose only content is the "id" of the target document.
if key == "id" && !isDocumentID {
if id, ok := stringSlice(sub); ok {
found = append(found, strings.Join(id, "/"))
continue
}
}
walk(sub, false)
}
case []any:
for _, sub := range v {
walk(sub, isDocumentID)
}
}
}
for key, value := range doc {
walk(value, key == "id")
}
return found
}
// stringSlice converts a JSON array of strings into a string slice.
func stringSlice(value any) ([]string, bool) {
values, ok := value.([]any)
if !ok {
return nil, false
}
result := make([]string, 0, len(values))
for _, v := range values {
s, ok := v.(string)
if !ok {
return nil, false
}
result = append(result, s)
}
return result, true
}