forked from natefinch/lumberjack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lumberjack_test.go
932 lines (764 loc) · 21.6 KB
/
lumberjack_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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
package lumberjack
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
"github.com/BurntSushi/toml"
"gopkg.in/yaml.v2"
)
// !!!NOTE!!!
//
// Running these tests in parallel will almost certainly cause sporadic (or even
// regular) failures, because they're all messing with the same global variable
// that controls the logic's mocked time.Now. So... don't do that.
// Since all the tests uses the time to determine filenames etc, we need to
// control the wall clock as much as possible, which means having a wall clock
// that doesn't change unless we want it to.
var fakeCurrentTime = time.Now()
func fakeTime() time.Time {
return fakeCurrentTime
}
func TestNewFile(t *testing.T) {
currentTime = fakeTime
dir := makeTempDir("TestNewFile", t)
defer os.RemoveAll(dir)
l := &Logger{
Filename: logFile(dir),
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(logFile(dir), b, t)
fileCount(dir, 1, t)
}
func TestOpenExisting(t *testing.T) {
currentTime = fakeTime
dir := makeTempDir("TestOpenExisting", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
data := []byte("foo!")
err := ioutil.WriteFile(filename, data, 0644)
isNil(err, t)
existsWithContent(filename, data, t)
l := &Logger{
Filename: filename,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
// make sure the file got appended
existsWithContent(filename, append(data, b...), t)
// make sure no other files were created
fileCount(dir, 1, t)
}
func TestWriteTooLong(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestWriteTooLong", t)
defer os.RemoveAll(dir)
l := &Logger{
Filename: logFile(dir),
MaxSize: 5,
}
defer l.Close()
b := []byte("booooooooooooooo!")
n, err := l.Write(b)
notNil(err, t)
equals(0, n, t)
equals(err.Error(),
fmt.Sprintf("write length %d exceeds maximum file size %d", len(b), l.MaxSize), t)
_, err = os.Stat(logFile(dir))
assert(os.IsNotExist(err), t, "File exists, but should not have been created")
}
func TestMakeLogDir(t *testing.T) {
currentTime = fakeTime
dir := time.Now().Format("TestMakeLogDir" + DefaultTimeFormat)
dir = filepath.Join(os.TempDir(), dir)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Filename: filename,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(logFile(dir), b, t)
fileCount(dir, 1, t)
}
func TestDefaultFilename(t *testing.T) {
currentTime = fakeTime
dir := os.TempDir()
filename := filepath.Join(dir, filepath.Base(os.Args[0])+"-lumberjack.log")
defer os.Remove(filename)
l := &Logger{}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
}
func TestAutoRotate(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestAutoRotate", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Filename: filename,
MaxSize: 10,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
fileCount(dir, 1, t)
newFakeTime()
b2 := []byte("foooooo!")
n, err = l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)
// the old logfile should be moved aside and the main logfile should have
// only the last write in it.
existsWithContent(filename, b2, t)
// the backup file will use the current fake time and have the old contents.
existsWithContent(backupFile(dir), b, t)
fileCount(dir, 2, t)
}
func TestFirstWriteRotate(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestFirstWriteRotate", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Filename: filename,
MaxSize: 10,
}
defer l.Close()
start := []byte("boooooo!")
err := ioutil.WriteFile(filename, start, 0600)
isNil(err, t)
newFakeTime()
// this would make us rotate
b := []byte("fooo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
existsWithContent(backupFile(dir), start, t)
fileCount(dir, 2, t)
}
func TestMaxBackups(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestMaxBackups", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Filename: filename,
MaxSize: 10,
MaxBackups: 1,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
fileCount(dir, 1, t)
newFakeTime()
// this will put us over the max
b2 := []byte("foooooo!")
n, err = l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)
// this will use the new fake time
secondFilename := backupFile(dir)
existsWithContent(secondFilename, b, t)
// make sure the old file still exists with the same content.
existsWithContent(filename, b2, t)
fileCount(dir, 2, t)
newFakeTime()
// this will make us rotate again
b3 := []byte("baaaaaar!")
n, err = l.Write(b3)
isNil(err, t)
equals(len(b3), n, t)
// this will use the new fake time
thirdFilename := backupFile(dir)
existsWithContent(thirdFilename, b2, t)
existsWithContent(filename, b3, t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(time.Millisecond * 10)
// should only have two files in the dir still
fileCount(dir, 2, t)
// second file name should still exist
existsWithContent(thirdFilename, b2, t)
// should have deleted the first backup
notExist(secondFilename, t)
// now test that we don't delete directories or non-logfile files
newFakeTime()
// create a file that is close to but different from the logfile name.
// It shouldn't get caught by our deletion filters.
notlogfile := logFile(dir) + ".foo"
err = ioutil.WriteFile(notlogfile, []byte("data"), 0644)
isNil(err, t)
// Make a directory that exactly matches our log file filters... it still
// shouldn't get caught by the deletion filter since it's a directory.
notlogfiledir := backupFile(dir)
err = os.Mkdir(notlogfiledir, 0700)
isNil(err, t)
newFakeTime()
// this will use the new fake time
fourthFilename := backupFile(dir)
// Create a log file that is/was being compressed - this should
// not be counted since both the compressed and the uncompressed
// log files still exist.
compLogFile := fourthFilename + compressSuffix
err = ioutil.WriteFile(compLogFile, []byte("compress"), 0644)
isNil(err, t)
// this will make us rotate again
b4 := []byte("baaaaaaz!")
n, err = l.Write(b4)
isNil(err, t)
equals(len(b4), n, t)
existsWithContent(fourthFilename, b3, t)
existsWithContent(fourthFilename+compressSuffix, []byte("compress"), t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(time.Millisecond * 10)
// We should have four things in the directory now - the 2 log files, the
// not log file, and the directory
fileCount(dir, 5, t)
// third file name should still exist
existsWithContent(filename, b4, t)
existsWithContent(fourthFilename, b3, t)
// should have deleted the first filename
notExist(thirdFilename, t)
// the not-a-logfile should still exist
exists(notlogfile, t)
// the directory
exists(notlogfiledir, t)
}
func TestCleanupExistingBackups(t *testing.T) {
// test that if we start with more backup files than we're supposed to have
// in total, that extra ones get cleaned up when we rotate.
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestCleanupExistingBackups", t)
defer os.RemoveAll(dir)
// make 3 backup files
data := []byte("data")
backup := backupFile(dir)
err := ioutil.WriteFile(backup, data, 0644)
isNil(err, t)
newFakeTime()
backup = backupFile(dir)
err = ioutil.WriteFile(backup+compressSuffix, data, 0644)
isNil(err, t)
newFakeTime()
backup = backupFile(dir)
err = ioutil.WriteFile(backup, data, 0644)
isNil(err, t)
// now create a primary log file with some data
filename := logFile(dir)
err = ioutil.WriteFile(filename, data, 0644)
isNil(err, t)
l := &Logger{
Filename: filename,
MaxSize: 10,
MaxBackups: 1,
}
defer l.Close()
newFakeTime()
b2 := []byte("foooooo!")
n, err := l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(time.Millisecond * 10)
// now we should only have 2 files left - the primary and one backup
fileCount(dir, 2, t)
}
func TestMaxAge(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestMaxAge", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Filename: filename,
MaxSize: 10,
MaxAge: 1,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
fileCount(dir, 1, t)
// two days later
newFakeTime()
b2 := []byte("foooooo!")
n, err = l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)
existsWithContent(backupFile(dir), b, t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(10 * time.Millisecond)
// We should still have 2 log files, since the most recent backup was just
// created.
fileCount(dir, 2, t)
existsWithContent(filename, b2, t)
// we should have deleted the old file due to being too old
existsWithContent(backupFile(dir), b, t)
// two days later
newFakeTime()
b3 := []byte("baaaaar!")
n, err = l.Write(b3)
isNil(err, t)
equals(len(b3), n, t)
existsWithContent(backupFile(dir), b2, t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(10 * time.Millisecond)
// We should have 2 log files - the main log file, and the most recent
// backup. The earlier backup is past the cutoff and should be gone.
fileCount(dir, 2, t)
existsWithContent(filename, b3, t)
// we should have deleted the old file due to being too old
existsWithContent(backupFile(dir), b2, t)
}
func TestOldLogFiles(t *testing.T) {
forEachBackupTestSpec(t, func(t *testing.T, test backupTestSpec) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestOldLogFiles", t)
defer os.RemoveAll(dir)
var backupDir string
effectiveBackupDir := dir
if test.customBackupDir {
backupDir = makeTempDir("TestOldLogFilesBackup", t)
defer os.RemoveAll(backupDir)
effectiveBackupDir = backupDir
}
filename := logFile(dir)
data := []byte("data")
err := ioutil.WriteFile(filename, data, 07)
isNil(err, t)
// This gives us a time with the same precision as the time we get from the
// timestamp in the name.
getTime := func() time.Time {
theTime := fakeTime()
if !test.local {
theTime = theTime.UTC()
}
theTime, err := time.Parse(test.timeFormat, theTime.Format(test.timeFormat))
isNil(err, t)
return theTime
}
t1 := getTime()
backup := backupFile(effectiveBackupDir, withLocalTime(test.local), withTimeFormat(test.timeFormat))
err = ioutil.WriteFile(backup, data, 07)
isNil(err, t)
newFakeTime()
t2 := getTime()
backup2 := backupFile(effectiveBackupDir, withLocalTime(test.local), withTimeFormat(test.timeFormat))
err = ioutil.WriteFile(backup2, data, 07)
isNil(err, t)
l := &Logger{Filename: filename, LocalTime: test.local, TimeFormat: test.timeFormat, BackupDir: backupDir}
files, err := l.oldLogFiles()
isNil(err, t)
equals(2, len(files), t)
// should be sorted by newest file first, which would be t2
equals(t2, files[0].timestamp, t)
equals(t1, files[1].timestamp, t)
})
}
func TestTimeFromName(t *testing.T) {
l := &Logger{Filename: "/var/log/myfoo/foo.log"}
prefix, ext := l.prefixAndExt()
tests := []struct {
filename string
want time.Time
wantErr bool
}{
{"foo-2014-05-04T14-44-33.555.log", time.Date(2014, 5, 4, 14, 44, 33, 555000000, time.UTC), false},
{"foo-2014-05-04T14-44-33.555", time.Time{}, true},
{"2014-05-04T14-44-33.555.log", time.Time{}, true},
{"foo.log", time.Time{}, true},
}
for _, test := range tests {
got, err := l.timeFromName(test.filename, prefix, ext)
equals(got, test.want, t)
equals(err != nil, test.wantErr, t)
}
}
func TestLocalTime(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestLocalTime", t)
defer os.RemoveAll(dir)
l := &Logger{
Filename: logFile(dir),
MaxSize: 10,
LocalTime: true,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
b2 := []byte("fooooooo!")
n2, err := l.Write(b2)
isNil(err, t)
equals(len(b2), n2, t)
existsWithContent(logFile(dir), b2, t)
existsWithContent(backupFile(dir, withLocalTime(true)), b, t)
}
func TestRotate(t *testing.T) {
forEachBackupTestSpec(t, func(t *testing.T, test backupTestSpec) {
currentTime = fakeTime
dir := makeTempDir("TestRotate", t)
defer os.RemoveAll(dir)
var backupDir string
effectiveBackupDir := dir
if test.customBackupDir {
// Temp non-existing dir - expected to be created on rotate
backupDir = filepath.Join(makeTempDir("TestOldLogFilesBackup", t), "backups")
defer os.RemoveAll(backupDir)
effectiveBackupDir = backupDir
}
filename := logFile(dir)
l := &Logger{
Filename: filename,
MaxBackups: 1,
MaxSize: 100, // megabytes
BackupDir: backupDir,
TimeFormat: test.timeFormat,
LocalTime: test.local,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
fileCount(dir, 1, t)
newFakeTime()
err = l.Rotate()
isNil(err, t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(10 * time.Millisecond)
filename2 := backupFile(effectiveBackupDir, withLocalTime(test.local), withTimeFormat(test.timeFormat))
existsWithContent(filename2, b, t)
existsWithContent(filename, []byte{}, t)
if test.customBackupDir {
fileCount(dir, 1, t)
fileCount(effectiveBackupDir, 1, t)
} else {
fileCount(dir, 2, t)
}
newFakeTime()
err = l.Rotate()
isNil(err, t)
// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(10 * time.Millisecond)
filename3 := backupFile(effectiveBackupDir, withLocalTime(test.local), withTimeFormat(test.timeFormat))
existsWithContent(filename3, []byte{}, t)
existsWithContent(filename, []byte{}, t)
if test.customBackupDir {
fileCount(dir, 1, t)
fileCount(effectiveBackupDir, 1, t)
} else {
fileCount(dir, 2, t)
}
b2 := []byte("foooooo!")
n, err = l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)
// this will use the new fake time
existsWithContent(filename, b2, t)
})
}
func TestCompressOnRotate(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestCompressOnRotate", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Compress: true,
Filename: filename,
MaxSize: 10,
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
existsWithContent(filename, b, t)
fileCount(dir, 1, t)
newFakeTime()
err = l.Rotate()
isNil(err, t)
// the old logfile should be moved aside and the main logfile should have
// nothing in it.
existsWithContent(filename, []byte{}, t)
// we need to wait a little bit since the files get compressed on a different
// goroutine.
<-time.After(300 * time.Millisecond)
// a compressed version of the log file should now exist and the original
// should have been removed.
bc := new(bytes.Buffer)
gz := gzip.NewWriter(bc)
_, err = gz.Write(b)
isNil(err, t)
err = gz.Close()
isNil(err, t)
existsWithContent(backupFile(dir)+compressSuffix, bc.Bytes(), t)
notExist(backupFile(dir), t)
fileCount(dir, 2, t)
}
func TestCompressOnResume(t *testing.T) {
currentTime = fakeTime
megabyte = 1
dir := makeTempDir("TestCompressOnResume", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
l := &Logger{
Compress: true,
Filename: filename,
MaxSize: 10,
}
defer l.Close()
// Create a backup file and empty "compressed" file.
filename2 := backupFile(dir)
b := []byte("foo!")
err := ioutil.WriteFile(filename2, b, 0644)
isNil(err, t)
err = ioutil.WriteFile(filename2+compressSuffix, []byte{}, 0644)
isNil(err, t)
newFakeTime()
b2 := []byte("boo!")
n, err := l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)
existsWithContent(filename, b2, t)
// we need to wait a little bit since the files get compressed on a different
// goroutine.
<-time.After(300 * time.Millisecond)
// The write should have started the compression - a compressed version of
// the log file should now exist and the original should have been removed.
bc := new(bytes.Buffer)
gz := gzip.NewWriter(bc)
_, err = gz.Write(b)
isNil(err, t)
err = gz.Close()
isNil(err, t)
existsWithContent(filename2+compressSuffix, bc.Bytes(), t)
notExist(filename2, t)
fileCount(dir, 2, t)
}
func TestJson(t *testing.T) {
data := []byte(`
{
"filename": "foo",
"maxsize": 5,
"maxage": 10,
"maxbackups": 3,
"localtime": true,
"compress": true,
"timeformat": "1:2.3",
"backupdir": "bar"
}`[1:])
l := Logger{}
err := json.Unmarshal(data, &l)
isNil(err, t)
equals("foo", l.Filename, t)
equals(5, l.MaxSize, t)
equals(10, l.MaxAge, t)
equals(3, l.MaxBackups, t)
equals(true, l.LocalTime, t)
equals(true, l.Compress, t)
equals("1:2.3", l.TimeFormat, t)
equals("bar", l.BackupDir, t)
}
func TestYaml(t *testing.T) {
data := []byte(`
filename: foo
maxsize: 5
maxage: 10
maxbackups: 3
localtime: true
compress: true
timeformat: 1:2.3
backupdir: bar`[1:])
l := Logger{}
err := yaml.Unmarshal(data, &l)
isNil(err, t)
equals("foo", l.Filename, t)
equals(5, l.MaxSize, t)
equals(10, l.MaxAge, t)
equals(3, l.MaxBackups, t)
equals(true, l.LocalTime, t)
equals(true, l.Compress, t)
equals("1:2.3", l.TimeFormat, t)
equals("bar", l.BackupDir, t)
}
func TestToml(t *testing.T) {
data := `
filename = "foo"
maxsize = 5
maxage = 10
maxbackups = 3
localtime = true
compress = true
timeformat = "1:2.3"
backupdir = "bar"`[1:]
l := Logger{}
md, err := toml.Decode(data, &l)
isNil(err, t)
equals("foo", l.Filename, t)
equals(5, l.MaxSize, t)
equals(10, l.MaxAge, t)
equals(3, l.MaxBackups, t)
equals(true, l.LocalTime, t)
equals(true, l.Compress, t)
equals("1:2.3", l.TimeFormat, t)
equals("bar", l.BackupDir, t)
equals(0, len(md.Undecoded()), t)
}
func forEachBackupTestSpec(t *testing.T, do func(t *testing.T, test backupTestSpec)) {
for _, test := range backupTestSpecs() {
t.Run(test.name, func(t *testing.T) {
do(t, test)
})
}
}
type backupTestSpec struct {
name string
local bool
timeFormat string
customBackupDir bool
}
func backupTestSpecs() []backupTestSpec {
return []backupTestSpec{
{
name: "Default time format, UTC, default backup dir",
local: false,
timeFormat: DefaultTimeFormat,
customBackupDir: false,
},
{
name: "Default time format, local time, custom backup dir",
local: true,
timeFormat: DefaultTimeFormat,
customBackupDir: true,
},
{
name: "Custom time format, UTC, custom backup dir",
local: false,
timeFormat: "20060102150405000",
customBackupDir: true,
},
{
name: "Default time format, local time, default backup dir",
local: true,
timeFormat: "2006.01.02.15.04.05.000",
customBackupDir: false,
},
}
}
// makeTempDir creates a file with a semi-unique name in the OS temp directory.
// It should be based on the name of the test, to keep parallel tests from
// colliding, and must be cleaned up after the test is finished.
func makeTempDir(name string, t testing.TB) string {
dir := time.Now().Format(name + DefaultTimeFormat)
dir = filepath.Join(os.TempDir(), dir)
isNilUp(os.Mkdir(dir, 0700), t, 1)
return dir
}
// existsWithContent checks that the given file exists and has the correct content.
func existsWithContent(path string, content []byte, t testing.TB) {
info, err := os.Stat(path)
isNilUp(err, t, 1)
equalsUp(int64(len(content)), info.Size(), t, 1)
b, err := ioutil.ReadFile(path)
isNilUp(err, t, 1)
equalsUp(content, b, t, 1)
}
// logFile returns the log file name in the given directory for the current fake
// time.
func logFile(dir string) string {
return filepath.Join(dir, "foobar.log")
}
func backupFile(dir string, opts ...backupFileOpt) string {
options := backupFileOpts{
local: false,
timeFormat: DefaultTimeFormat,
}
for _, opt := range opts {
opt(&options)
}
currTime := fakeTime()
if !options.local {
currTime = currTime.UTC()
}
return filepath.Join(dir, "foobar-"+currTime.Format(options.timeFormat)+".log")
}
type backupFileOpts struct {
local bool
timeFormat string
}
type backupFileOpt func(opts *backupFileOpts)
func withLocalTime(local bool) backupFileOpt {
return func(opts *backupFileOpts) {
opts.local = local
}
}
func withTimeFormat(format string) backupFileOpt {
return func(opts *backupFileOpts) {
opts.timeFormat = format
}
}
// fileCount checks that the number of files in the directory is exp.
func fileCount(dir string, exp int, t testing.TB) {
files, err := ioutil.ReadDir(dir)
isNilUp(err, t, 1)
// Make sure no other files were created.
equalsUp(exp, len(files), t, 1)
}
// newFakeTime sets the fake "current time" to two days later.
func newFakeTime() {
fakeCurrentTime = fakeCurrentTime.Add(time.Hour * 24 * 2)
}
func notExist(path string, t testing.TB) {
_, err := os.Stat(path)
assertUp(os.IsNotExist(err), t, 1, "expected to get os.IsNotExist, but instead got %v", err)
}
func exists(path string, t testing.TB) {
_, err := os.Stat(path)
assertUp(err == nil, t, 1, "expected file to exist, but got error from os.Stat: %v", err)
}