github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/internal/command/envelope_test.go (about) 1 package command 2 3 import ( 4 "encoding/json" 5 "errors" 6 "testing" 7 8 "github.com/stretchr/testify/require" 9 ) 10 11 func TestUnpack(t *testing.T) { 12 tests := []struct { 13 name string 14 envelope Envelope 15 expected Command 16 expectedError error 17 }{ 18 {"status command", Envelope{Type: StatusType}, &StatusCommand{}, nil}, 19 {"outlet command", Envelope{Type: OutletType, Data: rawMessage(`{"outletID":"foo","action":"toggle"}`)}, &OutletCommand{OutletID: "foo", Action: "toggle"}, nil}, 20 {"group command", Envelope{Type: GroupType, Data: rawMessage(`{"groupID":"foo","action":"on"}`)}, &GroupCommand{GroupID: "foo", Action: "on"}, nil}, 21 {"interval command", Envelope{Type: IntervalType, Data: rawMessage(`{"outletID":"foo","action":"create"}`)}, &IntervalCommand{OutletID: "foo", Action: "create"}, nil}, 22 // Error cases. 23 {"unknown command", Envelope{Type: Type("unknown")}, nil, errors.New(`unknown command type "unknown"`)}, 24 {"invalid data", Envelope{Type: OutletType, Data: rawMessage(`{`)}, nil, errors.New(`failed to unmarshal "outlet" command data: unexpected end of JSON input`)}, 25 } 26 27 for _, test := range tests { 28 t.Run(test.name, func(t *testing.T) { 29 cmd, err := Unpack(test.envelope) 30 if test.expectedError != nil { 31 require.Error(t, err) 32 require.Equal(t, test.expectedError.Error(), err.Error()) 33 } else { 34 require.NoError(t, err) 35 require.Equal(t, test.expected, cmd) 36 } 37 }) 38 } 39 } 40 41 func rawMessage(s string) *json.RawMessage { 42 raw := json.RawMessage(s) 43 return &raw 44 }