OSDN Git Service

Update to current version of Go library.
[pf3gnuchains/gcc-fork.git] / libgo / go / os / os_test.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package os_test
6
7 import (
8         "bytes"
9         "fmt"
10         "io"
11         "io/ioutil"
12         . "os"
13         "path/filepath"
14         "strings"
15         "syscall"
16         "testing"
17 )
18
19 var dot = []string{
20         "dir_unix.go",
21         "env_unix.go",
22         "error.go",
23         "file.go",
24         "os_test.go",
25         "time.go",
26         "types.go",
27 }
28
29 type sysDir struct {
30         name  string
31         files []string
32 }
33
34 var sysdir = func() (sd *sysDir) {
35         switch syscall.OS {
36         case "windows":
37                 sd = &sysDir{
38                         Getenv("SystemRoot") + "\\system32\\drivers\\etc",
39                         []string{
40                                 "hosts",
41                                 "networks",
42                                 "protocol",
43                                 "services",
44                         },
45                 }
46         case "plan9":
47                 sd = &sysDir{
48                         "/lib/ndb",
49                         []string{
50                                 "common",
51                                 "local",
52                         },
53                 }
54         default:
55                 sd = &sysDir{
56                         "/etc",
57                         []string{
58                                 "group",
59                                 "hosts",
60                                 "passwd",
61                         },
62                 }
63         }
64         return
65 }()
66
67 func size(name string, t *testing.T) int64 {
68         file, err := Open(name)
69         defer file.Close()
70         if err != nil {
71                 t.Fatal("open failed:", err)
72         }
73         var buf [100]byte
74         len := 0
75         for {
76                 n, e := file.Read(buf[0:])
77                 len += n
78                 if e == EOF {
79                         break
80                 }
81                 if e != nil {
82                         t.Fatal("read failed:", err)
83                 }
84         }
85         return int64(len)
86 }
87
88 func equal(name1, name2 string) (r bool) {
89         switch syscall.OS {
90         case "windows":
91                 r = strings.ToLower(name1) == strings.ToLower(name2)
92         default:
93                 r = name1 == name2
94         }
95         return
96 }
97
98 func newFile(testName string, t *testing.T) (f *File) {
99         // Use a local file system, not NFS.
100         // On Unix, override $TMPDIR in case the user
101         // has it set to an NFS-mounted directory.
102         dir := ""
103         if syscall.OS != "windows" {
104                 dir = "/tmp"
105         }
106         f, err := ioutil.TempFile(dir, "_Go_"+testName)
107         if err != nil {
108                 t.Fatalf("open %s: %s", testName, err)
109         }
110         return
111 }
112
113 var sfdir = sysdir.name
114 var sfname = sysdir.files[0]
115
116 func TestStat(t *testing.T) {
117         path := sfdir + "/" + sfname
118         dir, err := Stat(path)
119         if err != nil {
120                 t.Fatal("stat failed:", err)
121         }
122         if !equal(sfname, dir.Name) {
123                 t.Error("name should be ", sfname, "; is", dir.Name)
124         }
125         filesize := size(path, t)
126         if dir.Size != filesize {
127                 t.Error("size should be", filesize, "; is", dir.Size)
128         }
129 }
130
131 func TestFstat(t *testing.T) {
132         path := sfdir + "/" + sfname
133         file, err1 := Open(path)
134         defer file.Close()
135         if err1 != nil {
136                 t.Fatal("open failed:", err1)
137         }
138         dir, err2 := file.Stat()
139         if err2 != nil {
140                 t.Fatal("fstat failed:", err2)
141         }
142         if !equal(sfname, dir.Name) {
143                 t.Error("name should be ", sfname, "; is", dir.Name)
144         }
145         filesize := size(path, t)
146         if dir.Size != filesize {
147                 t.Error("size should be", filesize, "; is", dir.Size)
148         }
149 }
150
151 func TestLstat(t *testing.T) {
152         path := sfdir + "/" + sfname
153         dir, err := Lstat(path)
154         if err != nil {
155                 t.Fatal("lstat failed:", err)
156         }
157         if !equal(sfname, dir.Name) {
158                 t.Error("name should be ", sfname, "; is", dir.Name)
159         }
160         filesize := size(path, t)
161         if dir.Size != filesize {
162                 t.Error("size should be", filesize, "; is", dir.Size)
163         }
164 }
165
166 func testReaddirnames(dir string, contents []string, t *testing.T) {
167         file, err := Open(dir)
168         defer file.Close()
169         if err != nil {
170                 t.Fatalf("open %q failed: %v", dir, err)
171         }
172         s, err2 := file.Readdirnames(-1)
173         if err2 != nil {
174                 t.Fatalf("readdirnames %q failed: %v", dir, err2)
175         }
176         for _, m := range contents {
177                 found := false
178                 for _, n := range s {
179                         if n == "." || n == ".." {
180                                 t.Errorf("got %s in directory", n)
181                         }
182                         if equal(m, n) {
183                                 if found {
184                                         t.Error("present twice:", m)
185                                 }
186                                 found = true
187                         }
188                 }
189                 if !found {
190                         t.Error("could not find", m)
191                 }
192         }
193 }
194
195 func testReaddir(dir string, contents []string, t *testing.T) {
196         file, err := Open(dir)
197         defer file.Close()
198         if err != nil {
199                 t.Fatalf("open %q failed: %v", dir, err)
200         }
201         s, err2 := file.Readdir(-1)
202         if err2 != nil {
203                 t.Fatalf("readdir %q failed: %v", dir, err2)
204         }
205         for _, m := range contents {
206                 found := false
207                 for _, n := range s {
208                         if equal(m, n.Name) {
209                                 if found {
210                                         t.Error("present twice:", m)
211                                 }
212                                 found = true
213                         }
214                 }
215                 if !found {
216                         t.Error("could not find", m)
217                 }
218         }
219 }
220
221 func TestReaddirnames(t *testing.T) {
222         testReaddirnames(".", dot, t)
223         testReaddirnames(sysdir.name, sysdir.files, t)
224 }
225
226 func TestReaddir(t *testing.T) {
227         testReaddir(".", dot, t)
228         testReaddir(sysdir.name, sysdir.files, t)
229 }
230
231 // Read the directory one entry at a time.
232 func smallReaddirnames(file *File, length int, t *testing.T) []string {
233         names := make([]string, length)
234         count := 0
235         for {
236                 d, err := file.Readdirnames(1)
237                 if err != nil {
238                         t.Fatalf("readdir %q failed: %v", file.Name(), err)
239                 }
240                 if len(d) == 0 {
241                         break
242                 }
243                 names[count] = d[0]
244                 count++
245         }
246         return names[0:count]
247 }
248
249 // Check that reading a directory one entry at a time gives the same result
250 // as reading it all at once.
251 func TestReaddirnamesOneAtATime(t *testing.T) {
252         // big directory that doesn't change often.
253         dir := "/usr/bin"
254         switch syscall.OS {
255         case "windows":
256                 dir = Getenv("SystemRoot") + "\\system32"
257         case "plan9":
258                 dir = "/bin"
259         }
260         file, err := Open(dir)
261         defer file.Close()
262         if err != nil {
263                 t.Fatalf("open %q failed: %v", dir, err)
264         }
265         all, err1 := file.Readdirnames(-1)
266         if err1 != nil {
267                 t.Fatalf("readdirnames %q failed: %v", dir, err1)
268         }
269         file1, err2 := Open(dir)
270         if err2 != nil {
271                 t.Fatalf("open %q failed: %v", dir, err2)
272         }
273         small := smallReaddirnames(file1, len(all)+100, t) // +100 in case we screw up
274         if len(small) < len(all) {
275                 t.Fatalf("len(small) is %d, less than %d", len(small), len(all))
276         }
277         for i, n := range all {
278                 if small[i] != n {
279                         t.Errorf("small read %q mismatch: %v", small[i], n)
280                 }
281         }
282 }
283
284 func TestHardLink(t *testing.T) {
285         // Hardlinks are not supported under windows.
286         if syscall.OS == "windows" {
287                 return
288         }
289         from, to := "hardlinktestfrom", "hardlinktestto"
290         Remove(from) // Just in case.
291         file, err := Create(to)
292         if err != nil {
293                 t.Fatalf("open %q failed: %v", to, err)
294         }
295         defer Remove(to)
296         if err = file.Close(); err != nil {
297                 t.Errorf("close %q failed: %v", to, err)
298         }
299         err = Link(to, from)
300         if err != nil {
301                 t.Fatalf("link %q, %q failed: %v", to, from, err)
302         }
303         defer Remove(from)
304         tostat, err := Stat(to)
305         if err != nil {
306                 t.Fatalf("stat %q failed: %v", to, err)
307         }
308         fromstat, err := Stat(from)
309         if err != nil {
310                 t.Fatalf("stat %q failed: %v", from, err)
311         }
312         if tostat.Dev != fromstat.Dev || tostat.Ino != fromstat.Ino {
313                 t.Errorf("link %q, %q did not create hard link", to, from)
314         }
315 }
316
317 func TestSymLink(t *testing.T) {
318         // Symlinks are not supported under windows.
319         if syscall.OS == "windows" {
320                 return
321         }
322         from, to := "symlinktestfrom", "symlinktestto"
323         Remove(from) // Just in case.
324         file, err := Create(to)
325         if err != nil {
326                 t.Fatalf("open %q failed: %v", to, err)
327         }
328         defer Remove(to)
329         if err = file.Close(); err != nil {
330                 t.Errorf("close %q failed: %v", to, err)
331         }
332         err = Symlink(to, from)
333         if err != nil {
334                 t.Fatalf("symlink %q, %q failed: %v", to, from, err)
335         }
336         defer Remove(from)
337         tostat, err := Stat(to)
338         if err != nil {
339                 t.Fatalf("stat %q failed: %v", to, err)
340         }
341         if tostat.FollowedSymlink {
342                 t.Fatalf("stat %q claims to have followed a symlink", to)
343         }
344         fromstat, err := Stat(from)
345         if err != nil {
346                 t.Fatalf("stat %q failed: %v", from, err)
347         }
348         if tostat.Dev != fromstat.Dev || tostat.Ino != fromstat.Ino {
349                 t.Errorf("symlink %q, %q did not create symlink", to, from)
350         }
351         fromstat, err = Lstat(from)
352         if err != nil {
353                 t.Fatalf("lstat %q failed: %v", from, err)
354         }
355         if !fromstat.IsSymlink() {
356                 t.Fatalf("symlink %q, %q did not create symlink", to, from)
357         }
358         fromstat, err = Stat(from)
359         if err != nil {
360                 t.Fatalf("stat %q failed: %v", from, err)
361         }
362         if !fromstat.FollowedSymlink {
363                 t.Fatalf("stat %q did not follow symlink", from)
364         }
365         s, err := Readlink(from)
366         if err != nil {
367                 t.Fatalf("readlink %q failed: %v", from, err)
368         }
369         if s != to {
370                 t.Fatalf("after symlink %q != %q", s, to)
371         }
372         file, err = Open(from)
373         if err != nil {
374                 t.Fatalf("open %q failed: %v", from, err)
375         }
376         file.Close()
377 }
378
379 func TestLongSymlink(t *testing.T) {
380         // Symlinks are not supported under windows.
381         if syscall.OS == "windows" {
382                 return
383         }
384         s := "0123456789abcdef"
385         // Long, but not too long: a common limit is 255.
386         s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s
387         from := "longsymlinktestfrom"
388         Remove(from) // Just in case.
389         err := Symlink(s, from)
390         if err != nil {
391                 t.Fatalf("symlink %q, %q failed: %v", s, from, err)
392         }
393         defer Remove(from)
394         r, err := Readlink(from)
395         if err != nil {
396                 t.Fatalf("readlink %q failed: %v", from, err)
397         }
398         if r != s {
399                 t.Fatalf("after symlink %q != %q", r, s)
400         }
401 }
402
403 func TestRename(t *testing.T) {
404         from, to := "renamefrom", "renameto"
405         Remove(to) // Just in case.
406         file, err := Create(from)
407         if err != nil {
408                 t.Fatalf("open %q failed: %v", to, err)
409         }
410         if err = file.Close(); err != nil {
411                 t.Errorf("close %q failed: %v", to, err)
412         }
413         err = Rename(from, to)
414         if err != nil {
415                 t.Fatalf("rename %q, %q failed: %v", to, from, err)
416         }
417         defer Remove(to)
418         _, err = Stat(to)
419         if err != nil {
420                 t.Errorf("stat %q failed: %v", to, err)
421         }
422 }
423
424 func exec(t *testing.T, dir, cmd string, args []string, expect string) {
425         r, w, err := Pipe()
426         if err != nil {
427                 t.Fatalf("Pipe: %v", err)
428         }
429         attr := &ProcAttr{Dir: dir, Files: []*File{nil, w, Stderr}}
430         p, err := StartProcess(cmd, args, attr)
431         if err != nil {
432                 t.Fatalf("StartProcess: %v", err)
433         }
434         defer p.Release()
435         w.Close()
436
437         var b bytes.Buffer
438         io.Copy(&b, r)
439         output := b.String()
440         if output != expect {
441                 t.Errorf("exec %q returned %q wanted %q",
442                         strings.Join(append([]string{cmd}, args...), " "), output, expect)
443         }
444         p.Wait(0)
445 }
446
447 func TestStartProcess(t *testing.T) {
448         var dir, cmd, le string
449         var args []string
450         if syscall.OS == "windows" {
451                 le = "\r\n"
452                 cmd = Getenv("COMSPEC")
453                 dir = Getenv("SystemRoot")
454                 args = []string{"/c", "cd"}
455         } else {
456                 le = "\n"
457                 cmd = "/bin/pwd"
458                 dir = "/"
459                 args = []string{}
460         }
461         cmddir, cmdbase := filepath.Split(cmd)
462         args = append([]string{cmdbase}, args...)
463         // Test absolute executable path.
464         exec(t, dir, cmd, args, dir+le)
465         // Test relative executable path.
466         exec(t, cmddir, cmdbase, args, filepath.Clean(cmddir)+le)
467 }
468
469 func checkMode(t *testing.T, path string, mode uint32) {
470         dir, err := Stat(path)
471         if err != nil {
472                 t.Fatalf("Stat %q (looking for mode %#o): %s", path, mode, err)
473         }
474         if dir.Mode&0777 != mode {
475                 t.Errorf("Stat %q: mode %#o want %#o", path, dir.Mode, mode)
476         }
477 }
478
479 func TestChmod(t *testing.T) {
480         // Chmod is not supported under windows.
481         if syscall.OS == "windows" {
482                 return
483         }
484         f := newFile("TestChmod", t)
485         defer Remove(f.Name())
486         defer f.Close()
487
488         if err := Chmod(f.Name(), 0456); err != nil {
489                 t.Fatalf("chmod %s 0456: %s", f.Name(), err)
490         }
491         checkMode(t, f.Name(), 0456)
492
493         if err := f.Chmod(0123); err != nil {
494                 t.Fatalf("chmod %s 0123: %s", f.Name(), err)
495         }
496         checkMode(t, f.Name(), 0123)
497 }
498
499 func checkUidGid(t *testing.T, path string, uid, gid int) {
500         dir, err := Stat(path)
501         if err != nil {
502                 t.Fatalf("Stat %q (looking for uid/gid %d/%d): %s", path, uid, gid, err)
503         }
504         if dir.Uid != uid {
505                 t.Errorf("Stat %q: uid %d want %d", path, dir.Uid, uid)
506         }
507         if dir.Gid != gid {
508                 t.Errorf("Stat %q: gid %d want %d", path, dir.Gid, gid)
509         }
510 }
511
512 func TestChown(t *testing.T) {
513         // Chown is not supported under windows.
514         if syscall.OS == "windows" {
515                 return
516         }
517         // Use TempDir() to make sure we're on a local file system,
518         // so that the group ids returned by Getgroups will be allowed
519         // on the file.  On NFS, the Getgroups groups are
520         // basically useless.
521         f := newFile("TestChown", t)
522         defer Remove(f.Name())
523         defer f.Close()
524         dir, err := f.Stat()
525         if err != nil {
526                 t.Fatalf("stat %s: %s", f.Name(), err)
527         }
528
529         // Can't change uid unless root, but can try
530         // changing the group id.  First try our current group.
531         gid := Getgid()
532         t.Log("gid:", gid)
533         if err = Chown(f.Name(), -1, gid); err != nil {
534                 t.Fatalf("chown %s -1 %d: %s", f.Name(), gid, err)
535         }
536         checkUidGid(t, f.Name(), dir.Uid, gid)
537
538         // Then try all the auxiliary groups.
539         groups, err := Getgroups()
540         if err != nil {
541                 t.Fatalf("getgroups: %s", err)
542         }
543         t.Log("groups: ", groups)
544         for _, g := range groups {
545                 if err = Chown(f.Name(), -1, g); err != nil {
546                         t.Fatalf("chown %s -1 %d: %s", f.Name(), g, err)
547                 }
548                 checkUidGid(t, f.Name(), dir.Uid, g)
549
550                 // change back to gid to test fd.Chown
551                 if err = f.Chown(-1, gid); err != nil {
552                         t.Fatalf("fchown %s -1 %d: %s", f.Name(), gid, err)
553                 }
554                 checkUidGid(t, f.Name(), dir.Uid, gid)
555         }
556 }
557
558 func checkSize(t *testing.T, f *File, size int64) {
559         dir, err := f.Stat()
560         if err != nil {
561                 t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err)
562         }
563         if dir.Size != size {
564                 t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size, size)
565         }
566 }
567
568 func TestFTruncate(t *testing.T) {
569         f := newFile("TestFTruncate", t)
570         defer Remove(f.Name())
571         defer f.Close()
572
573         checkSize(t, f, 0)
574         f.Write([]byte("hello, world\n"))
575         checkSize(t, f, 13)
576         f.Truncate(10)
577         checkSize(t, f, 10)
578         f.Truncate(1024)
579         checkSize(t, f, 1024)
580         f.Truncate(0)
581         checkSize(t, f, 0)
582         f.Write([]byte("surprise!"))
583         checkSize(t, f, 13+9) // wrote at offset past where hello, world was.
584 }
585
586 func TestTruncate(t *testing.T) {
587         f := newFile("TestTruncate", t)
588         defer Remove(f.Name())
589         defer f.Close()
590
591         checkSize(t, f, 0)
592         f.Write([]byte("hello, world\n"))
593         checkSize(t, f, 13)
594         Truncate(f.Name(), 10)
595         checkSize(t, f, 10)
596         Truncate(f.Name(), 1024)
597         checkSize(t, f, 1024)
598         Truncate(f.Name(), 0)
599         checkSize(t, f, 0)
600         f.Write([]byte("surprise!"))
601         checkSize(t, f, 13+9) // wrote at offset past where hello, world was.
602 }
603
604 // Use TempDir() to make sure we're on a local file system,
605 // so that timings are not distorted by latency and caching.
606 // On NFS, timings can be off due to caching of meta-data on
607 // NFS servers (Issue 848).
608 func TestChtimes(t *testing.T) {
609         f := newFile("TestChtimes", t)
610         defer Remove(f.Name())
611         defer f.Close()
612
613         f.Write([]byte("hello, world\n"))
614         f.Close()
615
616         preStat, err := Stat(f.Name())
617         if err != nil {
618                 t.Fatalf("Stat %s: %s", f.Name(), err)
619         }
620
621         // Move access and modification time back a second
622         const OneSecond = 1e9 // in nanoseconds
623         err = Chtimes(f.Name(), preStat.Atime_ns-OneSecond, preStat.Mtime_ns-OneSecond)
624         if err != nil {
625                 t.Fatalf("Chtimes %s: %s", f.Name(), err)
626         }
627
628         postStat, err := Stat(f.Name())
629         if err != nil {
630                 t.Fatalf("second Stat %s: %s", f.Name(), err)
631         }
632
633         if postStat.Atime_ns >= preStat.Atime_ns {
634                 t.Errorf("Atime_ns didn't go backwards; was=%d, after=%d",
635                         preStat.Atime_ns,
636                         postStat.Atime_ns)
637         }
638
639         if postStat.Mtime_ns >= preStat.Mtime_ns {
640                 t.Errorf("Mtime_ns didn't go backwards; was=%d, after=%d",
641                         preStat.Mtime_ns,
642                         postStat.Mtime_ns)
643         }
644 }
645
646 func TestChdirAndGetwd(t *testing.T) {
647         // TODO(brainman): file.Chdir() is not implemented on windows.
648         if syscall.OS == "windows" {
649                 return
650         }
651         fd, err := Open(".")
652         if err != nil {
653                 t.Fatalf("Open .: %s", err)
654         }
655         // These are chosen carefully not to be symlinks on a Mac
656         // (unlike, say, /var, /etc, and /tmp).
657         dirs := []string{"/", "/usr/bin"}
658         for mode := 0; mode < 2; mode++ {
659                 for _, d := range dirs {
660                         if mode == 0 {
661                                 err = Chdir(d)
662                         } else {
663                                 fd1, err := Open(d)
664                                 if err != nil {
665                                         t.Errorf("Open %s: %s", d, err)
666                                         continue
667                                 }
668                                 err = fd1.Chdir()
669                                 fd1.Close()
670                         }
671                         pwd, err1 := Getwd()
672                         err2 := fd.Chdir()
673                         if err2 != nil {
674                                 // We changed the current directory and cannot go back.
675                                 // Don't let the tests continue; they'll scribble
676                                 // all over some other directory.
677                                 fmt.Fprintf(Stderr, "fchdir back to dot failed: %s\n", err2)
678                                 Exit(1)
679                         }
680                         if err != nil {
681                                 fd.Close()
682                                 t.Fatalf("Chdir %s: %s", d, err)
683                         }
684                         if err1 != nil {
685                                 fd.Close()
686                                 t.Fatalf("Getwd in %s: %s", d, err1)
687                         }
688                         if pwd != d {
689                                 fd.Close()
690                                 t.Fatalf("Getwd returned %q want %q", pwd, d)
691                         }
692                 }
693         }
694         fd.Close()
695 }
696
697 func TestTime(t *testing.T) {
698         // Just want to check that Time() is getting something.
699         // A common failure mode on Darwin is to get 0, 0,
700         // because it returns the time in registers instead of
701         // filling in the structure passed to the system call.
702         // Too bad the compiler doesn't know that
703         // 365.24*86400 is an integer.
704         sec, nsec, err := Time()
705         if sec < (2009-1970)*36524*864 {
706                 t.Errorf("Time() = %d, %d, %s; not plausible", sec, nsec, err)
707         }
708 }
709
710 func TestSeek(t *testing.T) {
711         f := newFile("TestSeek", t)
712         defer Remove(f.Name())
713         defer f.Close()
714
715         const data = "hello, world\n"
716         io.WriteString(f, data)
717
718         type test struct {
719                 in     int64
720                 whence int
721                 out    int64
722         }
723         var tests = []test{
724                 {0, 1, int64(len(data))},
725                 {0, 0, 0},
726                 {5, 0, 5},
727                 {0, 2, int64(len(data))},
728                 {0, 0, 0},
729                 {-1, 2, int64(len(data)) - 1},
730                 {1 << 33, 0, 1 << 33},
731                 {1 << 33, 2, 1<<33 + int64(len(data))},
732         }
733         for i, tt := range tests {
734                 off, err := f.Seek(tt.in, tt.whence)
735                 if off != tt.out || err != nil {
736                         if e, ok := err.(*PathError); ok && e.Error == EINVAL && tt.out > 1<<32 {
737                                 // Reiserfs rejects the big seeks.
738                                 // http://code.google.com/p/go/issues/detail?id=91
739                                 break
740                         }
741                         t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out)
742                 }
743         }
744 }
745
746 type openErrorTest struct {
747         path  string
748         mode  int
749         error Error
750 }
751
752 var openErrorTests = []openErrorTest{
753         {
754                 sfdir + "/no-such-file",
755                 O_RDONLY,
756                 ENOENT,
757         },
758         {
759                 sfdir,
760                 O_WRONLY,
761                 EISDIR,
762         },
763         {
764                 sfdir + "/" + sfname + "/no-such-file",
765                 O_WRONLY,
766                 ENOTDIR,
767         },
768 }
769
770 func TestOpenError(t *testing.T) {
771         for _, tt := range openErrorTests {
772                 f, err := OpenFile(tt.path, tt.mode, 0)
773                 if err == nil {
774                         t.Errorf("Open(%q, %d) succeeded", tt.path, tt.mode)
775                         f.Close()
776                         continue
777                 }
778                 perr, ok := err.(*PathError)
779                 if !ok {
780                         t.Errorf("Open(%q, %d) returns error of %T type; want *os.PathError", tt.path, tt.mode, err)
781                 }
782                 if perr.Error != tt.error {
783                         t.Errorf("Open(%q, %d) = _, %q; want %q", tt.path, tt.mode, perr.Error.String(), tt.error.String())
784                 }
785         }
786 }
787
788 func run(t *testing.T, cmd []string) string {
789         // Run /bin/hostname and collect output.
790         r, w, err := Pipe()
791         if err != nil {
792                 t.Fatal(err)
793         }
794         p, err := StartProcess("/bin/hostname", []string{"hostname"}, &ProcAttr{Files: []*File{nil, w, Stderr}})
795         if err != nil {
796                 t.Fatal(err)
797         }
798         defer p.Release()
799         w.Close()
800
801         var b bytes.Buffer
802         io.Copy(&b, r)
803         p.Wait(0)
804         output := b.String()
805         if n := len(output); n > 0 && output[n-1] == '\n' {
806                 output = output[0 : n-1]
807         }
808         if output == "" {
809                 t.Fatalf("%v produced no output", cmd)
810         }
811
812         return output
813 }
814
815
816 func TestHostname(t *testing.T) {
817         // There is no other way to fetch hostname on windows, but via winapi.
818         if syscall.OS == "windows" {
819                 return
820         }
821         // Check internal Hostname() against the output of /bin/hostname.
822         // Allow that the internal Hostname returns a Fully Qualified Domain Name
823         // and the /bin/hostname only returns the first component
824         hostname, err := Hostname()
825         if err != nil {
826                 t.Fatalf("%v", err)
827         }
828         want := run(t, []string{"/bin/hostname"})
829         if hostname != want {
830                 i := strings.Index(hostname, ".")
831                 if i < 0 || hostname[0:i] != want {
832                         t.Errorf("Hostname() = %q, want %q", hostname, want)
833                 }
834         }
835 }
836
837 func TestReadAt(t *testing.T) {
838         f := newFile("TestReadAt", t)
839         defer Remove(f.Name())
840         defer f.Close()
841
842         const data = "hello, world\n"
843         io.WriteString(f, data)
844
845         b := make([]byte, 5)
846         n, err := f.ReadAt(b, 7)
847         if err != nil || n != len(b) {
848                 t.Fatalf("ReadAt 7: %d, %r", n, err)
849         }
850         if string(b) != "world" {
851                 t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
852         }
853 }
854
855 func TestWriteAt(t *testing.T) {
856         f := newFile("TestWriteAt", t)
857         defer Remove(f.Name())
858         defer f.Close()
859
860         const data = "hello, world\n"
861         io.WriteString(f, data)
862
863         n, err := f.WriteAt([]byte("WORLD"), 7)
864         if err != nil || n != 5 {
865                 t.Fatalf("WriteAt 7: %d, %v", n, err)
866         }
867
868         b, err := ioutil.ReadFile(f.Name())
869         if err != nil {
870                 t.Fatalf("ReadFile %s: %v", f.Name(), err)
871         }
872         if string(b) != "hello, WORLD\n" {
873                 t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
874         }
875 }
876
877 func writeFile(t *testing.T, fname string, flag int, text string) string {
878         f, err := OpenFile(fname, flag, 0666)
879         if err != nil {
880                 t.Fatalf("Open: %v", err)
881         }
882         n, err := io.WriteString(f, text)
883         if err != nil {
884                 t.Fatalf("WriteString: %d, %v", n, err)
885         }
886         f.Close()
887         data, err := ioutil.ReadFile(fname)
888         if err != nil {
889                 t.Fatalf("ReadFile: %v", err)
890         }
891         return string(data)
892 }
893
894 func TestAppend(t *testing.T) {
895         const f = "append.txt"
896         defer Remove(f)
897         s := writeFile(t, f, O_CREATE|O_TRUNC|O_RDWR, "new")
898         if s != "new" {
899                 t.Fatalf("writeFile: have %q want %q", s, "new")
900         }
901         s = writeFile(t, f, O_APPEND|O_RDWR, "|append")
902         if s != "new|append" {
903                 t.Fatalf("writeFile: have %q want %q", s, "new|append")
904         }
905         s = writeFile(t, f, O_CREATE|O_APPEND|O_RDWR, "|append")
906         if s != "new|append|append" {
907                 t.Fatalf("writeFile: have %q want %q", s, "new|append|append")
908         }
909         err := Remove(f)
910         if err != nil {
911                 t.Fatalf("Remove: %v", err)
912         }
913         s = writeFile(t, f, O_CREATE|O_APPEND|O_RDWR, "new&append")
914         if s != "new&append" {
915                 t.Fatalf("writeFile: have %q want %q", s, "new&append")
916         }
917 }
918
919 func TestStatDirWithTrailingSlash(t *testing.T) {
920         // Create new dir, in _test so it will get
921         // cleaned up by make if not by us.
922         path := "_test/_TestStatDirWithSlash_"
923         err := MkdirAll(path, 0777)
924         if err != nil {
925                 t.Fatalf("MkdirAll %q: %s", path, err)
926         }
927         defer RemoveAll(path)
928
929         // Stat of path should succeed.
930         _, err = Stat(path)
931         if err != nil {
932                 t.Fatal("stat failed:", err)
933         }
934
935         // Stat of path+"/" should succeed too.
936         _, err = Stat(path + "/")
937         if err != nil {
938                 t.Fatal("stat failed:", err)
939         }
940 }