github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/memio/io_test.go (about) 1 // Copyright 2012-2019 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 memio 6 7 import ( 8 "fmt" 9 "io/ioutil" 10 "log" 11 "os" 12 "reflect" 13 "testing" 14 ) 15 16 var tests = []struct { 17 name string 18 addr int64 19 writeData, readData UintN 20 err string 21 }{ 22 { 23 name: "uint8", 24 addr: 0x10, 25 writeData: &[]Uint8{0x12}[0], 26 readData: new(Uint8), 27 }, 28 { 29 name: "uint16", 30 addr: 0x20, 31 writeData: &[]Uint16{0x1234}[0], 32 readData: new(Uint16), 33 }, 34 { 35 name: "uint32", 36 addr: 0x30, 37 writeData: &[]Uint32{0x12345678}[0], 38 readData: new(Uint32), 39 }, 40 { 41 name: "uint64", 42 addr: 0x40, 43 writeData: &[]Uint64{0x1234567890abcdef}[0], 44 readData: new(Uint64), 45 }, 46 { 47 name: "byte slice", 48 addr: 0x50, 49 writeData: &[]ByteSlice{[]byte("Hello")}[0], 50 readData: &[]ByteSlice{make([]byte, 5)}[0], 51 }, 52 } 53 54 func TestIO(t *testing.T) { 55 for _, tt := range tests { 56 t.Run(fmt.Sprintf(tt.name), func(t *testing.T) { 57 tmpFile, err := ioutil.TempFile("", "io_test") 58 if err != nil { 59 t.Fatal(err) 60 } 61 tmpFile.Write(make([]byte, 10000)) 62 tmpFile.Close() 63 defer os.Remove(tmpFile.Name()) 64 memPath = tmpFile.Name() 65 defer func() { memPath = "/dev/mem" }() 66 67 // Write to the file. 68 if err := Write(tt.addr, tt.writeData); err != nil { 69 if err.Error() == tt.err { 70 return 71 } 72 t.Fatal(err) 73 } 74 75 // Read back the value. 76 if err := Read(tt.addr, tt.readData); err != nil { 77 if err.Error() == tt.err { 78 return 79 } 80 t.Fatal(err) 81 } 82 83 want := tt.writeData 84 got := tt.readData 85 if !reflect.DeepEqual(want, got) { 86 t.Fatalf("Write(%#016x, %v) = %v; want %v", 87 tt.addr, want, got, want) 88 } 89 }) 90 } 91 } 92 93 func ExampleRead() { 94 var data Uint32 95 if err := Read(0x1000000, &data); err != nil { 96 log.Fatal(err) 97 } 98 log.Printf("%v\n", data) 99 } 100 101 func ExampleWrite() { 102 data := Uint32(42) 103 if err := Write(0x1000000, &data); err != nil { 104 log.Fatal(err) 105 } 106 }