gobot.io/x/gobot@v1.16.0/platforms/sphero/sphero_adaptor_test.go (about) 1 package sphero 2 3 import ( 4 "errors" 5 "io" 6 "strings" 7 "testing" 8 9 "gobot.io/x/gobot" 10 "gobot.io/x/gobot/gobottest" 11 ) 12 13 var _ gobot.Adaptor = (*Adaptor)(nil) 14 15 type nullReadWriteCloser struct { 16 testAdaptorRead func(p []byte) (int, error) 17 testAdaptorWrite func(b []byte) (int, error) 18 testAdaptorClose func() error 19 } 20 21 func (n *nullReadWriteCloser) Write(p []byte) (int, error) { 22 return n.testAdaptorWrite(p) 23 } 24 25 func (n *nullReadWriteCloser) Read(b []byte) (int, error) { 26 return n.testAdaptorRead(b) 27 } 28 29 func (n *nullReadWriteCloser) Close() error { 30 return n.testAdaptorClose() 31 } 32 33 func NewNullReadWriteCloser() *nullReadWriteCloser { 34 return &nullReadWriteCloser{ 35 testAdaptorRead: func(p []byte) (int, error) { 36 return len(p), nil 37 }, 38 testAdaptorWrite: func(b []byte) (int, error) { 39 return len(b), nil 40 }, 41 testAdaptorClose: func() error { 42 return nil 43 }, 44 } 45 } 46 47 func initTestSpheroAdaptor() (*Adaptor, *nullReadWriteCloser) { 48 a := NewAdaptor("/dev/null") 49 rwc := NewNullReadWriteCloser() 50 51 a.connect = func(string) (io.ReadWriteCloser, error) { 52 return rwc, nil 53 } 54 return a, rwc 55 } 56 57 func TestSpheroAdaptorName(t *testing.T) { 58 a, _ := initTestSpheroAdaptor() 59 gobottest.Assert(t, strings.HasPrefix(a.Name(), "Sphero"), true) 60 a.SetName("NewName") 61 gobottest.Assert(t, a.Name(), "NewName") 62 } 63 64 func TestSpheroAdaptor(t *testing.T) { 65 a, _ := initTestSpheroAdaptor() 66 gobottest.Assert(t, strings.HasPrefix(a.Name(), "Sphero"), true) 67 gobottest.Assert(t, a.Port(), "/dev/null") 68 } 69 70 func TestSpheroAdaptorReconnect(t *testing.T) { 71 a, _ := initTestSpheroAdaptor() 72 a.Connect() 73 gobottest.Assert(t, a.connected, true) 74 a.Reconnect() 75 gobottest.Assert(t, a.connected, true) 76 a.Disconnect() 77 gobottest.Assert(t, a.connected, false) 78 a.Reconnect() 79 gobottest.Assert(t, a.connected, true) 80 } 81 82 func TestSpheroAdaptorFinalize(t *testing.T) { 83 a, rwc := initTestSpheroAdaptor() 84 a.Connect() 85 gobottest.Assert(t, a.Finalize(), nil) 86 87 rwc.testAdaptorClose = func() error { 88 return errors.New("close error") 89 } 90 91 a.connected = true 92 gobottest.Assert(t, a.Finalize(), errors.New("close error")) 93 } 94 95 func TestSpheroAdaptorConnect(t *testing.T) { 96 a, _ := initTestSpheroAdaptor() 97 gobottest.Assert(t, a.Connect(), nil) 98 99 a.connect = func(string) (io.ReadWriteCloser, error) { 100 return nil, errors.New("connect error") 101 } 102 103 gobottest.Assert(t, a.Connect(), errors.New("connect error")) 104 }