tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/seesaw/mocki2c_test.go (about) 1 package seesaw 2 3 import ( 4 "encoding/hex" 5 "fmt" 6 "reflect" 7 "testing" 8 ) 9 10 type I2CHandleFunc func(t *testing.T, w, r []byte) error 11 12 // mocki2c implements the drivers.I2C interface and matches a list 13 // of handlers against actual invocations. Useful to test command/reply style I2C devices. 14 type mocki2c struct { 15 addr uint16 16 handlers []I2CHandleFunc 17 t *testing.T 18 } 19 20 func (m *mocki2c) Tx(addr uint16, w, r []byte) error { 21 if addr != m.addr { 22 m.t.Errorf("unexpected i2c address write, want: %v , got %v", m.addr, addr) 23 } 24 if len(m.handlers) == 0 { 25 ws := hex.EncodeToString(w) 26 rs := hex.EncodeToString(r) 27 panic(fmt.Sprintf("no handlers for: addr='%02x' w='%s' r='%s'", byte(addr), ws, rs)) 28 } 29 h := m.handlers[0] 30 m.handlers = m.handlers[1:] 31 return h(m.t, w, r) 32 } 33 34 func newMockDev(t *testing.T, addr uint16, handlers ...I2CHandleFunc) *mocki2c { 35 return &mocki2c{ 36 addr: addr, 37 handlers: handlers, 38 t: t, 39 } 40 } 41 42 func when(expectedWrite, returningRead []byte, returningError error) I2CHandleFunc { 43 return func(t *testing.T, w, r []byte) error { 44 if !reflect.DeepEqual(w, expectedWrite) { 45 t.Errorf("unexpected write. want: %v, got: %v", expectedWrite, w) 46 } 47 48 if len(r) != len(returningRead) { 49 t.Errorf("read buffer has wrong size. want: %v, got: %v", len(returningRead), len(r)) 50 } 51 52 if r != nil { 53 copy(r, returningRead) 54 } 55 return returningError 56 } 57 }