OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [os/] [os_test.go] - Blame information for rev 801

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.