github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/uio/reader_test.go (about) 1 // Copyright 2021 the u-root 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 uio 6 7 import ( 8 "os" 9 "path/filepath" 10 "strings" 11 "testing" 12 ) 13 14 func readAndCheck(t *testing.T, want, tmpfileP string) { 15 t.Helper() 16 r := strings.NewReader(want) 17 if err := ReadIntoFile(r, tmpfileP); err != nil { 18 t.Errorf("ReadIntoFile(%v, %s) = %v, want no error", r, tmpfileP, err) 19 } 20 21 got, err := os.ReadFile(tmpfileP) 22 if err != nil { 23 t.Fatalf("os.ReadFile(%s) = %v, want no error", tmpfileP, err) 24 } 25 if want != string(got) { 26 t.Errorf("got: %v, want %s", string(got), want) 27 } 28 } 29 30 func TestReadIntoFile(t *testing.T) { 31 want := "I am the wanted" 32 33 dir := t.TempDir() 34 35 // Write to a file already exist. 36 p := filepath.Join(dir, "uio-out") 37 // Expect net effect to be creating a new empty file: "uio-out". 38 f, err := os.OpenFile(p, os.O_RDONLY|os.O_CREATE|os.O_TRUNC, 0o755) 39 if err != nil { 40 t.Fatal(err) 41 } 42 if err := f.Close(); err != nil { 43 t.Fatal(err) 44 } 45 readAndCheck(t, want, f.Name()) 46 47 // Write to a file that does not exist. 48 p = filepath.Join(dir, "uio-out-not-existing") 49 readAndCheck(t, want, p) 50 51 // Write to an existing file that has pre-existing content. 52 p = filepath.Join(dir, "uio-out-prexist-content") 53 f, err = os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755) 54 if err != nil { 55 t.Fatal(err) 56 } 57 if _, err := f.Write([]byte("temporary file's content")); err != nil { 58 t.Fatal(err) 59 } 60 if err := f.Close(); err != nil { 61 t.Fatal(err) 62 } 63 readAndCheck(t, want, p) 64 }