Source file
src/os/os_test.go
1
2
3
4
5 package os_test
6
7 import (
8 "bytes"
9 "errors"
10 "flag"
11 "fmt"
12 "internal/testenv"
13 "io"
14 "io/fs"
15 "os"
16 . "os"
17 osexec "os/exec"
18 "path/filepath"
19 "reflect"
20 "runtime"
21 "runtime/debug"
22 "sort"
23 "strings"
24 "sync"
25 "syscall"
26 "testing"
27 "testing/fstest"
28 "time"
29 )
30
31 func TestMain(m *testing.M) {
32 if Getenv("GO_OS_TEST_DRAIN_STDIN") == "1" {
33 os.Stdout.Close()
34 io.Copy(io.Discard, os.Stdin)
35 Exit(0)
36 }
37
38 Exit(m.Run())
39 }
40
41 var dot = []string{
42 "dir_unix.go",
43 "env.go",
44 "error.go",
45 "file.go",
46 "os_test.go",
47 "types.go",
48 "stat_darwin.go",
49 "stat_linux.go",
50 }
51
52 type sysDir struct {
53 name string
54 files []string
55 }
56
57 var sysdir = func() *sysDir {
58 switch runtime.GOOS {
59 case "android":
60 return &sysDir{
61 "/system/lib",
62 []string{
63 "libmedia.so",
64 "libpowermanager.so",
65 },
66 }
67 case "ios":
68 wd, err := syscall.Getwd()
69 if err != nil {
70 wd = err.Error()
71 }
72 sd := &sysDir{
73 filepath.Join(wd, "..", ".."),
74 []string{
75 "ResourceRules.plist",
76 "Info.plist",
77 },
78 }
79 found := true
80 for _, f := range sd.files {
81 path := filepath.Join(sd.name, f)
82 if _, err := Stat(path); err != nil {
83 found = false
84 break
85 }
86 }
87 if found {
88 return sd
89 }
90
91
92 case "windows":
93 return &sysDir{
94 Getenv("SystemRoot") + "\\system32\\drivers\\etc",
95 []string{
96 "networks",
97 "protocol",
98 "services",
99 },
100 }
101 case "plan9":
102 return &sysDir{
103 "/lib/ndb",
104 []string{
105 "common",
106 "local",
107 },
108 }
109 }
110 return &sysDir{
111 "/etc",
112 []string{
113 "group",
114 "hosts",
115 "passwd",
116 },
117 }
118 }()
119
120 func size(name string, t *testing.T) int64 {
121 file, err := Open(name)
122 if err != nil {
123 t.Fatal("open failed:", err)
124 }
125 defer func() {
126 if err := file.Close(); err != nil {
127 t.Error(err)
128 }
129 }()
130 n, err := io.Copy(io.Discard, file)
131 if err != nil {
132 t.Fatal(err)
133 }
134 return n
135 }
136
137 func equal(name1, name2 string) (r bool) {
138 switch runtime.GOOS {
139 case "windows":
140 r = strings.ToLower(name1) == strings.ToLower(name2)
141 default:
142 r = name1 == name2
143 }
144 return
145 }
146
147
148 func localTmp() string {
149 switch runtime.GOOS {
150 case "android", "ios", "windows":
151 return TempDir()
152 }
153 return "/tmp"
154 }
155
156 func newFile(testName string, t *testing.T) (f *File) {
157 f, err := os.CreateTemp(localTmp(), "_Go_"+testName)
158 if err != nil {
159 t.Fatalf("TempFile %s: %s", testName, err)
160 }
161 return
162 }
163
164 func newDir(testName string, t *testing.T) (name string) {
165 name, err := os.MkdirTemp(localTmp(), "_Go_"+testName)
166 if err != nil {
167 t.Fatalf("TempDir %s: %s", testName, err)
168 }
169 return
170 }
171
172 var sfdir = sysdir.name
173 var sfname = sysdir.files[0]
174
175 func TestStat(t *testing.T) {
176 path := sfdir + "/" + sfname
177 dir, err := Stat(path)
178 if err != nil {
179 t.Fatal("stat failed:", err)
180 }
181 if !equal(sfname, dir.Name()) {
182 t.Error("name should be ", sfname, "; is", dir.Name())
183 }
184 filesize := size(path, t)
185 if dir.Size() != filesize {
186 t.Error("size should be", filesize, "; is", dir.Size())
187 }
188 }
189
190 func TestStatError(t *testing.T) {
191 defer chtmpdir(t)()
192
193 path := "no-such-file"
194
195 fi, err := Stat(path)
196 if err == nil {
197 t.Fatal("got nil, want error")
198 }
199 if fi != nil {
200 t.Errorf("got %v, want nil", fi)
201 }
202 if perr, ok := err.(*PathError); !ok {
203 t.Errorf("got %T, want %T", err, perr)
204 }
205
206 testenv.MustHaveSymlink(t)
207
208 link := "symlink"
209 err = Symlink(path, link)
210 if err != nil {
211 t.Fatal(err)
212 }
213
214 fi, err = Stat(link)
215 if err == nil {
216 t.Fatal("got nil, want error")
217 }
218 if fi != nil {
219 t.Errorf("got %v, want nil", fi)
220 }
221 if perr, ok := err.(*PathError); !ok {
222 t.Errorf("got %T, want %T", err, perr)
223 }
224 }
225
226 func TestFstat(t *testing.T) {
227 path := sfdir + "/" + sfname
228 file, err1 := Open(path)
229 if err1 != nil {
230 t.Fatal("open failed:", err1)
231 }
232 defer file.Close()
233 dir, err2 := file.Stat()
234 if err2 != nil {
235 t.Fatal("fstat failed:", err2)
236 }
237 if !equal(sfname, dir.Name()) {
238 t.Error("name should be ", sfname, "; is", dir.Name())
239 }
240 filesize := size(path, t)
241 if dir.Size() != filesize {
242 t.Error("size should be", filesize, "; is", dir.Size())
243 }
244 }
245
246 func TestLstat(t *testing.T) {
247 path := sfdir + "/" + sfname
248 dir, err := Lstat(path)
249 if err != nil {
250 t.Fatal("lstat failed:", err)
251 }
252 if !equal(sfname, dir.Name()) {
253 t.Error("name should be ", sfname, "; is", dir.Name())
254 }
255 filesize := size(path, t)
256 if dir.Size() != filesize {
257 t.Error("size should be", filesize, "; is", dir.Size())
258 }
259 }
260
261
262 func TestRead0(t *testing.T) {
263 path := sfdir + "/" + sfname
264 f, err := Open(path)
265 if err != nil {
266 t.Fatal("open failed:", err)
267 }
268 defer f.Close()
269
270 b := make([]byte, 0)
271 n, err := f.Read(b)
272 if n != 0 || err != nil {
273 t.Errorf("Read(0) = %d, %v, want 0, nil", n, err)
274 }
275 b = make([]byte, 100)
276 n, err = f.Read(b)
277 if n <= 0 || err != nil {
278 t.Errorf("Read(100) = %d, %v, want >0, nil", n, err)
279 }
280 }
281
282
283 func TestReadClosed(t *testing.T) {
284 path := sfdir + "/" + sfname
285 file, err := Open(path)
286 if err != nil {
287 t.Fatal("open failed:", err)
288 }
289 file.Close()
290
291 b := make([]byte, 100)
292 _, err = file.Read(b)
293
294 e, ok := err.(*PathError)
295 if !ok {
296 t.Fatalf("Read: %T(%v), want PathError", e, e)
297 }
298
299 if e.Err != ErrClosed {
300 t.Errorf("Read: %v, want PathError(ErrClosed)", e)
301 }
302 }
303
304 func testReaddirnames(dir string, contents []string, t *testing.T) {
305 file, err := Open(dir)
306 if err != nil {
307 t.Fatalf("open %q failed: %v", dir, err)
308 }
309 defer file.Close()
310 s, err2 := file.Readdirnames(-1)
311 if err2 != nil {
312 t.Fatalf("Readdirnames %q failed: %v", dir, err2)
313 }
314 for _, m := range contents {
315 found := false
316 for _, n := range s {
317 if n == "." || n == ".." {
318 t.Errorf("got %q in directory", n)
319 }
320 if !equal(m, n) {
321 continue
322 }
323 if found {
324 t.Error("present twice:", m)
325 }
326 found = true
327 }
328 if !found {
329 t.Error("could not find", m)
330 }
331 }
332 if s == nil {
333 t.Error("Readdirnames returned nil instead of empty slice")
334 }
335 }
336
337 func testReaddir(dir string, contents []string, t *testing.T) {
338 file, err := Open(dir)
339 if err != nil {
340 t.Fatalf("open %q failed: %v", dir, err)
341 }
342 defer file.Close()
343 s, err2 := file.Readdir(-1)
344 if err2 != nil {
345 t.Fatalf("Readdir %q failed: %v", dir, err2)
346 }
347 for _, m := range contents {
348 found := false
349 for _, n := range s {
350 if n.Name() == "." || n.Name() == ".." {
351 t.Errorf("got %q in directory", n.Name())
352 }
353 if !equal(m, n.Name()) {
354 continue
355 }
356 if found {
357 t.Error("present twice:", m)
358 }
359 found = true
360 }
361 if !found {
362 t.Error("could not find", m)
363 }
364 }
365 if s == nil {
366 t.Error("Readdir returned nil instead of empty slice")
367 }
368 }
369
370 func testReadDir(dir string, contents []string, t *testing.T) {
371 file, err := Open(dir)
372 if err != nil {
373 t.Fatalf("open %q failed: %v", dir, err)
374 }
375 defer file.Close()
376 s, err2 := file.ReadDir(-1)
377 if err2 != nil {
378 t.Fatalf("ReadDir %q failed: %v", dir, err2)
379 }
380 for _, m := range contents {
381 found := false
382 for _, n := range s {
383 if n.Name() == "." || n.Name() == ".." {
384 t.Errorf("got %q in directory", n)
385 }
386 if !equal(m, n.Name()) {
387 continue
388 }
389 if found {
390 t.Error("present twice:", m)
391 }
392 found = true
393 lstat, err := Lstat(dir + "/" + m)
394 if err != nil {
395 t.Fatal(err)
396 }
397 if n.IsDir() != lstat.IsDir() {
398 t.Errorf("%s: IsDir=%v, want %v", m, n.IsDir(), lstat.IsDir())
399 }
400 if n.Type() != lstat.Mode().Type() {
401 t.Errorf("%s: IsDir=%v, want %v", m, n.Type(), lstat.Mode().Type())
402 }
403 info, err := n.Info()
404 if err != nil {
405 t.Errorf("%s: Info: %v", m, err)
406 continue
407 }
408 if !SameFile(info, lstat) {
409 t.Errorf("%s: Info: SameFile(info, lstat) = false", m)
410 }
411 }
412 if !found {
413 t.Error("could not find", m)
414 }
415 }
416 if s == nil {
417 t.Error("ReadDir returned nil instead of empty slice")
418 }
419 }
420
421 func TestFileReaddirnames(t *testing.T) {
422 testReaddirnames(".", dot, t)
423 testReaddirnames(sysdir.name, sysdir.files, t)
424 testReaddirnames(t.TempDir(), nil, t)
425 }
426
427 func TestFileReaddir(t *testing.T) {
428 testReaddir(".", dot, t)
429 testReaddir(sysdir.name, sysdir.files, t)
430 testReaddir(t.TempDir(), nil, t)
431 }
432
433 func TestFileReadDir(t *testing.T) {
434 testReadDir(".", dot, t)
435 testReadDir(sysdir.name, sysdir.files, t)
436 testReadDir(t.TempDir(), nil, t)
437 }
438
439 func benchmarkReaddirname(path string, b *testing.B) {
440 var nentries int
441 for i := 0; i < b.N; i++ {
442 f, err := Open(path)
443 if err != nil {
444 b.Fatalf("open %q failed: %v", path, err)
445 }
446 ns, err := f.Readdirnames(-1)
447 f.Close()
448 if err != nil {
449 b.Fatalf("readdirnames %q failed: %v", path, err)
450 }
451 nentries = len(ns)
452 }
453 b.Logf("benchmarkReaddirname %q: %d entries", path, nentries)
454 }
455
456 func benchmarkReaddir(path string, b *testing.B) {
457 var nentries int
458 for i := 0; i < b.N; i++ {
459 f, err := Open(path)
460 if err != nil {
461 b.Fatalf("open %q failed: %v", path, err)
462 }
463 fs, err := f.Readdir(-1)
464 f.Close()
465 if err != nil {
466 b.Fatalf("readdir %q failed: %v", path, err)
467 }
468 nentries = len(fs)
469 }
470 b.Logf("benchmarkReaddir %q: %d entries", path, nentries)
471 }
472
473 func benchmarkReadDir(path string, b *testing.B) {
474 var nentries int
475 for i := 0; i < b.N; i++ {
476 f, err := Open(path)
477 if err != nil {
478 b.Fatalf("open %q failed: %v", path, err)
479 }
480 fs, err := f.ReadDir(-1)
481 f.Close()
482 if err != nil {
483 b.Fatalf("readdir %q failed: %v", path, err)
484 }
485 nentries = len(fs)
486 }
487 b.Logf("benchmarkReadDir %q: %d entries", path, nentries)
488 }
489
490 func BenchmarkReaddirname(b *testing.B) {
491 benchmarkReaddirname(".", b)
492 }
493
494 func BenchmarkReaddir(b *testing.B) {
495 benchmarkReaddir(".", b)
496 }
497
498 func BenchmarkReadDir(b *testing.B) {
499 benchmarkReadDir(".", b)
500 }
501
502 func benchmarkStat(b *testing.B, path string) {
503 b.ResetTimer()
504 for i := 0; i < b.N; i++ {
505 _, err := Stat(path)
506 if err != nil {
507 b.Fatalf("Stat(%q) failed: %v", path, err)
508 }
509 }
510 }
511
512 func benchmarkLstat(b *testing.B, path string) {
513 b.ResetTimer()
514 for i := 0; i < b.N; i++ {
515 _, err := Lstat(path)
516 if err != nil {
517 b.Fatalf("Lstat(%q) failed: %v", path, err)
518 }
519 }
520 }
521
522 func BenchmarkStatDot(b *testing.B) {
523 benchmarkStat(b, ".")
524 }
525
526 func BenchmarkStatFile(b *testing.B) {
527 benchmarkStat(b, filepath.Join(runtime.GOROOT(), "src/os/os_test.go"))
528 }
529
530 func BenchmarkStatDir(b *testing.B) {
531 benchmarkStat(b, filepath.Join(runtime.GOROOT(), "src/os"))
532 }
533
534 func BenchmarkLstatDot(b *testing.B) {
535 benchmarkLstat(b, ".")
536 }
537
538 func BenchmarkLstatFile(b *testing.B) {
539 benchmarkLstat(b, filepath.Join(runtime.GOROOT(), "src/os/os_test.go"))
540 }
541
542 func BenchmarkLstatDir(b *testing.B) {
543 benchmarkLstat(b, filepath.Join(runtime.GOROOT(), "src/os"))
544 }
545
546
547 func smallReaddirnames(file *File, length int, t *testing.T) []string {
548 names := make([]string, length)
549 count := 0
550 for {
551 d, err := file.Readdirnames(1)
552 if err == io.EOF {
553 break
554 }
555 if err != nil {
556 t.Fatalf("readdirnames %q failed: %v", file.Name(), err)
557 }
558 if len(d) == 0 {
559 t.Fatalf("readdirnames %q returned empty slice and no error", file.Name())
560 }
561 names[count] = d[0]
562 count++
563 }
564 return names[0:count]
565 }
566
567
568
569 func TestReaddirnamesOneAtATime(t *testing.T) {
570
571 dir := "/usr/bin"
572 switch runtime.GOOS {
573 case "android":
574 dir = "/system/bin"
575 case "ios":
576 wd, err := Getwd()
577 if err != nil {
578 t.Fatal(err)
579 }
580 dir = wd
581 case "plan9":
582 dir = "/bin"
583 case "windows":
584 dir = Getenv("SystemRoot") + "\\system32"
585 }
586 file, err := Open(dir)
587 if err != nil {
588 t.Fatalf("open %q failed: %v", dir, err)
589 }
590 defer file.Close()
591 all, err1 := file.Readdirnames(-1)
592 if err1 != nil {
593 t.Fatalf("readdirnames %q failed: %v", dir, err1)
594 }
595 file1, err2 := Open(dir)
596 if err2 != nil {
597 t.Fatalf("open %q failed: %v", dir, err2)
598 }
599 defer file1.Close()
600 small := smallReaddirnames(file1, len(all)+100, t)
601 if len(small) < len(all) {
602 t.Fatalf("len(small) is %d, less than %d", len(small), len(all))
603 }
604 for i, n := range all {
605 if small[i] != n {
606 t.Errorf("small read %q mismatch: %v", small[i], n)
607 }
608 }
609 }
610
611 func TestReaddirNValues(t *testing.T) {
612 if testing.Short() {
613 t.Skip("test.short; skipping")
614 }
615 dir := t.TempDir()
616 for i := 1; i <= 105; i++ {
617 f, err := Create(filepath.Join(dir, fmt.Sprintf("%d", i)))
618 if err != nil {
619 t.Fatalf("Create: %v", err)
620 }
621 f.Write([]byte(strings.Repeat("X", i)))
622 f.Close()
623 }
624
625 var d *File
626 openDir := func() {
627 var err error
628 d, err = Open(dir)
629 if err != nil {
630 t.Fatalf("Open directory: %v", err)
631 }
632 }
633
634 readdirExpect := func(n, want int, wantErr error) {
635 t.Helper()
636 fi, err := d.Readdir(n)
637 if err != wantErr {
638 t.Fatalf("Readdir of %d got error %v, want %v", n, err, wantErr)
639 }
640 if g, e := len(fi), want; g != e {
641 t.Errorf("Readdir of %d got %d files, want %d", n, g, e)
642 }
643 }
644
645 readDirExpect := func(n, want int, wantErr error) {
646 t.Helper()
647 de, err := d.ReadDir(n)
648 if err != wantErr {
649 t.Fatalf("ReadDir of %d got error %v, want %v", n, err, wantErr)
650 }
651 if g, e := len(de), want; g != e {
652 t.Errorf("ReadDir of %d got %d files, want %d", n, g, e)
653 }
654 }
655
656 readdirnamesExpect := func(n, want int, wantErr error) {
657 t.Helper()
658 fi, err := d.Readdirnames(n)
659 if err != wantErr {
660 t.Fatalf("Readdirnames of %d got error %v, want %v", n, err, wantErr)
661 }
662 if g, e := len(fi), want; g != e {
663 t.Errorf("Readdirnames of %d got %d files, want %d", n, g, e)
664 }
665 }
666
667 for _, fn := range []func(int, int, error){readdirExpect, readdirnamesExpect, readDirExpect} {
668
669 openDir()
670 fn(0, 105, nil)
671 fn(0, 0, nil)
672 d.Close()
673
674
675 openDir()
676 fn(-1, 105, nil)
677 fn(-2, 0, nil)
678 fn(0, 0, nil)
679 d.Close()
680
681
682 openDir()
683 fn(1, 1, nil)
684 fn(2, 2, nil)
685 fn(105, 102, nil)
686 fn(3, 0, io.EOF)
687 d.Close()
688 }
689 }
690
691 func touch(t *testing.T, name string) {
692 f, err := Create(name)
693 if err != nil {
694 t.Fatal(err)
695 }
696 if err := f.Close(); err != nil {
697 t.Fatal(err)
698 }
699 }
700
701 func TestReaddirStatFailures(t *testing.T) {
702 switch runtime.GOOS {
703 case "windows", "plan9":
704
705
706
707
708 t.Skipf("skipping test on %v", runtime.GOOS)
709 }
710 dir := t.TempDir()
711 touch(t, filepath.Join(dir, "good1"))
712 touch(t, filepath.Join(dir, "x"))
713 touch(t, filepath.Join(dir, "good2"))
714 defer func() {
715 *LstatP = Lstat
716 }()
717 var xerr error
718 *LstatP = func(path string) (FileInfo, error) {
719 if xerr != nil && strings.HasSuffix(path, "x") {
720 return nil, xerr
721 }
722 return Lstat(path)
723 }
724 readDir := func() ([]FileInfo, error) {
725 d, err := Open(dir)
726 if err != nil {
727 t.Fatal(err)
728 }
729 defer d.Close()
730 return d.Readdir(-1)
731 }
732 mustReadDir := func(testName string) []FileInfo {
733 fis, err := readDir()
734 if err != nil {
735 t.Fatalf("%s: Readdir: %v", testName, err)
736 }
737 return fis
738 }
739 names := func(fis []FileInfo) []string {
740 s := make([]string, len(fis))
741 for i, fi := range fis {
742 s[i] = fi.Name()
743 }
744 sort.Strings(s)
745 return s
746 }
747
748 if got, want := names(mustReadDir("initial readdir")),
749 []string{"good1", "good2", "x"}; !reflect.DeepEqual(got, want) {
750 t.Errorf("initial readdir got %q; want %q", got, want)
751 }
752
753 xerr = ErrNotExist
754 if got, want := names(mustReadDir("with x disappearing")),
755 []string{"good1", "good2"}; !reflect.DeepEqual(got, want) {
756 t.Errorf("with x disappearing, got %q; want %q", got, want)
757 }
758
759 xerr = errors.New("some real error")
760 if _, err := readDir(); err != xerr {
761 t.Errorf("with a non-ErrNotExist error, got error %v; want %v", err, xerr)
762 }
763 }
764
765
766 func TestReaddirOfFile(t *testing.T) {
767 f, err := os.CreateTemp("", "_Go_ReaddirOfFile")
768 if err != nil {
769 t.Fatal(err)
770 }
771 defer Remove(f.Name())
772 f.Write([]byte("foo"))
773 f.Close()
774 reg, err := Open(f.Name())
775 if err != nil {
776 t.Fatal(err)
777 }
778 defer reg.Close()
779
780 names, err := reg.Readdirnames(-1)
781 if err == nil {
782 t.Error("Readdirnames succeeded; want non-nil error")
783 }
784 var pe *PathError
785 if !errors.As(err, &pe) || pe.Path != f.Name() {
786 t.Errorf("Readdirnames returned %q; want a PathError with path %q", err, f.Name())
787 }
788 if len(names) > 0 {
789 t.Errorf("unexpected dir names in regular file: %q", names)
790 }
791 }
792
793 func TestHardLink(t *testing.T) {
794 testenv.MustHaveLink(t)
795
796 defer chtmpdir(t)()
797 from, to := "hardlinktestfrom", "hardlinktestto"
798 file, err := Create(to)
799 if err != nil {
800 t.Fatalf("open %q failed: %v", to, err)
801 }
802 if err = file.Close(); err != nil {
803 t.Errorf("close %q failed: %v", to, err)
804 }
805 err = Link(to, from)
806 if err != nil {
807 t.Fatalf("link %q, %q failed: %v", to, from, err)
808 }
809
810 none := "hardlinktestnone"
811 err = Link(none, none)
812
813 if lerr, ok := err.(*LinkError); !ok || lerr.Error() == "" {
814 t.Errorf("link %q, %q failed to return a valid error", none, none)
815 }
816
817 tostat, err := Stat(to)
818 if err != nil {
819 t.Fatalf("stat %q failed: %v", to, err)
820 }
821 fromstat, err := Stat(from)
822 if err != nil {
823 t.Fatalf("stat %q failed: %v", from, err)
824 }
825 if !SameFile(tostat, fromstat) {
826 t.Errorf("link %q, %q did not create hard link", to, from)
827 }
828
829 err = Link(to, from)
830 switch err := err.(type) {
831 case *LinkError:
832 if err.Op != "link" {
833 t.Errorf("Link(%q, %q) err.Op = %q; want %q", to, from, err.Op, "link")
834 }
835 if err.Old != to {
836 t.Errorf("Link(%q, %q) err.Old = %q; want %q", to, from, err.Old, to)
837 }
838 if err.New != from {
839 t.Errorf("Link(%q, %q) err.New = %q; want %q", to, from, err.New, from)
840 }
841 if !IsExist(err.Err) {
842 t.Errorf("Link(%q, %q) err.Err = %q; want %q", to, from, err.Err, "file exists error")
843 }
844 case nil:
845 t.Errorf("link %q, %q: expected error, got nil", from, to)
846 default:
847 t.Errorf("link %q, %q: expected %T, got %T %v", from, to, new(LinkError), err, err)
848 }
849 }
850
851
852
853 func chtmpdir(t *testing.T) func() {
854 oldwd, err := Getwd()
855 if err != nil {
856 t.Fatalf("chtmpdir: %v", err)
857 }
858 d, err := os.MkdirTemp("", "test")
859 if err != nil {
860 t.Fatalf("chtmpdir: %v", err)
861 }
862 if err := Chdir(d); err != nil {
863 t.Fatalf("chtmpdir: %v", err)
864 }
865 return func() {
866 if err := Chdir(oldwd); err != nil {
867 t.Fatalf("chtmpdir: %v", err)
868 }
869 RemoveAll(d)
870 }
871 }
872
873 func TestSymlink(t *testing.T) {
874 testenv.MustHaveSymlink(t)
875
876 defer chtmpdir(t)()
877 from, to := "symlinktestfrom", "symlinktestto"
878 file, err := Create(to)
879 if err != nil {
880 t.Fatalf("Create(%q) failed: %v", to, err)
881 }
882 if err = file.Close(); err != nil {
883 t.Errorf("Close(%q) failed: %v", to, err)
884 }
885 err = Symlink(to, from)
886 if err != nil {
887 t.Fatalf("Symlink(%q, %q) failed: %v", to, from, err)
888 }
889 tostat, err := Lstat(to)
890 if err != nil {
891 t.Fatalf("Lstat(%q) failed: %v", to, err)
892 }
893 if tostat.Mode()&ModeSymlink != 0 {
894 t.Fatalf("Lstat(%q).Mode()&ModeSymlink = %v, want 0", to, tostat.Mode()&ModeSymlink)
895 }
896 fromstat, err := Stat(from)
897 if err != nil {
898 t.Fatalf("Stat(%q) failed: %v", from, err)
899 }
900 if !SameFile(tostat, fromstat) {
901 t.Errorf("Symlink(%q, %q) did not create symlink", to, from)
902 }
903 fromstat, err = Lstat(from)
904 if err != nil {
905 t.Fatalf("Lstat(%q) failed: %v", from, err)
906 }
907 if fromstat.Mode()&ModeSymlink == 0 {
908 t.Fatalf("Lstat(%q).Mode()&ModeSymlink = 0, want %v", from, ModeSymlink)
909 }
910 fromstat, err = Stat(from)
911 if err != nil {
912 t.Fatalf("Stat(%q) failed: %v", from, err)
913 }
914 if fromstat.Name() != from {
915 t.Errorf("Stat(%q).Name() = %q, want %q", from, fromstat.Name(), from)
916 }
917 if fromstat.Mode()&ModeSymlink != 0 {
918 t.Fatalf("Stat(%q).Mode()&ModeSymlink = %v, want 0", from, fromstat.Mode()&ModeSymlink)
919 }
920 s, err := Readlink(from)
921 if err != nil {
922 t.Fatalf("Readlink(%q) failed: %v", from, err)
923 }
924 if s != to {
925 t.Fatalf("Readlink(%q) = %q, want %q", from, s, to)
926 }
927 file, err = Open(from)
928 if err != nil {
929 t.Fatalf("Open(%q) failed: %v", from, err)
930 }
931 file.Close()
932 }
933
934 func TestLongSymlink(t *testing.T) {
935 testenv.MustHaveSymlink(t)
936
937 defer chtmpdir(t)()
938 s := "0123456789abcdef"
939
940 s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s
941 from := "longsymlinktestfrom"
942 err := Symlink(s, from)
943 if err != nil {
944 t.Fatalf("symlink %q, %q failed: %v", s, from, err)
945 }
946 r, err := Readlink(from)
947 if err != nil {
948 t.Fatalf("readlink %q failed: %v", from, err)
949 }
950 if r != s {
951 t.Fatalf("after symlink %q != %q", r, s)
952 }
953 }
954
955 func TestRename(t *testing.T) {
956 defer chtmpdir(t)()
957 from, to := "renamefrom", "renameto"
958
959 file, err := Create(from)
960 if err != nil {
961 t.Fatalf("open %q failed: %v", from, err)
962 }
963 if err = file.Close(); err != nil {
964 t.Errorf("close %q failed: %v", from, err)
965 }
966 err = Rename(from, to)
967 if err != nil {
968 t.Fatalf("rename %q, %q failed: %v", to, from, err)
969 }
970 _, err = Stat(to)
971 if err != nil {
972 t.Errorf("stat %q failed: %v", to, err)
973 }
974 }
975
976 func TestRenameOverwriteDest(t *testing.T) {
977 defer chtmpdir(t)()
978 from, to := "renamefrom", "renameto"
979
980 toData := []byte("to")
981 fromData := []byte("from")
982
983 err := os.WriteFile(to, toData, 0777)
984 if err != nil {
985 t.Fatalf("write file %q failed: %v", to, err)
986 }
987
988 err = os.WriteFile(from, fromData, 0777)
989 if err != nil {
990 t.Fatalf("write file %q failed: %v", from, err)
991 }
992 err = Rename(from, to)
993 if err != nil {
994 t.Fatalf("rename %q, %q failed: %v", to, from, err)
995 }
996
997 _, err = Stat(from)
998 if err == nil {
999 t.Errorf("from file %q still exists", from)
1000 }
1001 if err != nil && !IsNotExist(err) {
1002 t.Fatalf("stat from: %v", err)
1003 }
1004 toFi, err := Stat(to)
1005 if err != nil {
1006 t.Fatalf("stat %q failed: %v", to, err)
1007 }
1008 if toFi.Size() != int64(len(fromData)) {
1009 t.Errorf(`"to" size = %d; want %d (old "from" size)`, toFi.Size(), len(fromData))
1010 }
1011 }
1012
1013 func TestRenameFailed(t *testing.T) {
1014 defer chtmpdir(t)()
1015 from, to := "renamefrom", "renameto"
1016
1017 err := Rename(from, to)
1018 switch err := err.(type) {
1019 case *LinkError:
1020 if err.Op != "rename" {
1021 t.Errorf("rename %q, %q: err.Op: want %q, got %q", from, to, "rename", err.Op)
1022 }
1023 if err.Old != from {
1024 t.Errorf("rename %q, %q: err.Old: want %q, got %q", from, to, from, err.Old)
1025 }
1026 if err.New != to {
1027 t.Errorf("rename %q, %q: err.New: want %q, got %q", from, to, to, err.New)
1028 }
1029 case nil:
1030 t.Errorf("rename %q, %q: expected error, got nil", from, to)
1031 default:
1032 t.Errorf("rename %q, %q: expected %T, got %T %v", from, to, new(LinkError), err, err)
1033 }
1034 }
1035
1036 func TestRenameNotExisting(t *testing.T) {
1037 defer chtmpdir(t)()
1038 from, to := "doesnt-exist", "dest"
1039
1040 Mkdir(to, 0777)
1041
1042 if err := Rename(from, to); !IsNotExist(err) {
1043 t.Errorf("Rename(%q, %q) = %v; want an IsNotExist error", from, to, err)
1044 }
1045 }
1046
1047 func TestRenameToDirFailed(t *testing.T) {
1048 defer chtmpdir(t)()
1049 from, to := "renamefrom", "renameto"
1050
1051 Mkdir(from, 0777)
1052 Mkdir(to, 0777)
1053
1054 err := Rename(from, to)
1055 switch err := err.(type) {
1056 case *LinkError:
1057 if err.Op != "rename" {
1058 t.Errorf("rename %q, %q: err.Op: want %q, got %q", from, to, "rename", err.Op)
1059 }
1060 if err.Old != from {
1061 t.Errorf("rename %q, %q: err.Old: want %q, got %q", from, to, from, err.Old)
1062 }
1063 if err.New != to {
1064 t.Errorf("rename %q, %q: err.New: want %q, got %q", from, to, to, err.New)
1065 }
1066 case nil:
1067 t.Errorf("rename %q, %q: expected error, got nil", from, to)
1068 default:
1069 t.Errorf("rename %q, %q: expected %T, got %T %v", from, to, new(LinkError), err, err)
1070 }
1071 }
1072
1073 func TestRenameCaseDifference(pt *testing.T) {
1074 from, to := "renameFROM", "RENAMEfrom"
1075 tests := []struct {
1076 name string
1077 create func() error
1078 }{
1079 {"dir", func() error {
1080 return Mkdir(from, 0777)
1081 }},
1082 {"file", func() error {
1083 fd, err := Create(from)
1084 if err != nil {
1085 return err
1086 }
1087 return fd.Close()
1088 }},
1089 }
1090
1091 for _, test := range tests {
1092 pt.Run(test.name, func(t *testing.T) {
1093 defer chtmpdir(t)()
1094
1095 if err := test.create(); err != nil {
1096 t.Fatalf("failed to create test file: %s", err)
1097 }
1098
1099 if _, err := Stat(to); err != nil {
1100
1101 if IsNotExist(err) {
1102 t.Skipf("case sensitive filesystem")
1103 }
1104 t.Fatalf("stat %q, got: %q", to, err)
1105 }
1106
1107 if err := Rename(from, to); err != nil {
1108 t.Fatalf("unexpected error when renaming from %q to %q: %s", from, to, err)
1109 }
1110
1111 fd, err := Open(".")
1112 if err != nil {
1113 t.Fatalf("Open .: %s", err)
1114 }
1115
1116
1117
1118 dirNames, err := fd.Readdirnames(-1)
1119 if err != nil {
1120 t.Fatalf("readdirnames: %s", err)
1121 }
1122
1123 if dirNamesLen := len(dirNames); dirNamesLen != 1 {
1124 t.Fatalf("unexpected dirNames len, got %q, want %q", dirNamesLen, 1)
1125 }
1126
1127 if dirNames[0] != to {
1128 t.Errorf("unexpected name, got %q, want %q", dirNames[0], to)
1129 }
1130 })
1131 }
1132 }
1133
1134 func exec(t *testing.T, dir, cmd string, args []string, expect string) {
1135 r, w, err := Pipe()
1136 if err != nil {
1137 t.Fatalf("Pipe: %v", err)
1138 }
1139 defer r.Close()
1140 attr := &ProcAttr{Dir: dir, Files: []*File{nil, w, Stderr}}
1141 p, err := StartProcess(cmd, args, attr)
1142 if err != nil {
1143 t.Fatalf("StartProcess: %v", err)
1144 }
1145 w.Close()
1146
1147 var b bytes.Buffer
1148 io.Copy(&b, r)
1149 output := b.String()
1150
1151 fi1, _ := Stat(strings.TrimSpace(output))
1152 fi2, _ := Stat(expect)
1153 if !SameFile(fi1, fi2) {
1154 t.Errorf("exec %q returned %q wanted %q",
1155 strings.Join(append([]string{cmd}, args...), " "), output, expect)
1156 }
1157 p.Wait()
1158 }
1159
1160 func TestStartProcess(t *testing.T) {
1161 testenv.MustHaveExec(t)
1162
1163 var dir, cmd string
1164 var args []string
1165 switch runtime.GOOS {
1166 case "android":
1167 t.Skip("android doesn't have /bin/pwd")
1168 case "windows":
1169 cmd = Getenv("COMSPEC")
1170 dir = Getenv("SystemRoot")
1171 args = []string{"/c", "cd"}
1172 default:
1173 var err error
1174 cmd, err = osexec.LookPath("pwd")
1175 if err != nil {
1176 t.Fatalf("Can't find pwd: %v", err)
1177 }
1178 dir = "/"
1179 args = []string{}
1180 t.Logf("Testing with %v", cmd)
1181 }
1182 cmddir, cmdbase := filepath.Split(cmd)
1183 args = append([]string{cmdbase}, args...)
1184
1185 exec(t, dir, cmd, args, dir)
1186
1187 exec(t, cmddir, cmdbase, args, cmddir)
1188 }
1189
1190 func checkMode(t *testing.T, path string, mode FileMode) {
1191 dir, err := Stat(path)
1192 if err != nil {
1193 t.Fatalf("Stat %q (looking for mode %#o): %s", path, mode, err)
1194 }
1195 if dir.Mode()&ModePerm != mode {
1196 t.Errorf("Stat %q: mode %#o want %#o", path, dir.Mode(), mode)
1197 }
1198 }
1199
1200 func TestChmod(t *testing.T) {
1201 f := newFile("TestChmod", t)
1202 defer Remove(f.Name())
1203 defer f.Close()
1204
1205
1206 fm := FileMode(0456)
1207 if runtime.GOOS == "windows" {
1208 fm = FileMode(0444)
1209 }
1210 if err := Chmod(f.Name(), fm); err != nil {
1211 t.Fatalf("chmod %s %#o: %s", f.Name(), fm, err)
1212 }
1213 checkMode(t, f.Name(), fm)
1214
1215 fm = FileMode(0123)
1216 if runtime.GOOS == "windows" {
1217 fm = FileMode(0666)
1218 }
1219 if err := f.Chmod(fm); err != nil {
1220 t.Fatalf("chmod %s %#o: %s", f.Name(), fm, err)
1221 }
1222 checkMode(t, f.Name(), fm)
1223 }
1224
1225 func checkSize(t *testing.T, f *File, size int64) {
1226 t.Helper()
1227 dir, err := f.Stat()
1228 if err != nil {
1229 t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err)
1230 }
1231 if dir.Size() != size {
1232 t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size(), size)
1233 }
1234 }
1235
1236 func TestFTruncate(t *testing.T) {
1237 f := newFile("TestFTruncate", t)
1238 defer Remove(f.Name())
1239 defer f.Close()
1240
1241 checkSize(t, f, 0)
1242 f.Write([]byte("hello, world\n"))
1243 checkSize(t, f, 13)
1244 f.Truncate(10)
1245 checkSize(t, f, 10)
1246 f.Truncate(1024)
1247 checkSize(t, f, 1024)
1248 f.Truncate(0)
1249 checkSize(t, f, 0)
1250 _, err := f.Write([]byte("surprise!"))
1251 if err == nil {
1252 checkSize(t, f, 13+9)
1253 }
1254 }
1255
1256 func TestTruncate(t *testing.T) {
1257 f := newFile("TestTruncate", t)
1258 defer Remove(f.Name())
1259 defer f.Close()
1260
1261 checkSize(t, f, 0)
1262 f.Write([]byte("hello, world\n"))
1263 checkSize(t, f, 13)
1264 Truncate(f.Name(), 10)
1265 checkSize(t, f, 10)
1266 Truncate(f.Name(), 1024)
1267 checkSize(t, f, 1024)
1268 Truncate(f.Name(), 0)
1269 checkSize(t, f, 0)
1270 _, err := f.Write([]byte("surprise!"))
1271 if err == nil {
1272 checkSize(t, f, 13+9)
1273 }
1274 }
1275
1276
1277
1278
1279
1280 func TestChtimes(t *testing.T) {
1281 f := newFile("TestChtimes", t)
1282 defer Remove(f.Name())
1283
1284 f.Write([]byte("hello, world\n"))
1285 f.Close()
1286
1287 testChtimes(t, f.Name())
1288 }
1289
1290
1291
1292
1293
1294 func TestChtimesDir(t *testing.T) {
1295 name := newDir("TestChtimes", t)
1296 defer RemoveAll(name)
1297
1298 testChtimes(t, name)
1299 }
1300
1301 func testChtimes(t *testing.T, name string) {
1302 st, err := Stat(name)
1303 if err != nil {
1304 t.Fatalf("Stat %s: %s", name, err)
1305 }
1306 preStat := st
1307
1308
1309 at := Atime(preStat)
1310 mt := preStat.ModTime()
1311 err = Chtimes(name, at.Add(-time.Second), mt.Add(-time.Second))
1312 if err != nil {
1313 t.Fatalf("Chtimes %s: %s", name, err)
1314 }
1315
1316 st, err = Stat(name)
1317 if err != nil {
1318 t.Fatalf("second Stat %s: %s", name, err)
1319 }
1320 postStat := st
1321
1322 pat := Atime(postStat)
1323 pmt := postStat.ModTime()
1324 if !pat.Before(at) {
1325 switch runtime.GOOS {
1326 case "plan9":
1327
1328
1329
1330
1331 case "netbsd":
1332 mounts, _ := os.ReadFile("/proc/mounts")
1333 if strings.Contains(string(mounts), "noatime") {
1334 t.Logf("AccessTime didn't go backwards, but see a filesystem mounted noatime; ignoring. Issue 19293.")
1335 } else {
1336 t.Logf("AccessTime didn't go backwards; was=%v, after=%v (Ignoring on NetBSD, assuming noatime, Issue 19293)", at, pat)
1337 }
1338 default:
1339 t.Errorf("AccessTime didn't go backwards; was=%v, after=%v", at, pat)
1340 }
1341 }
1342
1343 if !pmt.Before(mt) {
1344 t.Errorf("ModTime didn't go backwards; was=%v, after=%v", mt, pmt)
1345 }
1346 }
1347
1348 func TestFileChdir(t *testing.T) {
1349
1350 if runtime.GOOS == "windows" {
1351 return
1352 }
1353
1354 wd, err := Getwd()
1355 if err != nil {
1356 t.Fatalf("Getwd: %s", err)
1357 }
1358 defer Chdir(wd)
1359
1360 fd, err := Open(".")
1361 if err != nil {
1362 t.Fatalf("Open .: %s", err)
1363 }
1364 defer fd.Close()
1365
1366 if err := Chdir("/"); err != nil {
1367 t.Fatalf("Chdir /: %s", err)
1368 }
1369
1370 if err := fd.Chdir(); err != nil {
1371 t.Fatalf("fd.Chdir: %s", err)
1372 }
1373
1374 wdNew, err := Getwd()
1375 if err != nil {
1376 t.Fatalf("Getwd: %s", err)
1377 }
1378 if wdNew != wd {
1379 t.Fatalf("fd.Chdir failed, got %s, want %s", wdNew, wd)
1380 }
1381 }
1382
1383 func TestChdirAndGetwd(t *testing.T) {
1384
1385 if runtime.GOOS == "windows" {
1386 return
1387 }
1388 fd, err := Open(".")
1389 if err != nil {
1390 t.Fatalf("Open .: %s", err)
1391 }
1392
1393
1394 dirs := []string{"/", "/usr/bin", "/tmp"}
1395
1396 switch runtime.GOOS {
1397 case "android":
1398 dirs = []string{"/system/bin"}
1399 case "plan9":
1400 dirs = []string{"/", "/usr"}
1401 case "ios":
1402 dirs = nil
1403 for _, d := range []string{"d1", "d2"} {
1404 dir, err := os.MkdirTemp("", d)
1405 if err != nil {
1406 t.Fatalf("TempDir: %v", err)
1407 }
1408
1409 dir, err = filepath.EvalSymlinks(dir)
1410 if err != nil {
1411 t.Fatalf("EvalSymlinks: %v", err)
1412 }
1413 dirs = append(dirs, dir)
1414 }
1415 }
1416 oldwd := Getenv("PWD")
1417 for mode := 0; mode < 2; mode++ {
1418 for _, d := range dirs {
1419 if mode == 0 {
1420 err = Chdir(d)
1421 } else {
1422 fd1, err1 := Open(d)
1423 if err1 != nil {
1424 t.Errorf("Open %s: %s", d, err1)
1425 continue
1426 }
1427 err = fd1.Chdir()
1428 fd1.Close()
1429 }
1430 if d == "/tmp" {
1431 Setenv("PWD", "/tmp")
1432 }
1433 pwd, err1 := Getwd()
1434 Setenv("PWD", oldwd)
1435 err2 := fd.Chdir()
1436 if err2 != nil {
1437
1438
1439
1440 fmt.Fprintf(Stderr, "fchdir back to dot failed: %s\n", err2)
1441 Exit(1)
1442 }
1443 if err != nil {
1444 fd.Close()
1445 t.Fatalf("Chdir %s: %s", d, err)
1446 }
1447 if err1 != nil {
1448 fd.Close()
1449 t.Fatalf("Getwd in %s: %s", d, err1)
1450 }
1451 if pwd != d {
1452 fd.Close()
1453 t.Fatalf("Getwd returned %q want %q", pwd, d)
1454 }
1455 }
1456 }
1457 fd.Close()
1458 }
1459
1460
1461 func TestProgWideChdir(t *testing.T) {
1462 const N = 10
1463 const ErrPwd = "Error!"
1464 c := make(chan bool)
1465 cpwd := make(chan string, N)
1466 for i := 0; i < N; i++ {
1467 go func(i int) {
1468
1469
1470 if i%2 == 1 {
1471
1472
1473
1474
1475
1476 runtime.LockOSThread()
1477 }
1478 hasErr, closed := <-c
1479 if !closed && hasErr {
1480 cpwd <- ErrPwd
1481 return
1482 }
1483 pwd, err := Getwd()
1484 if err != nil {
1485 t.Errorf("Getwd on goroutine %d: %v", i, err)
1486 cpwd <- ErrPwd
1487 return
1488 }
1489 cpwd <- pwd
1490 }(i)
1491 }
1492 oldwd, err := Getwd()
1493 if err != nil {
1494 c <- true
1495 t.Fatalf("Getwd: %v", err)
1496 }
1497 d, err := os.MkdirTemp("", "test")
1498 if err != nil {
1499 c <- true
1500 t.Fatalf("TempDir: %v", err)
1501 }
1502 defer func() {
1503 if err := Chdir(oldwd); err != nil {
1504 t.Fatalf("Chdir: %v", err)
1505 }
1506 RemoveAll(d)
1507 }()
1508 if err := Chdir(d); err != nil {
1509 c <- true
1510 t.Fatalf("Chdir: %v", err)
1511 }
1512
1513
1514 d, err = Getwd()
1515 if err != nil {
1516 c <- true
1517 t.Fatalf("Getwd: %v", err)
1518 }
1519 close(c)
1520 for i := 0; i < N; i++ {
1521 pwd := <-cpwd
1522 if pwd == ErrPwd {
1523 t.FailNow()
1524 }
1525 if pwd != d {
1526 t.Errorf("Getwd returned %q; want %q", pwd, d)
1527 }
1528 }
1529 }
1530
1531 func TestSeek(t *testing.T) {
1532 f := newFile("TestSeek", t)
1533 defer Remove(f.Name())
1534 defer f.Close()
1535
1536 const data = "hello, world\n"
1537 io.WriteString(f, data)
1538
1539 type test struct {
1540 in int64
1541 whence int
1542 out int64
1543 }
1544 var tests = []test{
1545 {0, io.SeekCurrent, int64(len(data))},
1546 {0, io.SeekStart, 0},
1547 {5, io.SeekStart, 5},
1548 {0, io.SeekEnd, int64(len(data))},
1549 {0, io.SeekStart, 0},
1550 {-1, io.SeekEnd, int64(len(data)) - 1},
1551 {1 << 33, io.SeekStart, 1 << 33},
1552 {1 << 33, io.SeekEnd, 1<<33 + int64(len(data))},
1553
1554
1555 {1<<32 - 1, io.SeekStart, 1<<32 - 1},
1556 {0, io.SeekCurrent, 1<<32 - 1},
1557 {2<<32 - 1, io.SeekStart, 2<<32 - 1},
1558 {0, io.SeekCurrent, 2<<32 - 1},
1559 }
1560 for i, tt := range tests {
1561 off, err := f.Seek(tt.in, tt.whence)
1562 if off != tt.out || err != nil {
1563 if e, ok := err.(*PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 && runtime.GOOS == "linux" {
1564 mounts, _ := os.ReadFile("/proc/mounts")
1565 if strings.Contains(string(mounts), "reiserfs") {
1566
1567 t.Skipf("skipping test known to fail on reiserfs; https://golang.org/issue/91")
1568 }
1569 }
1570 t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out)
1571 }
1572 }
1573 }
1574
1575 func TestSeekError(t *testing.T) {
1576 switch runtime.GOOS {
1577 case "js", "plan9":
1578 t.Skipf("skipping test on %v", runtime.GOOS)
1579 }
1580
1581 r, w, err := Pipe()
1582 if err != nil {
1583 t.Fatal(err)
1584 }
1585 _, err = r.Seek(0, 0)
1586 if err == nil {
1587 t.Fatal("Seek on pipe should fail")
1588 }
1589 if perr, ok := err.(*PathError); !ok || perr.Err != syscall.ESPIPE {
1590 t.Errorf("Seek returned error %v, want &PathError{Err: syscall.ESPIPE}", err)
1591 }
1592 _, err = w.Seek(0, 0)
1593 if err == nil {
1594 t.Fatal("Seek on pipe should fail")
1595 }
1596 if perr, ok := err.(*PathError); !ok || perr.Err != syscall.ESPIPE {
1597 t.Errorf("Seek returned error %v, want &PathError{Err: syscall.ESPIPE}", err)
1598 }
1599 }
1600
1601 type openErrorTest struct {
1602 path string
1603 mode int
1604 error error
1605 }
1606
1607 var openErrorTests = []openErrorTest{
1608 {
1609 sfdir + "/no-such-file",
1610 O_RDONLY,
1611 syscall.ENOENT,
1612 },
1613 {
1614 sfdir,
1615 O_WRONLY,
1616 syscall.EISDIR,
1617 },
1618 {
1619 sfdir + "/" + sfname + "/no-such-file",
1620 O_WRONLY,
1621 syscall.ENOTDIR,
1622 },
1623 }
1624
1625 func TestOpenError(t *testing.T) {
1626 for _, tt := range openErrorTests {
1627 f, err := OpenFile(tt.path, tt.mode, 0)
1628 if err == nil {
1629 t.Errorf("Open(%q, %d) succeeded", tt.path, tt.mode)
1630 f.Close()
1631 continue
1632 }
1633 perr, ok := err.(*PathError)
1634 if !ok {
1635 t.Errorf("Open(%q, %d) returns error of %T type; want *PathError", tt.path, tt.mode, err)
1636 }
1637 if perr.Err != tt.error {
1638 if runtime.GOOS == "plan9" {
1639 syscallErrStr := perr.Err.Error()
1640 expectedErrStr := strings.Replace(tt.error.Error(), "file ", "", 1)
1641 if !strings.HasSuffix(syscallErrStr, expectedErrStr) {
1642
1643
1644
1645 if tt.error == syscall.EISDIR && strings.HasSuffix(syscallErrStr, syscall.EACCES.Error()) {
1646 continue
1647 }
1648 t.Errorf("Open(%q, %d) = _, %q; want suffix %q", tt.path, tt.mode, syscallErrStr, expectedErrStr)
1649 }
1650 continue
1651 }
1652 if runtime.GOOS == "dragonfly" {
1653
1654
1655 if tt.error == syscall.EISDIR && perr.Err == syscall.EACCES {
1656 continue
1657 }
1658 }
1659 t.Errorf("Open(%q, %d) = _, %q; want %q", tt.path, tt.mode, perr.Err.Error(), tt.error.Error())
1660 }
1661 }
1662 }
1663
1664 func TestOpenNoName(t *testing.T) {
1665 f, err := Open("")
1666 if err == nil {
1667 f.Close()
1668 t.Fatal(`Open("") succeeded`)
1669 }
1670 }
1671
1672 func runBinHostname(t *testing.T) string {
1673
1674 r, w, err := Pipe()
1675 if err != nil {
1676 t.Fatal(err)
1677 }
1678 defer r.Close()
1679 const path = "/bin/hostname"
1680 argv := []string{"hostname"}
1681 if runtime.GOOS == "aix" {
1682 argv = []string{"hostname", "-s"}
1683 }
1684 p, err := StartProcess(path, argv, &ProcAttr{Files: []*File{nil, w, Stderr}})
1685 if err != nil {
1686 if _, err := Stat(path); IsNotExist(err) {
1687 t.Skipf("skipping test; test requires %s but it does not exist", path)
1688 }
1689 t.Fatal(err)
1690 }
1691 w.Close()
1692
1693 var b bytes.Buffer
1694 io.Copy(&b, r)
1695 _, err = p.Wait()
1696 if err != nil {
1697 t.Fatalf("run hostname Wait: %v", err)
1698 }
1699 err = p.Kill()
1700 if err == nil {
1701 t.Errorf("expected an error from Kill running 'hostname'")
1702 }
1703 output := b.String()
1704 if n := len(output); n > 0 && output[n-1] == '\n' {
1705 output = output[0 : n-1]
1706 }
1707 if output == "" {
1708 t.Fatalf("/bin/hostname produced no output")
1709 }
1710
1711 return output
1712 }
1713
1714 func testWindowsHostname(t *testing.T, hostname string) {
1715 cmd := osexec.Command("hostname")
1716 out, err := cmd.CombinedOutput()
1717 if err != nil {
1718 t.Fatalf("Failed to execute hostname command: %v %s", err, out)
1719 }
1720 want := strings.Trim(string(out), "\r\n")
1721 if hostname != want {
1722 t.Fatalf("Hostname() = %q != system hostname of %q", hostname, want)
1723 }
1724 }
1725
1726 func TestHostname(t *testing.T) {
1727 hostname, err := Hostname()
1728 if err != nil {
1729 t.Fatal(err)
1730 }
1731 if hostname == "" {
1732 t.Fatal("Hostname returned empty string and no error")
1733 }
1734 if strings.Contains(hostname, "\x00") {
1735 t.Fatalf("unexpected zero byte in hostname: %q", hostname)
1736 }
1737
1738
1739
1740 switch runtime.GOOS {
1741 case "android", "plan9":
1742
1743 return
1744 case "windows":
1745 testWindowsHostname(t, hostname)
1746 return
1747 }
1748
1749 testenv.MustHaveExec(t)
1750
1751
1752
1753
1754 want := runBinHostname(t)
1755 if hostname != want {
1756 host, _, ok := strings.Cut(hostname, ".")
1757 if !ok || host != want {
1758 t.Errorf("Hostname() = %q, want %q", hostname, want)
1759 }
1760 }
1761 }
1762
1763 func TestReadAt(t *testing.T) {
1764 f := newFile("TestReadAt", t)
1765 defer Remove(f.Name())
1766 defer f.Close()
1767
1768 const data = "hello, world\n"
1769 io.WriteString(f, data)
1770
1771 b := make([]byte, 5)
1772 n, err := f.ReadAt(b, 7)
1773 if err != nil || n != len(b) {
1774 t.Fatalf("ReadAt 7: %d, %v", n, err)
1775 }
1776 if string(b) != "world" {
1777 t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
1778 }
1779 }
1780
1781
1782
1783
1784
1785 func TestReadAtOffset(t *testing.T) {
1786 f := newFile("TestReadAtOffset", t)
1787 defer Remove(f.Name())
1788 defer f.Close()
1789
1790 const data = "hello, world\n"
1791 io.WriteString(f, data)
1792
1793 f.Seek(0, 0)
1794 b := make([]byte, 5)
1795
1796 n, err := f.ReadAt(b, 7)
1797 if err != nil || n != len(b) {
1798 t.Fatalf("ReadAt 7: %d, %v", n, err)
1799 }
1800 if string(b) != "world" {
1801 t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
1802 }
1803
1804 n, err = f.Read(b)
1805 if err != nil || n != len(b) {
1806 t.Fatalf("Read: %d, %v", n, err)
1807 }
1808 if string(b) != "hello" {
1809 t.Fatalf("Read: have %q want %q", string(b), "hello")
1810 }
1811 }
1812
1813
1814 func TestReadAtNegativeOffset(t *testing.T) {
1815 f := newFile("TestReadAtNegativeOffset", t)
1816 defer Remove(f.Name())
1817 defer f.Close()
1818
1819 const data = "hello, world\n"
1820 io.WriteString(f, data)
1821
1822 f.Seek(0, 0)
1823 b := make([]byte, 5)
1824
1825 n, err := f.ReadAt(b, -10)
1826
1827 const wantsub = "negative offset"
1828 if !strings.Contains(fmt.Sprint(err), wantsub) || n != 0 {
1829 t.Errorf("ReadAt(-10) = %v, %v; want 0, ...%q...", n, err, wantsub)
1830 }
1831 }
1832
1833 func TestWriteAt(t *testing.T) {
1834 f := newFile("TestWriteAt", t)
1835 defer Remove(f.Name())
1836 defer f.Close()
1837
1838 const data = "hello, world\n"
1839 io.WriteString(f, data)
1840
1841 n, err := f.WriteAt([]byte("WORLD"), 7)
1842 if err != nil || n != 5 {
1843 t.Fatalf("WriteAt 7: %d, %v", n, err)
1844 }
1845
1846 b, err := os.ReadFile(f.Name())
1847 if err != nil {
1848 t.Fatalf("ReadFile %s: %v", f.Name(), err)
1849 }
1850 if string(b) != "hello, WORLD\n" {
1851 t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
1852 }
1853 }
1854
1855
1856 func TestWriteAtNegativeOffset(t *testing.T) {
1857 f := newFile("TestWriteAtNegativeOffset", t)
1858 defer Remove(f.Name())
1859 defer f.Close()
1860
1861 n, err := f.WriteAt([]byte("WORLD"), -10)
1862
1863 const wantsub = "negative offset"
1864 if !strings.Contains(fmt.Sprint(err), wantsub) || n != 0 {
1865 t.Errorf("WriteAt(-10) = %v, %v; want 0, ...%q...", n, err, wantsub)
1866 }
1867 }
1868
1869
1870 func TestWriteAtInAppendMode(t *testing.T) {
1871 defer chtmpdir(t)()
1872 f, err := OpenFile("write_at_in_append_mode.txt", O_APPEND|O_CREATE, 0666)
1873 if err != nil {
1874 t.Fatalf("OpenFile: %v", err)
1875 }
1876 defer f.Close()
1877
1878 _, err = f.WriteAt([]byte(""), 1)
1879 if err != ErrWriteAtInAppendMode {
1880 t.Fatalf("f.WriteAt returned %v, expected %v", err, ErrWriteAtInAppendMode)
1881 }
1882 }
1883
1884 func writeFile(t *testing.T, fname string, flag int, text string) string {
1885 f, err := OpenFile(fname, flag, 0666)
1886 if err != nil {
1887 t.Fatalf("Open: %v", err)
1888 }
1889 n, err := io.WriteString(f, text)
1890 if err != nil {
1891 t.Fatalf("WriteString: %d, %v", n, err)
1892 }
1893 f.Close()
1894 data, err := os.ReadFile(fname)
1895 if err != nil {
1896 t.Fatalf("ReadFile: %v", err)
1897 }
1898 return string(data)
1899 }
1900
1901 func TestAppend(t *testing.T) {
1902 defer chtmpdir(t)()
1903 const f = "append.txt"
1904 s := writeFile(t, f, O_CREATE|O_TRUNC|O_RDWR, "new")
1905 if s != "new" {
1906 t.Fatalf("writeFile: have %q want %q", s, "new")
1907 }
1908 s = writeFile(t, f, O_APPEND|O_RDWR, "|append")
1909 if s != "new|append" {
1910 t.Fatalf("writeFile: have %q want %q", s, "new|append")
1911 }
1912 s = writeFile(t, f, O_CREATE|O_APPEND|O_RDWR, "|append")
1913 if s != "new|append|append" {
1914 t.Fatalf("writeFile: have %q want %q", s, "new|append|append")
1915 }
1916 err := Remove(f)
1917 if err != nil {
1918 t.Fatalf("Remove: %v", err)
1919 }
1920 s = writeFile(t, f, O_CREATE|O_APPEND|O_RDWR, "new&append")
1921 if s != "new&append" {
1922 t.Fatalf("writeFile: after append have %q want %q", s, "new&append")
1923 }
1924 s = writeFile(t, f, O_CREATE|O_RDWR, "old")
1925 if s != "old&append" {
1926 t.Fatalf("writeFile: after create have %q want %q", s, "old&append")
1927 }
1928 s = writeFile(t, f, O_CREATE|O_TRUNC|O_RDWR, "new")
1929 if s != "new" {
1930 t.Fatalf("writeFile: after truncate have %q want %q", s, "new")
1931 }
1932 }
1933
1934 func TestStatDirWithTrailingSlash(t *testing.T) {
1935
1936 path := t.TempDir()
1937
1938
1939 if _, err := Stat(path); err != nil {
1940 t.Fatalf("stat %s failed: %s", path, err)
1941 }
1942
1943
1944 path += "/"
1945 if _, err := Stat(path); err != nil {
1946 t.Fatalf("stat %s failed: %s", path, err)
1947 }
1948 }
1949
1950 func TestNilProcessStateString(t *testing.T) {
1951 var ps *ProcessState
1952 s := ps.String()
1953 if s != "<nil>" {
1954 t.Errorf("(*ProcessState)(nil).String() = %q, want %q", s, "<nil>")
1955 }
1956 }
1957
1958 func TestSameFile(t *testing.T) {
1959 defer chtmpdir(t)()
1960 fa, err := Create("a")
1961 if err != nil {
1962 t.Fatalf("Create(a): %v", err)
1963 }
1964 fa.Close()
1965 fb, err := Create("b")
1966 if err != nil {
1967 t.Fatalf("Create(b): %v", err)
1968 }
1969 fb.Close()
1970
1971 ia1, err := Stat("a")
1972 if err != nil {
1973 t.Fatalf("Stat(a): %v", err)
1974 }
1975 ia2, err := Stat("a")
1976 if err != nil {
1977 t.Fatalf("Stat(a): %v", err)
1978 }
1979 if !SameFile(ia1, ia2) {
1980 t.Errorf("files should be same")
1981 }
1982
1983 ib, err := Stat("b")
1984 if err != nil {
1985 t.Fatalf("Stat(b): %v", err)
1986 }
1987 if SameFile(ia1, ib) {
1988 t.Errorf("files should be different")
1989 }
1990 }
1991
1992 func testDevNullFileInfo(t *testing.T, statname, devNullName string, fi FileInfo, ignoreCase bool) {
1993 pre := fmt.Sprintf("%s(%q): ", statname, devNullName)
1994 name := filepath.Base(devNullName)
1995 if ignoreCase {
1996 if strings.ToUpper(fi.Name()) != strings.ToUpper(name) {
1997 t.Errorf(pre+"wrong file name have %v want %v", fi.Name(), name)
1998 }
1999 } else {
2000 if fi.Name() != name {
2001 t.Errorf(pre+"wrong file name have %v want %v", fi.Name(), name)
2002 }
2003 }
2004 if fi.Size() != 0 {
2005 t.Errorf(pre+"wrong file size have %d want 0", fi.Size())
2006 }
2007 if fi.Mode()&ModeDevice == 0 {
2008 t.Errorf(pre+"wrong file mode %q: ModeDevice is not set", fi.Mode())
2009 }
2010 if fi.Mode()&ModeCharDevice == 0 {
2011 t.Errorf(pre+"wrong file mode %q: ModeCharDevice is not set", fi.Mode())
2012 }
2013 if fi.Mode().IsRegular() {
2014 t.Errorf(pre+"wrong file mode %q: IsRegular returns true", fi.Mode())
2015 }
2016 }
2017
2018 func testDevNullFile(t *testing.T, devNullName string, ignoreCase bool) {
2019 f, err := Open(devNullName)
2020 if err != nil {
2021 t.Fatalf("Open(%s): %v", devNullName, err)
2022 }
2023 defer f.Close()
2024
2025 fi, err := f.Stat()
2026 if err != nil {
2027 t.Fatalf("Stat(%s): %v", devNullName, err)
2028 }
2029 testDevNullFileInfo(t, "f.Stat", devNullName, fi, ignoreCase)
2030
2031 fi, err = Stat(devNullName)
2032 if err != nil {
2033 t.Fatalf("Stat(%s): %v", devNullName, err)
2034 }
2035 testDevNullFileInfo(t, "Stat", devNullName, fi, ignoreCase)
2036 }
2037
2038 func TestDevNullFile(t *testing.T) {
2039 testDevNullFile(t, DevNull, false)
2040 }
2041
2042 var testLargeWrite = flag.Bool("large_write", false, "run TestLargeWriteToConsole test that floods console with output")
2043
2044 func TestLargeWriteToConsole(t *testing.T) {
2045 if !*testLargeWrite {
2046 t.Skip("skipping console-flooding test; enable with -large_write")
2047 }
2048 b := make([]byte, 32000)
2049 for i := range b {
2050 b[i] = '.'
2051 }
2052 b[len(b)-1] = '\n'
2053 n, err := Stdout.Write(b)
2054 if err != nil {
2055 t.Fatalf("Write to os.Stdout failed: %v", err)
2056 }
2057 if n != len(b) {
2058 t.Errorf("Write to os.Stdout should return %d; got %d", len(b), n)
2059 }
2060 n, err = Stderr.Write(b)
2061 if err != nil {
2062 t.Fatalf("Write to os.Stderr failed: %v", err)
2063 }
2064 if n != len(b) {
2065 t.Errorf("Write to os.Stderr should return %d; got %d", len(b), n)
2066 }
2067 }
2068
2069 func TestStatDirModeExec(t *testing.T) {
2070 const mode = 0111
2071
2072 path := t.TempDir()
2073 if err := Chmod(path, 0777); err != nil {
2074 t.Fatalf("Chmod %q 0777: %v", path, err)
2075 }
2076
2077 dir, err := Stat(path)
2078 if err != nil {
2079 t.Fatalf("Stat %q (looking for mode %#o): %s", path, mode, err)
2080 }
2081 if dir.Mode()&mode != mode {
2082 t.Errorf("Stat %q: mode %#o want %#o", path, dir.Mode()&mode, mode)
2083 }
2084 }
2085
2086 func TestStatStdin(t *testing.T) {
2087 switch runtime.GOOS {
2088 case "android", "plan9":
2089 t.Skipf("%s doesn't have /bin/sh", runtime.GOOS)
2090 }
2091
2092 testenv.MustHaveExec(t)
2093
2094 if Getenv("GO_WANT_HELPER_PROCESS") == "1" {
2095 st, err := Stdin.Stat()
2096 if err != nil {
2097 t.Fatalf("Stat failed: %v", err)
2098 }
2099 fmt.Println(st.Mode() & ModeNamedPipe)
2100 Exit(0)
2101 }
2102
2103 fi, err := Stdin.Stat()
2104 if err != nil {
2105 t.Fatal(err)
2106 }
2107 switch mode := fi.Mode(); {
2108 case mode&ModeCharDevice != 0 && mode&ModeDevice != 0:
2109 case mode&ModeNamedPipe != 0:
2110 default:
2111 t.Fatalf("unexpected Stdin mode (%v), want ModeCharDevice or ModeNamedPipe", mode)
2112 }
2113
2114 var cmd *osexec.Cmd
2115 if runtime.GOOS == "windows" {
2116 cmd = osexec.Command("cmd", "/c", "echo output | "+Args[0]+" -test.run=TestStatStdin")
2117 } else {
2118 cmd = osexec.Command("/bin/sh", "-c", "echo output | "+Args[0]+" -test.run=TestStatStdin")
2119 }
2120 cmd.Env = append(Environ(), "GO_WANT_HELPER_PROCESS=1")
2121
2122 output, err := cmd.CombinedOutput()
2123 if err != nil {
2124 t.Fatalf("Failed to spawn child process: %v %q", err, string(output))
2125 }
2126
2127
2128 if len(output) < 1 || output[0] != 'p' {
2129 t.Fatalf("Child process reports stdin is not pipe '%v'", string(output))
2130 }
2131 }
2132
2133 func TestStatRelativeSymlink(t *testing.T) {
2134 testenv.MustHaveSymlink(t)
2135
2136 tmpdir := t.TempDir()
2137 target := filepath.Join(tmpdir, "target")
2138 f, err := Create(target)
2139 if err != nil {
2140 t.Fatal(err)
2141 }
2142 defer f.Close()
2143
2144 st, err := f.Stat()
2145 if err != nil {
2146 t.Fatal(err)
2147 }
2148
2149 link := filepath.Join(tmpdir, "link")
2150 err = Symlink(filepath.Base(target), link)
2151 if err != nil {
2152 t.Fatal(err)
2153 }
2154
2155 st1, err := Stat(link)
2156 if err != nil {
2157 t.Fatal(err)
2158 }
2159
2160 if !SameFile(st, st1) {
2161 t.Error("Stat doesn't follow relative symlink")
2162 }
2163
2164 if runtime.GOOS == "windows" {
2165 Remove(link)
2166 err = Symlink(target[len(filepath.VolumeName(target)):], link)
2167 if err != nil {
2168 t.Fatal(err)
2169 }
2170
2171 st1, err := Stat(link)
2172 if err != nil {
2173 t.Fatal(err)
2174 }
2175
2176 if !SameFile(st, st1) {
2177 t.Error("Stat doesn't follow relative symlink")
2178 }
2179 }
2180 }
2181
2182 func TestReadAtEOF(t *testing.T) {
2183 f := newFile("TestReadAtEOF", t)
2184 defer Remove(f.Name())
2185 defer f.Close()
2186
2187 _, err := f.ReadAt(make([]byte, 10), 0)
2188 switch err {
2189 case io.EOF:
2190
2191 case nil:
2192 t.Fatalf("ReadAt succeeded")
2193 default:
2194 t.Fatalf("ReadAt failed: %s", err)
2195 }
2196 }
2197
2198 func TestLongPath(t *testing.T) {
2199 tmpdir := newDir("TestLongPath", t)
2200 defer func(d string) {
2201 if err := RemoveAll(d); err != nil {
2202 t.Fatalf("RemoveAll failed: %v", err)
2203 }
2204 }(tmpdir)
2205
2206
2207 sizes := []int{247, 248, 249, 400}
2208 for len(tmpdir) < 400 {
2209 tmpdir += "/dir3456789"
2210 }
2211 for _, sz := range sizes {
2212 t.Run(fmt.Sprintf("length=%d", sz), func(t *testing.T) {
2213 sizedTempDir := tmpdir[:sz-1] + "x"
2214
2215
2216
2217 if err := MkdirAll(sizedTempDir, 0755); err != nil {
2218 t.Fatalf("MkdirAll failed: %v", err)
2219 }
2220 data := []byte("hello world\n")
2221 if err := os.WriteFile(sizedTempDir+"/foo.txt", data, 0644); err != nil {
2222 t.Fatalf("os.WriteFile() failed: %v", err)
2223 }
2224 if err := Rename(sizedTempDir+"/foo.txt", sizedTempDir+"/bar.txt"); err != nil {
2225 t.Fatalf("Rename failed: %v", err)
2226 }
2227 mtime := time.Now().Truncate(time.Minute)
2228 if err := Chtimes(sizedTempDir+"/bar.txt", mtime, mtime); err != nil {
2229 t.Fatalf("Chtimes failed: %v", err)
2230 }
2231 names := []string{"bar.txt"}
2232 if testenv.HasSymlink() {
2233 if err := Symlink(sizedTempDir+"/bar.txt", sizedTempDir+"/symlink.txt"); err != nil {
2234 t.Fatalf("Symlink failed: %v", err)
2235 }
2236 names = append(names, "symlink.txt")
2237 }
2238 if testenv.HasLink() {
2239 if err := Link(sizedTempDir+"/bar.txt", sizedTempDir+"/link.txt"); err != nil {
2240 t.Fatalf("Link failed: %v", err)
2241 }
2242 names = append(names, "link.txt")
2243 }
2244 for _, wantSize := range []int64{int64(len(data)), 0} {
2245 for _, name := range names {
2246 path := sizedTempDir + "/" + name
2247 dir, err := Stat(path)
2248 if err != nil {
2249 t.Fatalf("Stat(%q) failed: %v", path, err)
2250 }
2251 filesize := size(path, t)
2252 if dir.Size() != filesize || filesize != wantSize {
2253 t.Errorf("Size(%q) is %d, len(ReadFile()) is %d, want %d", path, dir.Size(), filesize, wantSize)
2254 }
2255 err = Chmod(path, dir.Mode())
2256 if err != nil {
2257 t.Fatalf("Chmod(%q) failed: %v", path, err)
2258 }
2259 }
2260 if err := Truncate(sizedTempDir+"/bar.txt", 0); err != nil {
2261 t.Fatalf("Truncate failed: %v", err)
2262 }
2263 }
2264 })
2265 }
2266 }
2267
2268 func testKillProcess(t *testing.T, processKiller func(p *Process)) {
2269 testenv.MustHaveExec(t)
2270 t.Parallel()
2271
2272
2273 cmd := osexec.Command(Args[0])
2274 cmd.Env = append(os.Environ(), "GO_OS_TEST_DRAIN_STDIN=1")
2275 stdout, err := cmd.StdoutPipe()
2276 if err != nil {
2277 t.Fatal(err)
2278 }
2279 stdin, err := cmd.StdinPipe()
2280 if err != nil {
2281 t.Fatal(err)
2282 }
2283 err = cmd.Start()
2284 if err != nil {
2285 t.Fatalf("Failed to start test process: %v", err)
2286 }
2287
2288 defer func() {
2289 if err := cmd.Wait(); err == nil {
2290 t.Errorf("Test process succeeded, but expected to fail")
2291 }
2292 stdin.Close()
2293 }()
2294
2295
2296
2297 io.Copy(io.Discard, stdout)
2298
2299 processKiller(cmd.Process)
2300 }
2301
2302 func TestKillStartProcess(t *testing.T) {
2303 testKillProcess(t, func(p *Process) {
2304 err := p.Kill()
2305 if err != nil {
2306 t.Fatalf("Failed to kill test process: %v", err)
2307 }
2308 })
2309 }
2310
2311 func TestGetppid(t *testing.T) {
2312 if runtime.GOOS == "plan9" {
2313
2314 t.Skipf("skipping test on plan9; see issue 8206")
2315 }
2316
2317 testenv.MustHaveExec(t)
2318
2319 if Getenv("GO_WANT_HELPER_PROCESS") == "1" {
2320 fmt.Print(Getppid())
2321 Exit(0)
2322 }
2323
2324 cmd := osexec.Command(Args[0], "-test.run=TestGetppid")
2325 cmd.Env = append(Environ(), "GO_WANT_HELPER_PROCESS=1")
2326
2327
2328 output, err := cmd.CombinedOutput()
2329 if err != nil {
2330 t.Fatalf("Failed to spawn child process: %v %q", err, string(output))
2331 }
2332
2333 childPpid := string(output)
2334 ourPid := fmt.Sprintf("%d", Getpid())
2335 if childPpid != ourPid {
2336 t.Fatalf("Child process reports parent process id '%v', expected '%v'", childPpid, ourPid)
2337 }
2338 }
2339
2340 func TestKillFindProcess(t *testing.T) {
2341 testKillProcess(t, func(p *Process) {
2342 p2, err := FindProcess(p.Pid)
2343 if err != nil {
2344 t.Fatalf("Failed to find test process: %v", err)
2345 }
2346 err = p2.Kill()
2347 if err != nil {
2348 t.Fatalf("Failed to kill test process: %v", err)
2349 }
2350 })
2351 }
2352
2353 var nilFileMethodTests = []struct {
2354 name string
2355 f func(*File) error
2356 }{
2357 {"Chdir", func(f *File) error { return f.Chdir() }},
2358 {"Close", func(f *File) error { return f.Close() }},
2359 {"Chmod", func(f *File) error { return f.Chmod(0) }},
2360 {"Chown", func(f *File) error { return f.Chown(0, 0) }},
2361 {"Read", func(f *File) error { _, err := f.Read(make([]byte, 0)); return err }},
2362 {"ReadAt", func(f *File) error { _, err := f.ReadAt(make([]byte, 0), 0); return err }},
2363 {"Readdir", func(f *File) error { _, err := f.Readdir(1); return err }},
2364 {"Readdirnames", func(f *File) error { _, err := f.Readdirnames(1); return err }},
2365 {"Seek", func(f *File) error { _, err := f.Seek(0, io.SeekStart); return err }},
2366 {"Stat", func(f *File) error { _, err := f.Stat(); return err }},
2367 {"Sync", func(f *File) error { return f.Sync() }},
2368 {"Truncate", func(f *File) error { return f.Truncate(0) }},
2369 {"Write", func(f *File) error { _, err := f.Write(make([]byte, 0)); return err }},
2370 {"WriteAt", func(f *File) error { _, err := f.WriteAt(make([]byte, 0), 0); return err }},
2371 {"WriteString", func(f *File) error { _, err := f.WriteString(""); return err }},
2372 }
2373
2374
2375 func TestNilFileMethods(t *testing.T) {
2376 for _, tt := range nilFileMethodTests {
2377 var file *File
2378 got := tt.f(file)
2379 if got != ErrInvalid {
2380 t.Errorf("%v should fail when f is nil; got %v", tt.name, got)
2381 }
2382 }
2383 }
2384
2385 func mkdirTree(t *testing.T, root string, level, max int) {
2386 if level >= max {
2387 return
2388 }
2389 level++
2390 for i := 'a'; i < 'c'; i++ {
2391 dir := filepath.Join(root, string(i))
2392 if err := Mkdir(dir, 0700); err != nil {
2393 t.Fatal(err)
2394 }
2395 mkdirTree(t, dir, level, max)
2396 }
2397 }
2398
2399
2400
2401 func TestRemoveAllRace(t *testing.T) {
2402 if runtime.GOOS == "windows" {
2403
2404
2405
2406
2407 t.Skip("skipping on windows")
2408 }
2409
2410 n := runtime.GOMAXPROCS(16)
2411 defer runtime.GOMAXPROCS(n)
2412 root, err := os.MkdirTemp("", "issue")
2413 if err != nil {
2414 t.Fatal(err)
2415 }
2416 mkdirTree(t, root, 1, 6)
2417 hold := make(chan struct{})
2418 var wg sync.WaitGroup
2419 for i := 0; i < 4; i++ {
2420 wg.Add(1)
2421 go func() {
2422 defer wg.Done()
2423 <-hold
2424 err := RemoveAll(root)
2425 if err != nil {
2426 t.Errorf("unexpected error: %T, %q", err, err)
2427 }
2428 }()
2429 }
2430 close(hold)
2431 wg.Wait()
2432 }
2433
2434
2435 func TestPipeThreads(t *testing.T) {
2436 switch runtime.GOOS {
2437 case "illumos", "solaris":
2438 t.Skip("skipping on Solaris and illumos; issue 19111")
2439 case "windows":
2440 t.Skip("skipping on Windows; issue 19098")
2441 case "plan9":
2442 t.Skip("skipping on Plan 9; does not support runtime poller")
2443 case "js":
2444 t.Skip("skipping on js; no support for os.Pipe")
2445 }
2446
2447 threads := 100
2448
2449
2450 if runtime.GOOS == "openbsd" {
2451 threads = 50
2452 }
2453
2454 r := make([]*File, threads)
2455 w := make([]*File, threads)
2456 for i := 0; i < threads; i++ {
2457 rp, wp, err := Pipe()
2458 if err != nil {
2459 for j := 0; j < i; j++ {
2460 r[j].Close()
2461 w[j].Close()
2462 }
2463 t.Fatal(err)
2464 }
2465 r[i] = rp
2466 w[i] = wp
2467 }
2468
2469 defer debug.SetMaxThreads(debug.SetMaxThreads(threads / 2))
2470
2471 creading := make(chan bool, threads)
2472 cdone := make(chan bool, threads)
2473 for i := 0; i < threads; i++ {
2474 go func(i int) {
2475 var b [1]byte
2476 creading <- true
2477 if _, err := r[i].Read(b[:]); err != nil {
2478 t.Error(err)
2479 }
2480 if err := r[i].Close(); err != nil {
2481 t.Error(err)
2482 }
2483 cdone <- true
2484 }(i)
2485 }
2486
2487 for i := 0; i < threads; i++ {
2488 <-creading
2489 }
2490
2491
2492
2493
2494 for i := 0; i < threads; i++ {
2495 if _, err := w[i].Write([]byte{0}); err != nil {
2496 t.Error(err)
2497 }
2498 if err := w[i].Close(); err != nil {
2499 t.Error(err)
2500 }
2501 <-cdone
2502 }
2503 }
2504
2505 func testDoubleCloseError(t *testing.T, path string) {
2506 file, err := Open(path)
2507 if err != nil {
2508 t.Fatal(err)
2509 }
2510 if err := file.Close(); err != nil {
2511 t.Fatalf("unexpected error from Close: %v", err)
2512 }
2513 if err := file.Close(); err == nil {
2514 t.Error("second Close did not fail")
2515 } else if pe, ok := err.(*PathError); !ok {
2516 t.Errorf("second Close returned unexpected error type %T; expected fs.PathError", pe)
2517 } else if pe.Err != ErrClosed {
2518 t.Errorf("second Close returned %q, wanted %q", err, ErrClosed)
2519 } else {
2520 t.Logf("second close returned expected error %q", err)
2521 }
2522 }
2523
2524 func TestDoubleCloseError(t *testing.T) {
2525 testDoubleCloseError(t, filepath.Join(sfdir, sfname))
2526 testDoubleCloseError(t, sfdir)
2527 }
2528
2529 func TestUserHomeDir(t *testing.T) {
2530 dir, err := UserHomeDir()
2531 if dir == "" && err == nil {
2532 t.Fatal("UserHomeDir returned an empty string but no error")
2533 }
2534 if err != nil {
2535 t.Skipf("UserHomeDir failed: %v", err)
2536 }
2537 fi, err := Stat(dir)
2538 if err != nil {
2539 t.Fatal(err)
2540 }
2541 if !fi.IsDir() {
2542 t.Fatalf("dir %s is not directory; type = %v", dir, fi.Mode())
2543 }
2544 }
2545
2546 func TestDirSeek(t *testing.T) {
2547 if runtime.GOOS == "windows" {
2548 testenv.SkipFlaky(t, 36019)
2549 }
2550 wd, err := Getwd()
2551 if err != nil {
2552 t.Fatal(err)
2553 }
2554 f, err := Open(wd)
2555 if err != nil {
2556 t.Fatal(err)
2557 }
2558 dirnames1, err := f.Readdirnames(0)
2559 if err != nil {
2560 t.Fatal(err)
2561 }
2562
2563 ret, err := f.Seek(0, 0)
2564 if err != nil {
2565 t.Fatal(err)
2566 }
2567 if ret != 0 {
2568 t.Fatalf("seek result not zero: %d", ret)
2569 }
2570
2571 dirnames2, err := f.Readdirnames(0)
2572 if err != nil {
2573 t.Fatal(err)
2574 return
2575 }
2576
2577 if len(dirnames1) != len(dirnames2) {
2578 t.Fatalf("listings have different lengths: %d and %d\n", len(dirnames1), len(dirnames2))
2579 }
2580 for i, n1 := range dirnames1 {
2581 n2 := dirnames2[i]
2582 if n1 != n2 {
2583 t.Fatalf("different name i=%d n1=%s n2=%s\n", i, n1, n2)
2584 }
2585 }
2586 }
2587
2588 func TestReaddirSmallSeek(t *testing.T) {
2589
2590
2591
2592 if runtime.GOOS == "windows" {
2593 testenv.SkipFlaky(t, 36019)
2594 }
2595 wd, err := Getwd()
2596 if err != nil {
2597 t.Fatal(err)
2598 }
2599 df, err := Open(filepath.Join(wd, "testdata", "issue37161"))
2600 if err != nil {
2601 t.Fatal(err)
2602 }
2603 names1, err := df.Readdirnames(1)
2604 if err != nil {
2605 t.Fatal(err)
2606 }
2607 if _, err = df.Seek(0, 0); err != nil {
2608 t.Fatal(err)
2609 }
2610 names2, err := df.Readdirnames(0)
2611 if err != nil {
2612 t.Fatal(err)
2613 }
2614 if len(names2) != 3 {
2615 t.Fatalf("first names: %v, second names: %v", names1, names2)
2616 }
2617 }
2618
2619
2620
2621 func isDeadlineExceeded(err error) bool {
2622 if !IsTimeout(err) {
2623 return false
2624 }
2625 if !errors.Is(err, ErrDeadlineExceeded) {
2626 return false
2627 }
2628 return true
2629 }
2630
2631
2632 func TestOpenFileKeepsPermissions(t *testing.T) {
2633 t.Parallel()
2634 dir := t.TempDir()
2635 name := filepath.Join(dir, "x")
2636 f, err := Create(name)
2637 if err != nil {
2638 t.Fatal(err)
2639 }
2640 if err := f.Close(); err != nil {
2641 t.Error(err)
2642 }
2643 f, err = OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, 0)
2644 if err != nil {
2645 t.Fatal(err)
2646 }
2647 if fi, err := f.Stat(); err != nil {
2648 t.Error(err)
2649 } else if fi.Mode()&0222 == 0 {
2650 t.Errorf("f.Stat.Mode after OpenFile is %v, should be writable", fi.Mode())
2651 }
2652 if err := f.Close(); err != nil {
2653 t.Error(err)
2654 }
2655 if fi, err := Stat(name); err != nil {
2656 t.Error(err)
2657 } else if fi.Mode()&0222 == 0 {
2658 t.Errorf("Stat after OpenFile is %v, should be writable", fi.Mode())
2659 }
2660 }
2661
2662 func TestDirFS(t *testing.T) {
2663
2664
2665 if runtime.GOOS == "windows" {
2666 if err := filepath.WalkDir("./testdata/dirfs", func(path string, d fs.DirEntry, err error) error {
2667 if err != nil {
2668 t.Fatal(err)
2669 }
2670 info, err := d.Info()
2671 if err != nil {
2672 t.Fatal(err)
2673 }
2674 stat, err := Stat(path)
2675 if err != nil {
2676 t.Fatal(err)
2677 }
2678 if stat.ModTime() == info.ModTime() {
2679 return nil
2680 }
2681 if err := Chtimes(path, stat.ModTime(), stat.ModTime()); err != nil {
2682 t.Log(err)
2683 }
2684 return nil
2685 }); err != nil {
2686 t.Fatal(err)
2687 }
2688 }
2689 if err := fstest.TestFS(DirFS("./testdata/dirfs"), "a", "b", "dir/x"); err != nil {
2690 t.Fatal(err)
2691 }
2692
2693
2694 d := DirFS(".")
2695 _, err := d.Open(`testdata\dirfs`)
2696 if err == nil {
2697 t.Fatalf(`Open testdata\dirfs succeeded`)
2698 }
2699 }
2700
2701 func TestDirFSPathsValid(t *testing.T) {
2702 if runtime.GOOS == "windows" {
2703 t.Skipf("skipping on Windows")
2704 }
2705
2706 d := t.TempDir()
2707 if err := os.WriteFile(filepath.Join(d, "control.txt"), []byte(string("Hello, world!")), 0644); err != nil {
2708 t.Fatal(err)
2709 }
2710 if err := os.WriteFile(filepath.Join(d, `e:xperi\ment.txt`), []byte(string("Hello, colon and backslash!")), 0644); err != nil {
2711 t.Fatal(err)
2712 }
2713
2714 fsys := os.DirFS(d)
2715 err := fs.WalkDir(fsys, ".", func(path string, e fs.DirEntry, err error) error {
2716 if fs.ValidPath(e.Name()) {
2717 t.Logf("%q ok", e.Name())
2718 } else {
2719 t.Errorf("%q INVALID", e.Name())
2720 }
2721 return nil
2722 })
2723 if err != nil {
2724 t.Fatal(err)
2725 }
2726 }
2727
2728 func TestReadFileProc(t *testing.T) {
2729
2730
2731
2732
2733
2734 name := "/proc/sys/fs/pipe-max-size"
2735 if _, err := Stat(name); err != nil {
2736 t.Skip(err)
2737 }
2738 data, err := ReadFile(name)
2739 if err != nil {
2740 t.Fatal(err)
2741 }
2742 if len(data) == 0 || data[len(data)-1] != '\n' {
2743 t.Fatalf("read %s: not newline-terminated: %q", name, data)
2744 }
2745 }
2746
2747 func TestWriteStringAlloc(t *testing.T) {
2748 if runtime.GOOS == "js" {
2749 t.Skip("js allocates a lot during File.WriteString")
2750 }
2751 d := t.TempDir()
2752 f, err := Create(filepath.Join(d, "whiteboard.txt"))
2753 if err != nil {
2754 t.Fatal(err)
2755 }
2756 defer f.Close()
2757 allocs := testing.AllocsPerRun(100, func() {
2758 f.WriteString("I will not allocate when passed a string longer than 32 bytes.\n")
2759 })
2760 if allocs != 0 {
2761 t.Errorf("expected 0 allocs for File.WriteString, got %v", allocs)
2762 }
2763 }
2764
View as plain text