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.
15 func checkSize(t
*testing
.T
, path
string, size
int64) {
16 dir
, err
:= os
.Stat(path
)
18 t
.Fatalf("Stat %q (looking for size %d): %s", path
, size
, err
)
20 if dir
.Size() != size
{
21 t
.Errorf("Stat %q: size %d want %d", path
, dir
.Size(), size
)
25 func TestReadFile(t
*testing
.T
) {
26 filename
:= "rumpelstilzchen"
27 contents
, err
:= ReadFile(filename
)
29 t
.Fatalf("ReadFile %s: error expected, none found", filename
)
32 filename
= "ioutil_test.go"
33 contents
, err
= ReadFile(filename
)
35 t
.Fatalf("ReadFile %s: %v", filename
, err
)
38 checkSize(t
, filename
, int64(len(contents
)))
41 func TestWriteFile(t
*testing
.T
) {
42 f
, err
:= TempFile("", "ioutil-test")
47 data
:= "Programming today is a race between software engineers striving to " +
48 "build bigger and better idiot-proof programs, and the Universe trying " +
49 "to produce bigger and better idiots. So far, the Universe is winning."
51 if err
:= WriteFile(filename
, []byte(data
), 0644); err
!= nil {
52 t
.Fatalf("WriteFile %s: %v", filename
, err
)
55 contents
, err
:= ReadFile(filename
)
57 t
.Fatalf("ReadFile %s: %v", filename
, err
)
60 if string(contents
) != data
{
61 t
.Fatalf("contents = %q\nexpected = %q", string(contents
), data
)
66 os
.Remove(filename
) // ignore error
69 func TestReadOnlyWriteFile(t
*testing
.T
) {
71 t
.Skipf("Root can write to read-only files anyway, so skip the read-only test.")
74 // We don't want to use TempFile directly, since that opens a file for us as 0600.
75 tempDir
, err
:= TempDir("", t
.Name())
77 t
.Fatalf("TempDir %s: %v", t
.Name(), err
)
79 defer os
.RemoveAll(tempDir
)
80 filename
:= filepath
.Join(tempDir
, "blurp.txt")
82 shmorp
:= []byte("shmorp")
83 florp
:= []byte("florp")
84 err
= WriteFile(filename
, shmorp
, 0444)
86 t
.Fatalf("WriteFile %s: %v", filename
, err
)
88 err
= WriteFile(filename
, florp
, 0444)
90 t
.Fatalf("Expected an error when writing to read-only file %s", filename
)
92 got
, err
:= ReadFile(filename
)
94 t
.Fatalf("ReadFile %s: %v", filename
, err
)
96 if !bytes
.Equal(got
, shmorp
) {
97 t
.Fatalf("want %s, got %s", shmorp
, got
)
101 func TestReadDir(t
*testing
.T
) {
102 dirname
:= "rumpelstilzchen"
103 _
, err
:= ReadDir(dirname
)
105 t
.Fatalf("ReadDir %s: error expected, none found", dirname
)
108 /* Does not work in gccgo testing environment.
110 list, err := ReadDir(dirname)
112 t.Fatalf("ReadDir %s: %v", dirname, err)
117 for _, dir := range list {
119 case !dir.IsDir() && dir.Name() == "io_test.go":
121 case dir.IsDir() && dir.Name() == "ioutil":
126 t.Fatalf("ReadDir %s: io_test.go file not found", dirname)
129 t.Fatalf("ReadDir %s: ioutil directory not found", dirname)