github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/os/read_test.go (about) 1 //go:build !baremetal && !js && !wasip1 2 3 // Copyright 2009 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package os_test 8 9 import ( 10 "bytes" 11 . "os" 12 "path/filepath" 13 "testing" 14 ) 15 16 func checkNamedSize(t *testing.T, path string, size int64) { 17 // TODO: this statement fails on wasi, possibly it objects to reading Stat on a symlink 18 dir, err := Stat(path) 19 if err != nil { 20 t.Fatalf("Stat %q (looking for size %d): %s", path, size, err) 21 return 22 } 23 if dir.Size() != size { 24 t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size) 25 } 26 } 27 28 func TestReadFile(t *testing.T) { 29 filename := "rumpelstilzchen" 30 contents, err := ReadFile(filename) 31 if err == nil { 32 t.Fatalf("ReadFile %s: error expected, none found", filename) 33 } 34 35 filename = "read_test.go" 36 contents, err = ReadFile(filename) 37 if err != nil { 38 t.Fatalf("ReadFile %s: %v", filename, err) 39 } 40 41 checkNamedSize(t, filename, int64(len(contents))) 42 } 43 44 func TestWriteFile(t *testing.T) { 45 f, err := CreateTemp("", "ioutil-test") 46 if err != nil { 47 t.Fatal(err) 48 } 49 defer f.Close() 50 defer Remove(f.Name()) 51 52 msg := "Programming today is a race between software engineers striving to " + 53 "build bigger and better idiot-proof programs, and the Universe trying " + 54 "to produce bigger and better idiots. So far, the Universe is winning." 55 56 if err := WriteFile(f.Name(), []byte(msg), 0644); err != nil { 57 t.Fatalf("WriteFile %s: %v", f.Name(), err) 58 } 59 60 data, err := ReadFile(f.Name()) 61 if err != nil { 62 t.Fatalf("ReadFile %s: %v", f.Name(), err) 63 } 64 65 if string(data) != msg { 66 t.Fatalf("ReadFile: wrong data:\nhave %q\nwant %q", string(data), msg) 67 } 68 } 69 70 func TestReadOnlyWriteFile(t *testing.T) { 71 // TODO: also skip on wasi, where file permissions are ignored 72 if Getuid() == 0 { 73 t.Skipf("Root can write to read-only files anyway, so skip the read-only test.") 74 } 75 76 // We don't want to use CreateTemp directly, since that opens a file for us as 0600. 77 tempDir, err := MkdirTemp("", t.Name()) 78 if err != nil { 79 t.Fatal(err) 80 } 81 defer RemoveAll(tempDir) 82 filename := filepath.Join(tempDir, "blurp.txt") 83 84 shmorp := []byte("shmorp") 85 florp := []byte("florp") 86 err = WriteFile(filename, shmorp, 0444) 87 if err != nil { 88 t.Fatalf("WriteFile %s: %v", filename, err) 89 } 90 err = WriteFile(filename, florp, 0444) 91 if err == nil { 92 t.Fatalf("Expected an error when writing to read-only file %s", filename) 93 } 94 got, err := ReadFile(filename) 95 if err != nil { 96 t.Fatalf("ReadFile %s: %v", filename, err) 97 } 98 if !bytes.Equal(got, shmorp) { 99 t.Fatalf("want %s, got %s", shmorp, got) 100 } 101 }