-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
466 lines (403 loc) · 12.1 KB
/
main_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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// main_test.go
package main
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var userInputMutex sync.Mutex
var TestOutputDir string = "test/test-resources/test_output_dir"
var TestDirUnFester string = "test/test-resources/un-festerized"
var TestDirFester string = "test/test-resources/festerized"
// MemorySink implements zap.Sink by writing all messages to a buffer.
type MemorySink struct {
*bytes.Buffer
}
// Implement Close and Sync as no-ops to satisfy the interface. The Write
// method is provided by the embedded buffer.
func (s *MemorySink) Close() error { return nil }
func (s *MemorySink) Sync() error { return nil }
// createLogger creates a test logger to be used
func createLogger() (Logger *zap.Logger, sink *MemorySink) {
// Create a sink instance, and register it with zap for the "memory"
// protocol.
sink = &MemorySink{new(bytes.Buffer)}
zap.RegisterSink("memory", func(*url.URL) (zap.Sink, error) {
return sink, nil
})
// Create a logger instance using the registered sink.
Logger = zap.New(zapcore.NewCore(
zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig()),
zapcore.AddSync(sink),
zapcore.DebugLevel,
))
return Logger, sink
}
// simulateUserInput simulates stdin input during testing
func simulateUserInput(input string) {
userInputMutex.Lock()
defer userInputMutex.Unlock()
reader, writer, _ := os.Pipe()
go func() {
defer writer.Close()
io.WriteString(writer, input)
}()
os.Stdin = reader
}
// redirectStdoutToBuffer redirects the standard out so that it is not seen when running test
func redirectStdoutToBuffer(t *testing.T) *bytes.Buffer {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
returnedBuffer := new(bytes.Buffer)
go func() {
defer func() {
_ = r.Close()
os.Stdout = oldStdout
}()
io.Copy(returnedBuffer, r)
}()
// Restore os.Stdout when the test ends
t.Cleanup(func() {
_ = r.Close()
os.Stdout = oldStdout
})
return returnedBuffer
}
// compareCSVs compares two CSV files and returns true if they are identical, false otherwise.
func compareCSVs(file1, file2 string) (bool, error) {
// Open the first CSV file
f1, err := os.Open(file1)
if err != nil {
return false, err
}
defer f1.Close()
// Open the second CSV file
f2, err := os.Open(file2)
if err != nil {
return false, err
}
defer f2.Close()
// Create CSV readers for both files
reader1 := csv.NewReader(f1)
reader2 := csv.NewReader(f2)
// Compare row by row
for {
row1, err1 := reader1.Read()
row2, err2 := reader2.Read()
// Check for EOF
if err1 != nil && err2 != nil {
if err1 == err2 {
return true, nil // Files are identical
}
return false, fmt.Errorf("error comparing files: %v, %v", err1, err2)
}
// Check if number of columns match
if len(row1) != len(row2) {
return false, nil // Files have different structure
}
// Compare each column
for i := range row1 {
if row1[i] != row2[i] {
return false, nil // Files have different content
}
}
}
}
// TestValidateLogLevel tests loglevels
func TestValidateLoglevel(t *testing.T) {
tests := []struct {
loglevel string
wantErr bool
}{
{"INFO", false},
{"DEBUG", false},
{"ERROR", false},
{"INVALID", true},
}
for _, tt := range tests {
t.Run(tt.loglevel, func(t *testing.T) {
loglevel = tt.loglevel
err := ValidateLoglevel()
if tt.wantErr && err == nil {
t.Error("Expected an error, but got none.")
} else if !tt.wantErr && err != nil {
t.Error("Unexpected error:", err)
}
})
}
}
// TestValidateVersion tests versions are properly validated
func TestValidateVersion(t *testing.T) {
tests := []struct {
version string
wantErr bool
}{
{"2", false},
{"3", false},
{"4", true},
}
for _, tt := range tests {
t.Run(tt.version, func(t *testing.T) {
iiifApiVersion = tt.version
err := ValidateVersion()
if tt.wantErr && err == nil {
t.Error("Expected an error, but got none.")
} else if !tt.wantErr && err != nil {
t.Error("Unexpected error:", err)
}
})
}
}
// TestCreateOutputDir tests the creation of an output directory given valid and invalid inputs
func TestCreateOutputDir(t *testing.T) {
_ = redirectStdoutToBuffer(t)
testCases := []struct {
name string
out string
userInput string
expectedError error
}{
{
name: "Output directory does not exist",
out: TestOutputDir,
userInput: "",
expectedError: nil,
},
{
name: "Output directory already exists, user enters 'yes'",
out: TestOutputDir,
userInput: "yes\n",
expectedError: nil,
},
{
name: "Output directory already exists, user enters 'no'",
out: TestOutputDir,
userInput: "no\n",
expectedError: errors.New("aborted"),
},
}
for _, tc := range testCases {
out = tc.out
// Use the helper function to simulate user input during testing
simulateUserInput(tc.userInput)
// Call the function being tested
err := CreateOutputDir()
// Clean up the created directory
defer os.RemoveAll(tc.out)
// Check the result against the expected error
if (err != nil && tc.expectedError == nil) || (err == nil && tc.expectedError != nil) || (err != nil && err.Error() != tc.expectedError.Error()) {
t.Errorf("[%s] Test failed. Test failed onExpected error: %v, got: %v", tc.name, tc.expectedError, err)
}
}
}
// TestFesterStatus tests proper responses to connect to Server
func TestFesterStatus(t *testing.T) {
tests := []struct {
name string
getStatusURL string
responseCode int
expectedError error
}{
{
name: "Fester available, status 200",
getStatusURL: "https://test.ingest.iiif.library.ucla.edu/fester/status",
responseCode: http.StatusOK,
expectedError: nil,
},
{
name: "Fester unavailable, status 404",
getStatusURL: "https://test.ingest.iiif.library.ucla.edu/fester/notfound",
responseCode: http.StatusNotFound,
expectedError: errors.New("error connecting to Fester: Unexpected status code"),
},
// Add more test cases as needed
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Call the function being tested with the server URL
statusCode, err := FesterStatus(tc.getStatusURL)
// Check if the returned status code matches the expected one
if statusCode != tc.responseCode {
t.Errorf("Expected status code %d, got %d", tc.responseCode, statusCode)
}
// Check if the returned error matches the expected one
if (err == nil && tc.expectedError != nil) || (err != nil && err.Error() != tc.expectedError.Error()) {
t.Errorf("Expected error: %v, got: %v", tc.expectedError, err)
}
})
}
}
// TestUploadCSV tests if a CSV is properly uploaded otherwise an error should be thrown and
func TestUploadCSV(t *testing.T) {
// Valid File
testDirectory := "test/test-resources"
testDirUnFester := "test/test-resources/un-festerized/"
testDirFester := "test/test-resources/festerized/"
tests := []struct {
fileName string
verifiedFesterizedpath string
postURL string
iiifAPIVersion string
iiifHost string
metadataUpdate bool
headers map[string]string
expectedError error
expStatusCode int
}{
{
fileName: "ballin.csv",
postURL: "https://test.ingest.iiif.library.ucla.edu/collections",
iiifAPIVersion: "2",
iiifHost: "",
metadataUpdate: false,
headers: map[string]string{
"User-Agent": fmt.Sprintf("%s/%s", "Festerize", "0.4.2")},
expectedError: nil,
expStatusCode: 201,
},
{
fileName: "chandler.csv",
postURL: "https://test.ingest.iiif.library.ucla.edu/collections",
iiifAPIVersion: "2",
iiifHost: "",
metadataUpdate: false,
headers: map[string]string{
"User-Agent": fmt.Sprintf("%s/%s", "Festerize", "0.4.2")},
expectedError: nil,
expStatusCode: 201,
},
{
fileName: "chase.csv",
postURL: "https://test.ingest.iiif.library.ucla.edu/collections",
iiifAPIVersion: "2",
iiifHost: "",
metadataUpdate: false,
headers: map[string]string{
"User-Agent": fmt.Sprintf("%s/%s", "Festerize", "0.4.2")},
expectedError: nil,
expStatusCode: 201,
},
{
fileName: "edson.csv",
postURL: "https://test.ingest.iiif.library.ucla.edu/collections",
iiifAPIVersion: "2",
iiifHost: "",
metadataUpdate: false,
headers: map[string]string{
"User-Agent": fmt.Sprintf("%s/%s", "Festerize", "0.4.2")},
expectedError: nil,
expStatusCode: 201,
},
}
for _, tc := range tests {
t.Run(tc.fileName, func(t *testing.T) {
filePath := testDirUnFester + tc.fileName
response, responseBody, err := uploadCSV(filePath, tc.postURL, tc.iiifAPIVersion, tc.iiifHost,
tc.metadataUpdate, tc.headers)
assert.Equal(t, err, nil)
assert.Equal(t, response.StatusCode, tc.expStatusCode)
if response.StatusCode == 201 {
tempDir, err := os.MkdirTemp(testDirectory, "temporary-")
if err != nil {
fmt.Println("Error creating temporary directory:", err)
return
}
defer os.RemoveAll(tempDir) // Clean up the temporary directory when done
festerizedPath := filepath.Join(tempDir, tc.fileName)
file, _ := os.Create(festerizedPath)
defer file.Close()
_, _ = file.Write(responseBody)
filePath = testDirFester + tc.fileName
match, err := compareCSVs(festerizedPath, filePath)
if err != nil {
fmt.Println("Error:", err)
return
}
if !match {
fmt.Println("Files match.")
t.Errorf("Festerized CSV did not contain expected values")
}
}
})
}
}
// TestMainValid tests an instance where all inputs are valid to the program and a file should be processed fully
func TestMainValid(t *testing.T) {
redirectStdoutToBuffer(t)
// Create a logger instance using the registered sink.
logger, sink := createLogger()
defer logger.Sync()
Logger = logger
testCSV := "/ballin.csv"
os.Args = []string{"cmd", "--iiif-api-version=2", "--out=" + TestOutputDir, "--loglevel=INFO", TestDirUnFester + testCSV}
defer os.RemoveAll(TestOutputDir)
simulateUserInput("yes")
main()
// Assert sink contents
output := sink.String()
// Verifies that file was uploaded successfully through the logger
if !strings.Contains(output, `File was uploaded to Fester succesfully`) {
t.Error("File should have been uploaded to Fester succesfully but an error occured")
}
match, err := compareCSVs(TestOutputDir+"output"+testCSV, TestDirFester+testCSV)
if err != nil {
fmt.Println("Error:", err)
return
}
if !match {
fmt.Println("Files match.")
t.Errorf("Festerized CSV did not contain expected values")
}
}
// TestMainInvalidCSV tests an invalid CSV and gets a valid response
func TestMainInvalidCSV(t *testing.T) {
redirectStdoutToBuffer(t)
// Create a logger instance using the registered sink.
logger, sink := createLogger()
defer logger.Sync()
Logger = logger
testCSV := "/random.csv"
os.Args = []string{"cmd", "--iiif-api-version=2", "--out=" + TestOutputDir, "--loglevel=INFO", testCSV}
defer os.RemoveAll(TestOutputDir)
simulateUserInput("yes")
main()
// Assert sink contents
output := sink.String()
if !strings.Contains(output, `File does not exist`) {
t.Error("File should not exist")
}
}
// TestInvalidFesterResponse tests an instance where Fester responds with a non 200 code
func TestInvalidFesterResponse(t *testing.T) {
redirectStdoutToBuffer(t)
// Create a logger instance using the registered sink.
logger, sink := createLogger()
defer logger.Sync()
Logger = logger
festerizeVersion = "0.0.1"
testCSV := "/ballin.csv"
os.Args = []string{"cmd", "--iiif-api-version=2", "--out=" + TestOutputDir, "--loglevel=INFO", TestDirUnFester + testCSV}
defer os.RemoveAll(TestOutputDir)
simulateUserInput("yes")
main()
// Assert sink contents
output := sink.String()
// Verifies that file was uploaded successfully through the logger
// fmt.Println(output)
if !strings.Contains(output, `Failed to upload file to Fester`) {
t.Error("The file should have failed to upload to Fester")
}
}