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