github.com/arduino/arduino-cloud-cli@v0.0.0-20240517070944-e7a449561083/internal/serial/serial_test.go (about) 1 // This file is part of arduino-cloud-cli. 2 // 3 // Copyright (C) 2021 ARDUINO SA (http://www.arduino.cc/) 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published 7 // by the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 package serial 19 20 import ( 21 "bytes" 22 "context" 23 "testing" 24 25 "github.com/arduino/arduino-cloud-cli/internal/serial/mocks" 26 "github.com/stretchr/testify/mock" 27 ) 28 29 func TestSendReceive(t *testing.T) { 30 mockPort := &mocks.Port{} 31 mockSerial := &Serial{mockPort} 32 33 want := []byte{1, 2, 3} 34 resp := encode(Response, want) 35 respIdx := 0 36 37 mockRead := func(msg []uint8) int { 38 if respIdx >= len(resp) { 39 return 0 40 } 41 copy(msg, resp[respIdx:respIdx+2]) 42 respIdx += 2 43 return 2 44 } 45 46 mockPort.On("Write", mock.AnythingOfType("[]uint8")).Return(0, nil) 47 mockPort.On("Read", mock.AnythingOfType("[]uint8")).Return(mockRead, nil) 48 49 res, err := mockSerial.SendReceive(context.TODO(), BeginStorage, []byte{1, 2}) 50 if err != nil { 51 t.Error(err) 52 } 53 54 if !bytes.Equal(res, want) { 55 t.Errorf("Expected %v but received %v", want, res) 56 } 57 } 58 59 func TestSend(t *testing.T) { 60 mockPort := &mocks.Port{} 61 mockSerial := &Serial{mockPort} 62 mockPort.On("Write", mock.AnythingOfType("[]uint8")).Return(0, nil) 63 64 payload := []byte{1, 2} 65 cmd := SetDay 66 want := []byte{msgStart[0], msgStart[1], 1, 0, 5, 10, 1, 2, 143, 124, msgEnd[0], msgEnd[1]} 67 68 err := mockSerial.Send(context.TODO(), cmd, payload) 69 if err != nil { 70 t.Error(err) 71 } 72 73 mockPort.AssertCalled(t, "Write", want) 74 } 75 76 func TestEncode(t *testing.T) { 77 tests := []struct { 78 name string 79 msg []byte 80 want []byte 81 }{ 82 { 83 name: "begin-storage", 84 msg: []byte{byte(BeginStorage)}, 85 want: []byte{msgStart[0], msgStart[1], 1, 0, 3, 6, 0x95, 0x4e, msgEnd[0], msgEnd[1]}, 86 }, 87 88 { 89 name: "set-year", 90 msg: append([]byte{byte(SetYear)}, []byte("2021")...), 91 want: []byte{msgStart[0], msgStart[1], 1, 0, 7, 0x8, 0x32, 0x30, 0x32, 0x31, 0xc3, 0x65, msgEnd[0], msgEnd[1]}, 92 }, 93 } 94 for _, tt := range tests { 95 t.Run(tt.name, func(t *testing.T) { 96 got := encode(Cmd, tt.msg) 97 if !bytes.Equal(tt.want, got) { 98 t.Errorf("Expected %v, received %v", tt.want, got) 99 } 100 }) 101 } 102 }