-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathnew_test.go
More file actions
433 lines (346 loc) · 12.8 KB
/
new_test.go
File metadata and controls
433 lines (346 loc) · 12.8 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package cmd
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/snippet"
"github.com/pelletier/go-toml"
)
// MockReadCloser is a mock implementation of io.ReadCloser
type MockReadCloser struct {
*strings.Reader
}
// Close does nothing for this mock implementation
func (m *MockReadCloser) Close() error {
return nil
}
func TestScan(t *testing.T) {
message := "Enter something: "
input := "test\n" // Simulated user input
want := "test" // Expected output
expectedError := error(nil)
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input
inputReader := &MockReadCloser{strings.NewReader(input)}
result, err := scan(message, &outputBuffer, inputReader, false)
// Check if the input was printed
got := result
// Check if the result matches the expected result
if want != got {
t.Errorf("Expected result %q, but got %q", want, got)
}
// Check if the error matches the expected error
if err != expectedError {
t.Errorf("Expected error %v, but got %v", expectedError, err)
}
}
func TestScan_EmptyStringWithAllowEmpty(t *testing.T) {
message := "Enter something: "
input := "\n" // Simulated user input
want := "" // Expected output
expectedError := error(nil) // Should not error
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input
inputReader := &MockReadCloser{strings.NewReader(input)}
result, err := scan(message, &outputBuffer, inputReader, true)
// Check if the input was printed
got := result
// Check if the result is empty
if want != got {
t.Errorf("Expected result %q, but got %q", want, got)
}
// Check if the error matches the expected error
if err != expectedError {
t.Errorf("Expected error %v, but got %v", expectedError, err)
}
}
func TestScan_EmptyStringWithoutAllowEmpty(t *testing.T) {
message := "Enter something: "
input := "\n" // Simulated user input
want := "" // Expected output
expectedError := CanceledError()
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input
inputReader := &MockReadCloser{strings.NewReader(input)}
result, err := scan(message, &outputBuffer, inputReader, false)
// Check if the input was printed
got := result
// Check if the result matches the expected result
if want != got {
t.Errorf("Expected result %q, but got %q", want, got)
}
// Check if the error matches the expected error
if err.Error() != expectedError.Error() {
t.Errorf("Expected error %v, but got %v", expectedError, err)
}
}
func TestScanMultiLine_ExitsOnTwoEmptyLines(t *testing.T) {
prompt := "Enter something: "
secondPrompt := "whatever"
input := "test\nnewline here\nand another;\n\n\n" // Simulated user input
want := "test\nnewline here\nand another;" // Expected output
expectedError := error(nil)
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input
inputReader := &MockReadCloser{strings.NewReader(input)}
result, err := scanMultiLine(prompt, secondPrompt, &outputBuffer, inputReader)
// Check if the input was printed
got := result
// Check if the result matches the expected result
if want != got {
t.Errorf("Expected result %q, but got %q", want, got)
}
// Check if the error matches the expected error
if err != expectedError {
t.Errorf("Expected error %v, but got %v", expectedError, err)
}
}
func TestNew_SnippetCreationWithSnippetDirectory(t *testing.T) {
// Setup temporary directory for config
tempDir, _ := os.MkdirTemp("", "testdata")
tempSnippetFile := filepath.Join(tempDir, "snippet.toml")
tempSnippetDir1 := filepath.Join(tempDir, "snippets1")
tempSnippetDir2 := filepath.Join(tempDir, "snippets2")
// Clean up temp dirs, needed for windows
// https://github.com/golang/go/issues/51442
defer os.RemoveAll(tempDir)
// Create snippet directories
if err := os.Mkdir(tempSnippetDir1, 0755); err != nil {
t.Fatalf("Failed to create temp snippet directory: %v", err)
}
if err := os.Mkdir(tempSnippetDir2, 0755); err != nil {
t.Fatalf("Failed to create temp snippet directory: %v", err)
}
// Create dummy snippets in the main snippet file
mainSnippets := snippet.Snippets{
Snippets: []snippet.SnippetInfo{
{Description: "main snippet 1", Command: "echo main1"},
{Description: "main snippet 2", Command: "echo main2"},
},
}
saveSnippetsToFile(t, tempSnippetFile, mainSnippets)
// Create dummy snippets in the snippet directories
dirSnippets1 := snippet.Snippets{
Snippets: []snippet.SnippetInfo{
{Description: "dir1 snippet 1", Command: "echo dir1-1"},
},
}
dirSnippets2 := snippet.Snippets{
Snippets: []snippet.SnippetInfo{
{Description: "dir2 snippet 1", Command: "echo dir2-1"},
},
}
saveSnippetsToFile(t, filepath.Join(tempSnippetDir1, "snippets1.toml"), dirSnippets1)
saveSnippetsToFile(t, filepath.Join(tempSnippetDir2, "snippets2.toml"), dirSnippets2)
// Mock configuration
config.Conf.General.SnippetFile = tempSnippetFile
config.Conf.General.SnippetDirs = []string{tempSnippetDir1, tempSnippetDir2}
// Simulate creating a new snippet
args := []string{"echo new command"}
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input
inputReader := &MockReadCloser{strings.NewReader("test\ntest")}
err := _new(inputReader, &outputBuffer, args)
if err != nil {
t.Fatalf("Failed to create new snippet: %v", err)
}
// Load the main snippet file and check:
// 1 - if the new snippet is added
// 2 - if the number of snippets is correct (to avoid bugs like overwriting with dir snippets)
var updatedMainSnippets snippet.Snippets
loadSnippetsFromFile(t, tempSnippetFile, &updatedMainSnippets)
if len(updatedMainSnippets.Snippets) != 3 {
t.Fatalf("Expected 3 snippets in main snippet file, got %d", len(updatedMainSnippets.Snippets))
}
newSnippet := updatedMainSnippets.Snippets[2]
if newSnippet.Command != "echo new command" {
t.Errorf("Expected new command to be 'echo new command', got '%s'", newSnippet.Command)
}
// Ensure the snippet files in the directories remain unchanged
var unchangedDirSnippets1, unchangedDirSnippets2 snippet.Snippets
loadSnippetsFromFile(t, filepath.Join(tempSnippetDir1, "snippets1.toml"), &unchangedDirSnippets1)
loadSnippetsFromFile(t, filepath.Join(tempSnippetDir2, "snippets2.toml"), &unchangedDirSnippets2)
if !compareSnippets(dirSnippets1, unchangedDirSnippets1) {
t.Errorf("Snippets in directory 1 have changed")
}
if !compareSnippets(dirSnippets2, unchangedDirSnippets2) {
t.Errorf("Snippets in directory 2 have changed")
}
}
func saveSnippetsToFile(t *testing.T, filename string, snippets snippet.Snippets) {
f, err := os.Create(filename)
if err != nil {
t.Fatalf("Failed to create snippet file: %v", err)
}
defer f.Close()
if err := toml.NewEncoder(f).Encode(snippets); err != nil {
t.Fatalf("Failed to encode snippets to file: %v", err)
}
}
func loadSnippetsFromFile(t *testing.T, filename string, snippets *snippet.Snippets) {
f, err := os.ReadFile(filename)
if err != nil {
t.Fatalf("Failed to read snippet file: %v", err)
}
if err := toml.Unmarshal(f, snippets); err != nil {
t.Fatalf("Failed to unmarshal snippets from file: %v", err)
}
}
func compareSnippets(a, b snippet.Snippets) bool {
if len(a.Snippets) != len(b.Snippets) {
return false
}
for i := range a.Snippets {
if a.Snippets[i].Description != b.Snippets[i].Description || a.Snippets[i].Command != b.Snippets[i].Command {
return false
}
}
return true
}
func TestNew_WithStaticFlag(t *testing.T) {
// Setup temporary directory for config
tempDir, _ := os.MkdirTemp("", "testdata")
tempSnippetFile := filepath.Join(tempDir, "snippet.toml")
// Clean up temp dirs
defer os.RemoveAll(tempDir)
// Create empty snippet file
_, err := os.Create(tempSnippetFile)
if err != nil {
t.Fatalf("Failed to create temp snippet file: %v", err)
}
// Mock configuration
config.Conf.General.SnippetFile = tempSnippetFile
config.Conf.General.SnippetDirs = []string{}
// Set the static flag to true
originalStatic := config.Flag.Static
config.Flag.Static = true
defer func() { config.Flag.Static = originalStatic }()
// Simulate creating a new snippet with static flag
args := []string{"echo hello <name>"}
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input (description)
inputReader := &MockReadCloser{strings.NewReader("test description\n")}
err = _new(inputReader, &outputBuffer, args)
if err != nil {
t.Fatalf("Failed to create new snippet: %v", err)
}
// Load the snippet file and check if static field is set
var snippets snippet.Snippets
loadSnippetsFromFile(t, tempSnippetFile, &snippets)
if len(snippets.Snippets) != 1 {
t.Fatalf("Expected 1 snippet, got %d", len(snippets.Snippets))
}
createdSnippet := snippets.Snippets[0]
if createdSnippet.Command != "echo hello <name>" {
t.Errorf("Expected command to be 'echo hello <name>', got '%s'", createdSnippet.Command)
}
if createdSnippet.Description != "test description" {
t.Errorf("Expected description to be 'test description', got '%s'", createdSnippet.Description)
}
// Check that static field is set to true
if createdSnippet.Static == nil {
t.Error("Expected Static field to be set, got nil")
} else if !*createdSnippet.Static {
t.Error("Expected Static field to be true, got false")
}
}
func TestNew_WithoutStaticFlag(t *testing.T) {
// Setup temporary directory for config
tempDir, _ := os.MkdirTemp("", "testdata")
tempSnippetFile := filepath.Join(tempDir, "snippet.toml")
// Clean up temp dirs
defer os.RemoveAll(tempDir)
// Create empty snippet file
_, err := os.Create(tempSnippetFile)
if err != nil {
t.Fatalf("Failed to create temp snippet file: %v", err)
}
// Mock configuration
config.Conf.General.SnippetFile = tempSnippetFile
config.Conf.General.SnippetDirs = []string{}
// Ensure the static flag is false
originalStatic := config.Flag.Static
config.Flag.Static = false
defer func() { config.Flag.Static = originalStatic }()
// Simulate creating a new snippet without static flag
args := []string{"echo hello <name>"}
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input (description)
inputReader := &MockReadCloser{strings.NewReader("test description\n")}
err = _new(inputReader, &outputBuffer, args)
if err != nil {
t.Fatalf("Failed to create new snippet: %v", err)
}
// Load the snippet file and check if static field is not set
var snippets snippet.Snippets
loadSnippetsFromFile(t, tempSnippetFile, &snippets)
if len(snippets.Snippets) != 1 {
t.Fatalf("Expected 1 snippet, got %d", len(snippets.Snippets))
}
createdSnippet := snippets.Snippets[0]
if createdSnippet.Command != "echo hello <name>" {
t.Errorf("Expected command to be 'echo hello <name>', got '%s'", createdSnippet.Command)
}
// Check that static field is nil (not set) when flag is false
if createdSnippet.Static != nil {
t.Errorf("Expected Static field to be nil when flag is false, got %v", *createdSnippet.Static)
}
}
func TestNew_WithStaticFlagAndEditor(t *testing.T) {
// Setup temporary directory for config
tempDir, _ := os.MkdirTemp("", "testdata")
tempSnippetFile := filepath.Join(tempDir, "snippet.toml")
// Clean up temp dirs
defer os.RemoveAll(tempDir)
// Create empty snippet file
_, err := os.Create(tempSnippetFile)
if err != nil {
t.Fatalf("Failed to create temp snippet file: %v", err)
}
// Mock configuration
config.Conf.General.SnippetFile = tempSnippetFile
config.Conf.General.SnippetDirs = []string{}
config.Conf.General.Editor = "echo" // Use echo as a mock editor that won't actually open
// Set flags
originalStatic := config.Flag.Static
originalUseEditor := config.Flag.UseEditor
config.Flag.Static = true
config.Flag.UseEditor = true
defer func() {
config.Flag.Static = originalStatic
config.Flag.UseEditor = originalUseEditor
}()
// Simulate creating a new snippet with static flag and editor
args := []string{} // No command args when using editor
// Create a buffer for output
var outputBuffer bytes.Buffer
// Create a mock ReadCloser for input
inputReader := &MockReadCloser{strings.NewReader("")}
err = _new(inputReader, &outputBuffer, args)
if err != nil {
t.Fatalf("Failed to create new snippet: %v", err)
}
// Load the snippet file and check if static field is set
var snippets snippet.Snippets
loadSnippetsFromFile(t, tempSnippetFile, &snippets)
if len(snippets.Snippets) != 1 {
t.Fatalf("Expected 1 snippet, got %d", len(snippets.Snippets))
}
createdSnippet := snippets.Snippets[0]
// Check that static field is set to true even when using editor
if createdSnippet.Static == nil {
t.Error("Expected Static field to be set, got nil")
} else if !*createdSnippet.Static {
t.Error("Expected Static field to be true, got false")
}
}