/
testing.go
317 lines (268 loc) · 8.99 KB
/
testing.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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package core
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"github.com/julien-sobczak/the-notewriter/internal/testutil"
"github.com/julien-sobczak/the-notewriter/pkg/clock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Reset forces singletons to be recreated. Useful between unit tests.
func Reset() {
collectionOnce.Reset()
configOnce.Reset()
dbRemoteOnce.Reset()
dbClientOnce.Reset()
dbOnce.Reset()
loggerOnce.Reset()
sectionsInventoryOnce.Reset()
slugInventoryOnce.Reset()
}
/* Fixtures */
// SetUpCollectionFromGoldenFile populates a temp directory containing a valid .nt collection and a single file.
func SetUpCollectionFromGoldenFile(t *testing.T) string {
return SetUpCollectionFromGoldenFileNamed(t, t.Name()+".md")
}
// SetUpCollectionFromGoldenFileNamed populates a temp directory based on the given golden file name.
func SetUpCollectionFromGoldenFileNamed(t *testing.T, testname string) string {
filename := testutil.SetUpFromGoldenFileNamed(t, testname)
dirname := filepath.Dir(filename)
configureDir(t, dirname)
return filename
}
// SetUpCollectionFromFileContent populates a temp directory based on the given file content.
func SetUpCollectionFromFileContent(t *testing.T, name, content string) string {
filename := testutil.SetUpFromFileContent(t, name, content)
dirname := filepath.Dir(filename)
configureDir(t, dirname)
return filename
}
// SetUpCollectionFromGoldenDir populates a temp directory containing a valid .nt collection.
func SetUpCollectionFromGoldenDir(t *testing.T) string {
return SetUpCollectionFromGoldenDirNamed(t, t.Name())
}
// SetUpCollectionFromGoldenDir populates a temp directory based on the given golden dir name.
func SetUpCollectionFromGoldenDirNamed(t *testing.T, testname string) string {
dirname := testutil.SetUpFromGoldenDirNamed(t, testname)
configureDir(t, dirname)
return dirname
}
// SetUpCollectionFromTempDir populates a temp directory containing a valid .nt collection.
func SetUpCollectionFromTempDir(t *testing.T) string {
dirname := t.TempDir()
configureDir(t, dirname)
t.Logf("Working in configured directory %s", dirname)
return dirname
}
func configureDir(t *testing.T, dirname string) {
ntDir := filepath.Join(dirname, ".nt")
if _, err := os.Stat(ntDir); os.IsNotExist(err) {
// Create a default configuration if not exists for CurrentConfig() to work
if err := os.Mkdir(ntDir, os.ModePerm); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(ntDir, "config"), []byte(`
[core]
extensions=["md", "markdown"]
[medias]
command="random"
`), os.ModePerm); err != nil {
t.Fatal(err)
}
}
// Force the application to consider the temporary directory as the home
os.Setenv("NT_HOME", dirname)
t.Cleanup(func() {
os.Unsetenv("NT_HOME")
Reset()
})
// Force debug level in tests to diagnose more easily
CurrentLogger().SetVerboseLevel(VerboseDebug)
CurrentLogger().Debugf("✨ Set up directory %q", ntDir)
}
/* Reproducible Tests */
// FreezeNow wraps the clock API to register the cleanup function at the end of the test.
func FreezeNow(t *testing.T) time.Time {
now := clock.Freeze()
t.Cleanup(clock.Unfreeze)
return now
}
// FreezeAt wraps the clock API to register the cleanup function at the end of the test.
func FreezeAt(t *testing.T, point time.Time) time.Time {
now := clock.FreezeAt(point)
t.Cleanup(clock.Unfreeze)
return now
}
// SetNextOIDs configures a predefined list of OID
func SetNextOIDs(t *testing.T, oids ...string) {
oidGenerator = &suiteOIDGenerator{
nextOIDs: oids,
}
t.Cleanup(ResetOID)
}
// UseFixedOID configures a fixed OID value
func UseFixedOID(t *testing.T, value string) {
oidGenerator = &fixedOIDGenerator{
oid: value,
}
t.Cleanup(ResetOID)
}
// UseFixedOID configures a fixed OID value
func UseSequenceOID(t *testing.T) {
oidGenerator = &sequenceOIDGenerator{}
t.Cleanup(ResetOID)
}
/* Test Helpers */
func MustCountFiles(t *testing.T) int {
count, err := CurrentCollection().CountFiles()
require.NoError(t, err)
return count
}
func MustCountMedias(t *testing.T) int {
count, err := CurrentCollection().CountMedias()
require.NoError(t, err)
return count
}
func MustCountNotes(t *testing.T) int {
count, err := CurrentCollection().CountNotes()
require.NoError(t, err)
return count
}
func MustCountLinks(t *testing.T) int {
count, err := CurrentCollection().CountLinks()
require.NoError(t, err)
return count
}
func MustCountFlashcards(t *testing.T) int {
count, err := CurrentCollection().CountFlashcards()
require.NoError(t, err)
return count
}
func MustCountReminders(t *testing.T) int {
count, err := CurrentCollection().CountReminders()
require.NoError(t, err)
return count
}
func AssertNoFiles(t *testing.T) {
count, err := CurrentCollection().CountFiles()
require.NoError(t, err)
require.Equal(t, 0, count)
}
func AssertNoNotes(t *testing.T) {
count, err := CurrentCollection().CountNotes()
require.NoError(t, err)
require.Equal(t, 0, count)
}
func AssertNoFlashcards(t *testing.T) {
count, err := CurrentCollection().CountFlashcards()
require.NoError(t, err)
require.Equal(t, 0, count)
}
func AssertNoLinks(t *testing.T) {
count, err := CurrentCollection().CountLinks()
require.NoError(t, err)
require.Equal(t, 0, count)
}
func AssertNoReminders(t *testing.T) {
count, err := CurrentCollection().CountReminders()
require.NoError(t, err)
require.Equal(t, 0, count)
}
func AssertNoMedias(t *testing.T) {
count, err := CurrentCollection().CountMedias()
require.NoError(t, err)
require.Equal(t, 0, count)
}
func AssertFrontMatterEqual(t *testing.T, expected string, file *File) {
actual, err := file.FrontMatterString()
require.NoError(t, err)
AssertTrimEqual(t, expected, actual)
}
func AssertContentEqual(t *testing.T, expected string, file *File) {
actual := file.Body
AssertTrimEqual(t, expected, actual)
}
func AssertTrimEqual(t *testing.T, expected string, actual string) {
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(actual))
}
func MustFindFlashcardByShortTitle(t *testing.T, shortTitle string) *Flashcard {
flashcard, err := CurrentCollection().FindFlashcardByShortTitle(shortTitle)
require.NoError(t, err)
require.NotNil(t, flashcard)
return flashcard
}
func MustFindNoteByPathAndTitle(t *testing.T, relativePath, longTitle string) *Note {
note, err := CurrentCollection().FindNoteByPathAndTitle(relativePath, longTitle)
require.NoError(t, err)
require.NotNil(t, note)
return note
}
/* Collection Helpers */
// MustWriteFile edits the file in the current collection to force the given content.
func MustWriteFile(t *testing.T, path string, content string) {
root := CurrentConfig().RootDirectory
newFilepath := filepath.Join(root, path)
err := os.WriteFile(newFilepath, []byte(UnescapeTestContent(content)), 0644)
require.NoError(t, err)
}
// UnescapeTestContent supports content using a special character instead of backticks.
func UnescapeTestContent(content string) string {
// We support a special syntax for backticks in content.
// Backticks are used to define note attributes (= common syntax with The NoteWriter) but
// multiline strings in Golang cannot contains backticks.
// We allows the ” character instead as suggested here: https://stackoverflow.com/a/59900008
//
// Example: ”@slug: toto” will become `@slug: toto`
return strings.ReplaceAll(content, "”", "`")
}
// MustDeleteFile remove a file iin the current collection.
func MustDeleteFile(t *testing.T, path string) {
root := CurrentConfig().RootDirectory
existingFilepath := filepath.Join(root, path)
err := os.Remove(existingFilepath)
require.NoError(t, err)
}
/* Text Helpers */
// ReplaceLine replaces a line inside a file.
func ReplaceLine(t *testing.T, path string, lineNumber int, oldLine string, newLine string) {
data, err := os.ReadFile(path)
require.NoError(t, err)
lines := strings.Split(string(data), "\n")
require.LessOrEqual(t, lineNumber, len(lines))
require.Equal(t, oldLine, lines[lineNumber-1])
lines[lineNumber-1] = newLine
content := strings.Join(lines, "\n")
os.WriteFile(path, []byte(content), 0644)
}
// AppendLines append multiple lines in a file.
func AppendLines(t *testing.T, path string, text string) {
data, err := os.ReadFile(path)
require.NoError(t, err)
lines := strings.Split(string(data), "\n")
newLines := strings.Split(text, "\n")
lines = append(lines, newLines...)
content := strings.Join(lines, "\n")
os.WriteFile(path, []byte(content), 0644)
}
/* Date Management */
func HumanTime(t *testing.T, str string) time.Time {
patterns := map[string]string{
"2006-01-02": `^\d{4}-\d{2}-\d{2}$`,
"2006-01-02 15:04": `^\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}$`,
"2006-01-02 15:04:05": `^\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}$`,
"2006-01-02 15:04:05.000": `^\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}[.]\d{3}$`,
}
for layout, regex := range patterns {
if match, _ := regexp.MatchString(regex, str); match {
result, err := time.Parse(layout, str)
require.NoError(t, err)
return result
}
}
t.Fatalf("No matching pattern for date %q", str)
return time.Time{} // zero
}