-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathfat32_test.go
1168 lines (1103 loc) · 36.4 KB
/
fat32_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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fat32_test
/*
These tests the exported functions
We want to do full-in tests with files
*/
import (
"bytes"
"fmt"
"io"
"math/rand/v2"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/diskfs/go-diskfs"
"github.com/diskfs/go-diskfs/disk"
"github.com/diskfs/go-diskfs/filesystem"
"github.com/diskfs/go-diskfs/filesystem/fat32"
"github.com/diskfs/go-diskfs/testhelper"
"github.com/diskfs/go-diskfs/util"
)
var (
intImage = os.Getenv("TEST_IMAGE")
keepTmpFiles = os.Getenv("KEEPTESTFILES")
)
func getOpenMode(mode int) string {
modes := make([]string, 0)
if mode&os.O_CREATE == os.O_CREATE {
modes = append(modes, "CREATE")
}
if mode&os.O_APPEND == os.O_APPEND {
modes = append(modes, "APPEND")
}
if mode&os.O_RDWR == os.O_RDWR {
modes = append(modes, "RDWR")
} else {
modes = append(modes, "RDONLY")
}
return strings.Join(modes, "|")
}
func tmpFat32(fill bool, embedPre, embedPost int64) (*os.File, error) {
filename := "fat32_test"
f, err := os.CreateTemp("", filename)
if err != nil {
return nil, fmt.Errorf("Failed to create tempfile %s :%v", filename, err)
}
// either copy the contents of the base file over, or make a file of similar size
b, err := os.ReadFile(fat32.Fat32File)
if err != nil {
return nil, fmt.Errorf("Failed to read contents of %s: %v", fat32.Fat32File, err)
}
if embedPre > 0 {
empty := make([]byte, embedPre)
written, err := f.Write(empty)
if err != nil {
return nil, fmt.Errorf("Failed to write %d zeroes at beginning of %s: %v", embedPre, filename, err)
}
if written != len(empty) {
return nil, fmt.Errorf("wrote only %d zeroes at beginning of %s instead of %d", written, filename, len(empty))
}
}
if fill {
written, err := f.Write(b)
if err != nil {
return nil, fmt.Errorf("Failed to write contents of %s to %s: %v", fat32.Fat32File, filename, err)
}
if written != len(b) {
return nil, fmt.Errorf("wrote only %d bytes of %s to %s instead of %d", written, fat32.Fat32File, filename, len(b))
}
} else {
size := int64(len(b))
empty := make([]byte, size)
written, err := f.Write(empty)
if err != nil {
return nil, fmt.Errorf("Failed to write %d zeroes as content of %s: %v", size, filename, err)
}
if written != len(empty) {
return nil, fmt.Errorf("wrote only %d zeroes as content of %s instead of %d", written, filename, len(empty))
}
}
if embedPost > 0 {
empty := make([]byte, embedPost)
written, err := f.Write(empty)
if err != nil {
return nil, fmt.Errorf("Failed to write %d zeroes at end of %s: %v", embedPost, filename, err)
}
if written != len(empty) {
return nil, fmt.Errorf("wrote only %d zeroes at end of %s instead of %d", written, filename, len(empty))
}
}
return f, nil
}
func TestFat32Type(t *testing.T) {
fs := &fat32.FileSystem{}
fstype := fs.Type()
expected := filesystem.TypeFat32
if fstype != expected {
t.Errorf("Type() returns %v instead of expected %v", fstype, expected)
}
}
func TestFat32Mkdir(t *testing.T) {
// only do this test if os.Getenv("TEST_IMAGE") contains a real image
if intImage == "" {
return
}
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, post, pre int64, fatFunc func(util.File, int64, int64, int64) (*fat32.FileSystem, error)) {
// create our directories
tests := []string{
"/",
"/foo",
"/foo/bar",
"/a/b/c",
}
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fatFunc(f, fileInfo.Size()-pre-post, pre, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
for _, p := range tests {
err := fs.Mkdir(p)
switch {
case err != nil:
t.Errorf("Mkdir(%s): error %v", p, err)
default:
// check that the directory actually was created
output := new(bytes.Buffer)
mpath := "/file.img"
mounts := map[string]string{
f.Name(): mpath,
}
err := testhelper.DockerRun(nil, output, false, true, mounts, intImage, "mdir", "-i", fmt.Sprintf("%s@@%d", mpath, pre), fmt.Sprintf("::%s", p))
if err != nil {
t.Errorf("Mkdir(%s): Unexpected err: %v", p, err)
t.Log(output.String())
}
}
}
}
t.Run("read to Mkdir", func(t *testing.T) {
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0, fat32.Read)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000, fat32.Read)
})
})
t.Run("Create to Mkdir", func(t *testing.T) {
// This is to enable Create "fit" into the common testing logic
createShim := func(file util.File, size int64, start int64, blocksize int64) (*fat32.FileSystem, error) {
return fat32.Create(file, size, start, blocksize, "")
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0, createShim)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000, createShim)
})
})
}
func TestFat32Create(t *testing.T) {
tests := []struct {
blocksize int64
filesize int64
fs *fat32.FileSystem
err error
}{
{500, 6000, nil, fmt.Errorf("blocksize for FAT32 must be")},
{513, 6000, nil, fmt.Errorf("blocksize for FAT32 must be")},
{512, fat32.Fat32MaxSize + 100000, nil, fmt.Errorf("requested size is larger than maximum allowed FAT32")},
{512, 0, nil, fmt.Errorf("requested size is smaller than minimum allowed FAT32")},
{512, 10000000, &fat32.FileSystem{}, nil},
}
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
for _, t2 := range tests {
tt := t2
t.Run(fmt.Sprintf("blocksize %d filesize %d", tt.blocksize, tt.filesize), func(t *testing.T) {
// get a temporary working file
f, err := tmpFat32(false, pre, post)
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
// create the filesystem
fs, err := fat32.Create(f, tt.filesize-pre-post, pre, tt.blocksize, "")
switch {
case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
t.Errorf("Create(%s, %d, %d, %d): mismatched errors\nactual %v\nexpected %v", f.Name(), tt.filesize, 0, tt.blocksize, err, tt.err)
case (fs == nil && tt.fs != nil) || (fs != nil && tt.fs == nil):
t.Errorf("Create(%s, %d, %d, %d): mismatched fs\nactual %v\nexpected %v", f.Name(), tt.filesize, 0, tt.blocksize, fs, tt.fs)
}
// we do not match the filesystems here, only check functional accuracy
})
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
}
func TestFat32Read(t *testing.T) {
// test cases:
// - invalid blocksize
// - invalid file size (0 and too big)
// - invalid FSISBootSector
// - valid file
tests := []struct {
blocksize int64
filesize int64
bytechange int64
fs *fat32.FileSystem
err error
}{
{500, 6000, -1, nil, fmt.Errorf("blocksize for FAT32 must be")},
{513, 6000, -1, nil, fmt.Errorf("blocksize for FAT32 must be")},
{512, fat32.Fat32MaxSize + 10000, -1, nil, fmt.Errorf("requested size is larger than maximum allowed FAT32 size")},
{512, 0, -1, nil, fmt.Errorf("requested size is smaller than minimum allowed FAT32 size")},
{512, 10000000, 512, nil, fmt.Errorf("error reading FileSystem Information Sector")},
{512, 10000000, -1, &fat32.FileSystem{}, nil},
}
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
seed := [32]byte{}
chacha := rand.NewChaCha8(seed)
for _, t2 := range tests {
tt := t2
t.Run(fmt.Sprintf("blocksize %d filesize %d bytechange %d", tt.filesize, tt.blocksize, tt.bytechange), func(t *testing.T) {
// get a temporary working file
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
// make any changes needed to corrupt it
corrupted := ""
if tt.bytechange >= 0 {
b := make([]byte, 1)
_, _ = chacha.Read(b)
_, _ = f.WriteAt(b, tt.bytechange+pre)
corrupted = fmt.Sprintf("corrupted %d", tt.bytechange+pre)
}
// create the filesystem
fs, err := fat32.Read(f, tt.filesize-pre-post, pre, tt.blocksize)
switch {
case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
t.Errorf("read(%s, %d, %d, %d) %s: mismatched errors, actual %v expected %v", f.Name(), tt.filesize, 0, tt.blocksize, corrupted, err, tt.err)
case (fs == nil && tt.fs != nil) || (fs != nil && tt.fs == nil):
t.Errorf("read(%s, %d, %d, %d) %s: mismatched fs, actual then expected", f.Name(), tt.filesize, 0, tt.blocksize, corrupted)
t.Logf("%v", fs)
t.Logf("%v", tt.fs)
}
// we do not match the filesystems here, only check functional accuracy
})
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
}
func TestFat32ReadDir(t *testing.T) {
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
// get a temporary working file
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
// determine entries from the actual data
rootEntries, _, err := fat32.GetValidDirectoryEntries()
if err != nil {
t.Fatalf("error getting valid directory entries: %v", err)
}
// ignore volume entry when public-facing root entries
rootEntries = rootEntries[:len(rootEntries)-1]
fooEntries, _, err := fat32.GetValidDirectoryEntriesExtended("/foo")
if err != nil {
t.Fatalf("error getting valid directory entries for /foo: %v", err)
}
tests := []struct {
path string
count int
name string
isDir bool
err error
}{
{"/", len(rootEntries), "foo", true, nil},
{"/foo", len(fooEntries), ".", true, nil},
// 0 entries because the directory does not exist
{"/a/b/c", 0, "", false, fmt.Errorf("error reading directory /a/b/c")},
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Read(f, fileInfo.Size()-pre-post, pre, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
for _, tt := range tests {
output, err := fs.ReadDir(tt.path)
switch {
case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
t.Errorf("readDir(%s): mismatched errors, actual: %v , expected: %v", tt.path, err, tt.err)
case output == nil && tt.err == nil:
t.Errorf("readDir(%s): Unexpected nil output", tt.path)
case len(output) != tt.count:
t.Errorf("readDir(%s): output gave %d entries instead of expected %d", tt.path, len(output), tt.count)
case len(output) > 0 && output[0].IsDir() != tt.isDir:
t.Errorf("readDir(%s): output gave directory %t expected %t", tt.path, output[0].IsDir(), tt.isDir)
case len(output) > 0 && output[0].Name() != tt.name:
t.Errorf("readDir(%s): output gave name %s expected %s", tt.path, output[0].Name(), tt.name)
}
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
}
//nolint:gocyclo // we really do not care about the cyclomatic complexity of a test function. Maybe someday we will improve it.
func TestFat32OpenFile(t *testing.T) {
// opening directories and files for reading
t.Run("read", func(t *testing.T) {
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
// get a temporary working file
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
tests := []struct {
path string
mode int
expected string
err error
}{
// error opening a directory
{"/", os.O_RDONLY, "", fmt.Errorf("cannot open directory %s as file", "/")},
{"/", os.O_RDWR, "", fmt.Errorf("cannot open directory %s as file", "/")},
{"/", os.O_CREATE, "", fmt.Errorf("cannot open directory %s as file", "/")},
// open non-existent file for read or read write
{"/abcdefg", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
{"/abcdefg", os.O_RDWR, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
{"/abcdefg", os.O_APPEND, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
// open file for read or read write and check contents
{"/CORTO1.TXT", os.O_RDONLY, "Tenemos un archivo corto\n", nil},
{"/CORTO1.TXT", os.O_RDWR, "Tenemos un archivo corto\n", nil},
// open file for create that already exists
// {"/CORTO1.TXT", os.O_CREATE | os.O_RDWR, "Tenemos un archivo corto\n", nil},
// {"/CORTO1.TXT", os.O_CREATE | os.O_RDONLY, "Tenemos un archivo corto\n", nil},
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Read(f, fileInfo.Size()-pre-post, pre, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
for _, tt := range tests {
header := fmt.Sprintf("OpenFile(%s, %s)", tt.path, getOpenMode(tt.mode))
reader, err := fs.OpenFile(tt.path, tt.mode)
switch {
case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
t.Errorf("%s: mismatched errors, actual: %v , expected: %v", header, err, tt.err)
case reader == nil && (tt.err == nil || tt.expected != ""):
t.Errorf("%s: Unexpected nil output", header)
case reader != nil:
b, err := io.ReadAll(reader)
if err != nil {
t.Errorf("%s: io.ReadAll(reader) unexpected error: %v", header, err)
}
if string(b) != tt.expected {
t.Errorf("%s: mismatched contents, actual then expected", header)
t.Log(string(b))
t.Log(tt.expected)
}
}
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
})
// write / create-and-write files and check contents
// *** Write - writes right after last write or read
// *** Read - reads right after last write or read
// ** WriteAt - writes at specific location in file
// ** ReadAt - reads at specific location in file
t.Run("Write", func(t *testing.T) {
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
tests := []struct {
path string
mode int
beginning bool // true means "Seek() to beginning of file before writing"; false means "read entire file then write"
contents string
expected string
err error
}{
// - open for create file that does not exist (write contents, check that written)
{"/abcdefg", os.O_RDWR | os.O_CREATE, false, "This is a test", "This is a test", nil},
// - open for readwrite file that does exist (write contents, check that overwritten)
{"/CORTO1.TXT", os.O_RDWR, true, "This is a very long replacement string", "This is a very long replacement string", nil},
{"/CORTO1.TXT", os.O_RDWR, true, "Two", "Twoemos un archivo corto\n", nil},
{"/CORTO1.TXT", os.O_RDWR, false, "This is a very long replacement string", "Tenemos un archivo corto\nThis is a very long replacement string", nil},
{"/CORTO1.TXT", os.O_RDWR, false, "Two", "Tenemos un archivo corto\nTwo", nil},
// - open for append file that does exist (write contents, check that appended)
{"/CORTO1.TXT", os.O_APPEND, false, "More", "", fmt.Errorf("cannot write to file opened read-only")},
{"/CORTO1.TXT", os.O_APPEND | os.O_RDWR, false, "More", "Tenemos un archivo corto\nMore", nil},
{"/CORTO1.TXT", os.O_APPEND, true, "More", "", fmt.Errorf("cannot write to file opened read-only")},
{"/CORTO1.TXT", os.O_APPEND | os.O_RDWR, true, "More", "Moremos un archivo corto\n", nil},
}
for _, t2 := range tests {
tt := t2
t.Run(fmt.Sprintf("path %s mode %v beginning %v", tt.path, tt.mode, tt.beginning), func(t *testing.T) {
header := fmt.Sprintf("OpenFile(%s, %s, %t)", tt.path, getOpenMode(tt.mode), tt.beginning)
// get a temporary working file
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Read(f, fileInfo.Size()-pre-post, pre, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
readWriter, err := fs.OpenFile(tt.path, tt.mode)
switch {
case err != nil:
t.Errorf("%s: unexpected error: %v", header, err)
case readWriter == nil:
t.Errorf("%s: Unexpected nil output", header)
default:
// write and then read
bWrite := []byte(tt.contents)
if tt.beginning {
offset, err := readWriter.Seek(0, 0)
if err != nil {
t.Errorf("%s: Seek(0,0) unexpected error: %v", header, err)
return
}
if offset != 0 {
t.Errorf("%s: Seek(0,0) reset to %d instead of %d", header, offset, 0)
return
}
} else {
b := make([]byte, 512)
_, err := readWriter.Read(b)
if err != nil && err != io.EOF {
t.Errorf("%s: io.ReadAll(readWriter) unexpected error: %v", header, err)
return
}
}
written, writeErr := readWriter.Write(bWrite)
_, _ = readWriter.Seek(0, 0)
bRead, readErr := io.ReadAll(readWriter)
switch {
case readErr != nil:
t.Errorf("%s: io.ReadAll() unexpected error: %v", header, readErr)
case (writeErr == nil && tt.err != nil) || (writeErr != nil && tt.err == nil) || (writeErr != nil && tt.err != nil && !strings.HasPrefix(writeErr.Error(), tt.err.Error())):
t.Errorf("%s: readWriter.Write(b) mismatched errors, actual: %v , expected: %v", header, writeErr, tt.err)
case written != len(bWrite) && tt.err == nil:
t.Errorf("%s: readWriter.Write(b) wrote %d bytes instead of expected %d", header, written, len(bWrite))
case string(bRead) != tt.expected && tt.err == nil:
t.Errorf("%s: mismatched contents, actual then expected", header)
t.Log(string(bRead))
t.Log(tt.expected)
}
}
})
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
})
// write many files to exceed the first cluster, then read back
t.Run("Write Many", func(t *testing.T) {
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
f, err := tmpFat32(false, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Create(f, fileInfo.Size()-pre-post, pre, 512, " NO NAME")
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
pathPrefix := "/f"
fileCount := 32
for fileNumber := 1; fileNumber <= fileCount; fileNumber++ {
fileName := fmt.Sprintf("%s%d", pathPrefix, fileNumber)
fileContent := []byte(fileName)
readWriter, err := fs.OpenFile(fileName, os.O_RDWR|os.O_CREATE)
switch {
case err != nil:
t.Errorf("write many: unexpected error writing %s: %v", fileName, err)
case readWriter == nil:
t.Errorf("write many: unexpected nil output writing %s", fileName)
default:
_, _ = readWriter.Seek(0, 0)
written, writeErr := readWriter.Write(fileContent)
_, _ = readWriter.Seek(0, 0)
readFileContent, readErr := io.ReadAll(readWriter)
switch {
case readErr != nil:
t.Errorf("write many: io.ReadAll() unexpected error on %s: %v", fileName, readErr)
case writeErr != nil:
t.Errorf("write many: readWriter.Write(b) error on %s: %v", fileName, writeErr)
case written != len(fileContent):
t.Errorf("write many: readWriter.Write(b) wrote %d bytes instead of expected %d on %s", written, len(fileContent), fileName)
case string(readFileContent) != fileName:
t.Errorf("write many: mismatched contents on %s, expected: %s, got: %s", fileName, fileName, string(readFileContent))
}
}
}
dir, err := fs.ReadDir("/")
if err != nil {
t.Errorf("write many: error reading /: %v", err)
}
if len(dir) != fileCount {
t.Errorf("write many: entry count mismatch on /: expected %d, got %d -- %v", fileCount, len(dir), dir)
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
})
// large file should cross multiple clusters
// out cluster size is 512 bytes, so make it 10+ clusters
t.Run("Large File", func(t *testing.T) {
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
// get a temporary working file
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Read(f, fileInfo.Size()-pre-post, pre, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
path := "/abcdefghi"
mode := os.O_RDWR | os.O_CREATE
// each cluster is 512 bytes, so use 10 clusters and a bit of another
size := 10*512 + 22
bWrite := make([]byte, size)
header := fmt.Sprintf("OpenFile(%s, %s)", path, getOpenMode(mode))
readWriter, err := fs.OpenFile(path, mode)
seed := [32]byte{}
chacha := rand.NewChaCha8(seed)
switch {
case err != nil:
t.Errorf("%s: unexpected error: %v", header, err)
case readWriter == nil:
t.Errorf("%s: Unexpected nil output", header)
default:
// write and then read
_, _ = chacha.Read(bWrite)
written, writeErr := readWriter.Write(bWrite)
_, _ = readWriter.Seek(0, 0)
bRead, readErr := io.ReadAll(readWriter)
switch {
case readErr != nil:
t.Errorf("%s: io.ReadAll() unexpected error: %v", header, readErr)
case writeErr != nil:
t.Errorf("%s: readWriter.Write(b) unexpected error: %v", header, writeErr)
case written != len(bWrite):
t.Errorf("%s: readWriter.Write(b) wrote %d bytes instead of expected %d", header, written, len(bWrite))
case !bytes.Equal(bWrite, bRead):
t.Errorf("%s: mismatched contents, read %d expected %d, actual data then expected:", header, len(bRead), len(bWrite))
}
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
})
// large file should cross multiple clusters
// out cluster size is 512 bytes, so make it 10+ clusters
t.Run("Truncate File", func(t *testing.T) {
// get a temporary working file
f, err := tmpFat32(true, 0, 0)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Read(f, fileInfo.Size(), 0, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
p := "/abcdefghi"
mode := os.O_RDWR | os.O_CREATE
// each cluster is 512 bytes, so use 10 clusters and a bit of another
size := 10*512 + 22
bWrite := make([]byte, size)
header := fmt.Sprintf("OpenFile(%s, %s)", p, getOpenMode(mode))
readWriter, err := fs.OpenFile(p, mode)
seed := [32]byte{}
chacha := rand.NewChaCha8(seed)
switch {
case err != nil:
t.Fatalf("%s: unexpected error: %v", header, err)
case readWriter == nil:
t.Fatalf("%s: Unexpected nil output", header)
default:
// write and then read
_, _ = chacha.Read(bWrite)
written, writeErr := readWriter.Write(bWrite)
_, _ = readWriter.Seek(0, 0)
switch {
case writeErr != nil:
t.Fatalf("%s: readWriter.Write(b) unexpected error: %v", header, writeErr)
case written != len(bWrite):
t.Fatalf("%s: readWriter.Write(b) wrote %d bytes instead of expected %d", header, written, len(bWrite))
}
}
// we now have written lots of data to the file. Close it, then reopen it to truncate
if err := readWriter.Close(); err != nil {
t.Fatalf("error closing file: %v", err)
}
// and open to truncate
mode = os.O_RDWR | os.O_TRUNC
readWriter, err = fs.OpenFile(p, mode)
if err != nil {
t.Fatalf("could not reopen file: %v", err)
}
// read the data
bRead, readErr := io.ReadAll(readWriter)
switch {
case readErr != nil:
t.Fatalf("%s: io.ReadAll() unexpected error: %v", header, readErr)
case len(bRead) != 0:
t.Fatalf("%s: readWriter.ReadAll(b) read %d bytes after truncate instead of expected %d", header, len(bRead), 0)
}
})
// large files are often written in multiple passes
t.Run("Streaming Large File", func(t *testing.T) {
//nolint:thelper // this is not a helper function
runTest := func(t *testing.T, pre, post int64) {
// get a temporary working file
f, err := tmpFat32(true, pre, post)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
fs, err := fat32.Read(f, fileInfo.Size()-pre-post, pre, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
path := "/abcdefghi"
mode := os.O_RDWR | os.O_CREATE
// each cluster is 512 bytes, so use 10 clusters and a bit of another
size := 10*512 + 22
bWrite := make([]byte, size)
header := fmt.Sprintf("OpenFile(%s, %s)", path, getOpenMode(mode))
readWriter, err := fs.OpenFile(path, mode)
switch {
case err != nil:
t.Errorf("%s: unexpected error: %v", header, err)
case readWriter == nil:
t.Errorf("%s: Unexpected nil output", header)
default:
// success
}
seed := [32]byte{}
chacha := rand.NewChaCha8(seed)
_, _ = chacha.Read(bWrite)
writeSizes := []int{512, 1024, 256}
low := 0
for i := 0; low < len(bWrite); i++ {
high := low + writeSizes[i%len(writeSizes)]
if high > len(bWrite) {
high = len(bWrite)
}
written, err := readWriter.Write(bWrite[low:high])
if err != nil {
t.Errorf("%s: readWriter.Write(b) unexpected error: %v", header, err)
}
if written != high-low {
t.Errorf("%s: readWriter.Write(b) wrote %d bytes instead of expected %d", header, written, high-low)
}
low = high
}
_, _ = readWriter.Seek(0, 0)
bRead, readErr := io.ReadAll(readWriter)
switch {
case readErr != nil:
t.Errorf("%s: io.ReadAll() unexpected error: %v", header, readErr)
case !bytes.Equal(bWrite, bRead):
t.Errorf("%s: mismatched contents, read %d expected %d, actual data then expected:", header, len(bRead), len(bWrite))
}
}
t.Run("entire image", func(t *testing.T) {
runTest(t, 0, 0)
})
t.Run("embedded filesystem", func(t *testing.T) {
runTest(t, 500, 1000)
})
})
}
func TestFat32Label(t *testing.T) {
t.Run("read-label", func(t *testing.T) {
// get a mock filesystem image
f, err := tmpFat32(true, 0, 0)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
// read the filesystem
fs, err := fat32.Read(f, fileInfo.Size(), 0, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
// validate the label
label := fs.Label()
if label != "go-diskfs" {
t.Errorf("Unexpected label '%s', expected '%s'", label, "go-diskfs")
}
})
t.Run("create-label", func(t *testing.T) {
// get a mock filesystem image
f, err := tmpFat32(false, 0, 0)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
// create an empty filesystem
fs, err := fat32.Create(f, fileInfo.Size(), 0, 512, "go-diskfs")
if err != nil {
t.Fatalf("error creating fat32 filesystem: %v", err)
}
// read the label back
label := fs.Label()
if label != "go-diskfs" {
t.Errorf("Unexpected label '%s', expected '%s'", label, "go-diskfs")
}
// re-open the filesystem
if err := f.Close(); err != nil {
t.Fatalf("error closing file %s: %v", f.Name(), err)
}
f, err = os.Open(f.Name())
if err != nil {
t.Fatalf("error re-opening file %s: %v", f.Name(), err)
}
// read the filesystem
fs, err = fat32.Read(f, fileInfo.Size(), 0, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
// read-back the label
label = fs.Label()
if label != "go-diskfs" {
t.Errorf("Unexpected label '%s', expected '%s'", label, "go-diskfs")
}
})
t.Run("write-label", func(t *testing.T) {
// get a mock filesystem image
f, err := tmpFat32(false, 0, 0)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())
} else {
fmt.Println(f.Name())
}
fileInfo, err := f.Stat()
if err != nil {
t.Fatalf("error getting file info for tmpfile %s: %v", f.Name(), err)
}
// create an empty filesystem
fs, err := fat32.Create(f, fileInfo.Size(), 0, 512, "go-diskfs")
if err != nil {
t.Fatalf("error creating fat32 filesystem: %v", err)
}
// set the label
err = fs.SetLabel("Other Label")
if err != nil {
t.Fatalf("error setting label: %v", err)
}
// read the label back
label := fs.Label()
if label != "Other Label" {
t.Errorf("Unexpected label '%s', expected '%s'", label, "Other Label")
}
// re-open the filesystem
if err := f.Close(); err != nil {
t.Fatalf("error closing file %s: %v", f.Name(), err)
}
f, err = os.Open(f.Name())
if err != nil {
t.Fatalf("error re-opening file %s: %v", f.Name(), err)
}
// read the filesystem
fs, err = fat32.Read(f, fileInfo.Size(), 0, 512)
if err != nil {
t.Fatalf("error reading fat32 filesystem from %s: %v", f.Name(), err)
}
// read-back the label
label = fs.Label()
if label != "Other Label" {
t.Errorf("Unexpected label '%s', expected '%s'", label, "Other Label")
}
})
}
func TestFat32MkdirCases(t *testing.T) {
f, err := tmpFat32(false, 0, 0)
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
fs, err := fat32.Create(f, 1048576, 0, 512, "")
if err != nil {
t.Error(err.Error())
}
err = fs.Mkdir("/EFI/BOOT")
if err != nil {
t.Error(err.Error())
}
// Make the same folders but now lowercase ... I expect it not to create anything new,
// these folders exist but are named /EFI/BOOT
err = fs.Mkdir("/efi/boot")
if err != nil {
t.Error(err.Error())
}
files, err := fs.ReadDir("/")
if err != nil {
t.Error(err.Error())
}
if len(files) != 1 {
for _, file := range files {
fmt.Printf("file: %s\n", file.Name())
}
t.Fatalf("expected 1 file, found %d", len(files))
}
}
func Test83Lowercase(t *testing.T) {
// get a temporary working file
f, err := tmpFat32(true, 0, 0)
if err != nil {
t.Fatal(err)
}
if keepTmpFiles == "" {
defer os.Remove(f.Name())