github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/cmos/cmos_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 //go:build (linux && amd64) || (linux && 386) 6 // +build linux,amd64 linux,386 7 8 package cmos 9 10 import ( 11 "bytes" 12 "io" 13 "os" 14 "strings" 15 "testing" 16 17 "github.com/mvdan/u-root-coreutils/pkg/testutil" 18 19 "github.com/mvdan/u-root-coreutils/pkg/memio" 20 ) 21 22 func newMock(errStr string, inBuf, outBuf io.ReadWriter, f *os.File) *Chip { 23 memPort := memio.NewMemIOPort(f) 24 return &Chip{ 25 PortReadWriter: &memio.LinuxPort{ 26 ReadWriteCloser: memPort, 27 }, 28 } 29 } 30 31 func TestCMOS(t *testing.T) { 32 for _, tt := range []struct { 33 name string 34 addr memio.Uint8 35 writeData, readData memio.UintN 36 err string 37 }{ 38 { 39 name: "uint8", 40 addr: 0x10, 41 writeData: &[]memio.Uint8{0x12}[0], 42 }, 43 { 44 name: "uint16", 45 addr: 0x20, 46 writeData: &[]memio.Uint16{0x1234}[0], 47 }, 48 { 49 name: "uint32", 50 addr: 0x30, 51 writeData: &[]memio.Uint32{0x12345678}[0], 52 }, 53 { 54 name: "uint64", 55 addr: 0x40, 56 writeData: &[]memio.Uint64{0x1234567890abcdef}[0], 57 err: "/dev/port data must be 8 bits on Linux", 58 }, 59 } { 60 t.Run(tt.name, func(t *testing.T) { 61 tmpDir := t.TempDir() 62 f, err := os.CreateTemp(tmpDir, "testfile-") 63 if err != nil { 64 t.Errorf(`os.CreateTemp(tmpDir, "testfile-") = f, %q, not f, nil`, err) 65 } 66 data := make([]byte, 10000) 67 if _, err := f.Write(data); err != nil { 68 t.Errorf(`f.Write(data) = _, %q, not _, nil`, err) 69 } 70 var in, out bytes.Buffer 71 c := newMock(tt.err, &in, &out, f) 72 // Set internal function to dummy but save old state for reset later 73 if err := c.Write(tt.addr, tt.writeData); err != nil { 74 if !strings.Contains(err.Error(), tt.err) { 75 t.Errorf(`c.Write(tt.addr, tt.writeData) = %q, not nil`, err) 76 } 77 } 78 err = c.Read(tt.addr, tt.readData) 79 if err != nil { 80 if !strings.Contains(err.Error(), tt.err) { 81 t.Errorf(`c.Read(tt.addr, tt.readData) = %q, not nil`, err) 82 } 83 } 84 // We can only progress if error is nil. 85 if err == nil { 86 got := in.String() 87 want := tt.writeData.String() 88 if got != want { 89 t.Errorf("%s, not %s", want, got) 90 } 91 } 92 }) 93 } 94 } 95 96 // This is just for coverage percentage. This test does nothing of any other value. 97 func TestNew(t *testing.T) { 98 testutil.SkipIfNotRoot(t) 99 if _, err := New(); err != nil { 100 t.Errorf(`New() = %q, not nil`, err) 101 } 102 }