gobot.io/x/gobot@v1.16.0/drivers/i2c/grovepi_driver_test.go (about) 1 package i2c 2 3 import ( 4 "gobot.io/x/gobot" 5 "gobot.io/x/gobot/drivers/aio" 6 "gobot.io/x/gobot/drivers/gpio" 7 "gobot.io/x/gobot/gobottest" 8 "strings" 9 "testing" 10 ) 11 12 var _ gobot.Driver = (*GrovePiDriver)(nil) 13 14 // must implement the DigitalReader interface 15 var _ gpio.DigitalReader = (*GrovePiDriver)(nil) 16 17 // must implement the DigitalWriter interface 18 var _ gpio.DigitalWriter = (*GrovePiDriver)(nil) 19 20 // must implement the AnalogReader interface 21 var _ aio.AnalogReader = (*GrovePiDriver)(nil) 22 23 // must implement the Adaptor interface 24 var _ gobot.Adaptor = (*GrovePiDriver)(nil) 25 26 func initTestGrovePiDriver() (driver *GrovePiDriver, adaptor *i2cTestAdaptor) { 27 return initGrovePiDriverWithStubbedAdaptor() 28 } 29 30 func initGrovePiDriverWithStubbedAdaptor() (*GrovePiDriver, *i2cTestAdaptor) { 31 adaptor := newI2cTestAdaptor() 32 return NewGrovePiDriver(adaptor), adaptor 33 } 34 35 func TestGrovePiDriverName(t *testing.T) { 36 g, _ := initTestGrovePiDriver() 37 gobottest.Refute(t, g.Connection(), nil) 38 gobottest.Assert(t, strings.HasPrefix(g.Name(), "GrovePi"), true) 39 } 40 41 func TestGrovePiDriverOptions(t *testing.T) { 42 g := NewGrovePiDriver(newI2cTestAdaptor(), WithBus(2)) 43 gobottest.Assert(t, g.GetBusOrDefault(1), 2) 44 } 45 46 func TestGrovePiDriver_UltrasonicRead(t *testing.T) { 47 g, a := initTestGrovePiDriver() 48 g.Start() 49 50 fakePin := byte(1) 51 fakeI2cResponse := []byte{CommandReadUltrasonic, 1, 2} 52 53 expectedCommand := []byte{CommandReadUltrasonic, fakePin, 0, 0} 54 expectedResult := 257 55 56 resultCommand := make([]byte, 3) 57 58 // capture i2c command 59 a.i2cWriteImpl = func(bytes []byte) (i int, e error) { 60 resultCommand = bytes 61 return len(bytes), nil 62 } 63 64 // fake i2c response 65 a.i2cReadImpl = func(bytes []byte) (i int, e error) { 66 bytes[0] = fakeI2cResponse[0] 67 bytes[1] = fakeI2cResponse[1] 68 bytes[2] = fakeI2cResponse[2] 69 return len(bytes), nil 70 } 71 72 result, _ := g.readUltrasonic(fakePin, 10) 73 74 gobottest.Assert(t, resultCommand, expectedCommand) 75 gobottest.Assert(t, result, expectedResult) 76 } 77 78 // Methods 79 func TestGrovePiDriverStart(t *testing.T) { 80 g, _ := initTestGrovePiDriver() 81 82 gobottest.Assert(t, g.Start(), nil) 83 } 84 85 func TestGrovePiDrivergetPin(t *testing.T) { 86 gobottest.Assert(t, getPin("a1"), "1") 87 gobottest.Assert(t, getPin("A16"), "16") 88 gobottest.Assert(t, getPin("D3"), "3") 89 gobottest.Assert(t, getPin("d22"), "22") 90 gobottest.Assert(t, getPin("22"), "22") 91 }