From 7b2514ce76e3ad739570105655613854557debde Mon Sep 17 00:00:00 2001 From: Dave Chen Date: Thu, 10 Oct 2019 15:08:33 +0800 Subject: [PATCH] WIP: test for e2e test. --- .travis.yml | 131 +- Makefile | 4 +- edge/Makefile | 1 + edge/pkg/devicetwin/dtmanager/communicate.go | 21 +- .../devicetwin/dtmanager/communicate_test.go | 506 +++---- edge/pkg/devicetwin/dtmanager/device_test.go | 492 ------- .../devicetwin/dtmanager/membership_test.go | 363 ----- edge/pkg/devicetwin/dtmanager/twin_test.go | 1262 ----------------- edge/test.sh | 23 + pkg/util/flag/flags.go | 4 +- 10 files changed, 368 insertions(+), 2439 deletions(-) delete mode 100644 edge/pkg/devicetwin/dtmanager/device_test.go delete mode 100644 edge/pkg/devicetwin/dtmanager/membership_test.go delete mode 100644 edge/pkg/devicetwin/dtmanager/twin_test.go create mode 100644 edge/test.sh diff --git a/.travis.yml b/.travis.yml index cd4df433ee2..2ab3e4211a7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,13 +10,13 @@ services: go: - 1.12 -before_install: - - | - if ! git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qvE '(\.md)|(\.png)|(\.pdf)|(\.html)|^(LICENSE)|^(docs)' - then - echo "Only doc files were updated, skip running the CI." - exit - fi + #before_install: + # - | + # if ! git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qvE '(\.md)|(\.png)|(\.pdf)|(\.html)|^(LICENSE)|^(docs)' + # then + # echo "Only doc files were updated, skip running the CI." + # exit + # fi before_script: - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | BINARY=golangci-lint sh -s -- -d -b $(go env GOPATH)/bin v1.20.0 @@ -36,71 +36,74 @@ install: true jobs: include: - - stage: "Verify vendor" - script: make verify - name: "check if the vendor is up to date" + # - stage: "Verify vendor" + # script: make verify + # name: "check if the vendor is up to date" - - stage: "Test lint" - script: make cloud_lint - name: "cloud_lint" - - script: make bluetoothdevice_lint - name: "bluetooth_device_lint" - - script: make keadm_lint - name: "keadm_lint" - - script: make edge_lint - name: "edge_lint" + # - stage: "Test lint" + # script: make cloud_lint + # name: "cloud_lint" + # - script: make bluetoothdevice_lint + # name: "bluetooth_device_lint" + # - script: make keadm_lint + # name: "keadm_lint" + # - script: make edge_lint + # name: "edge_lint" - - stage: "Test Build" - script: make - arch: amd64 - name: "builds cloud and edge components on amd64" - - script: make bluetoothdevice - arch: amd64 - name: "build bluetooth_device on amd64" - - script: make edge_small_build - arch: amd64 - name: "build small edge version on amd64" - - script: make edge_cross_build - name: "cross build edge" - - script: make edge_cross_build_v7 - name: "cross build edge for armv7" - - script: make edgesite_cross_build - name: "cross build edgesite" - - script: make edgesite_cross_build_v7 - name: "cross build edgeite for armv7" + # - stage: "Test Build" + # script: make + # arch: amd64 + # name: "builds cloud and edge components on amd64" + # - script: make bluetoothdevice + # arch: amd64 + # name: "build bluetooth_device on amd64" + # - script: make edge_small_build + # arch: amd64 + # name: "build small edge version on amd64" + # - script: make edge_cross_build + # name: "cross build edge" + # - script: make edge_cross_build_v7 + # name: "cross build edge for armv7" + # - script: make edgesite_cross_build + # name: "cross build edgesite" + # - script: make edgesite_cross_build_v7 + # name: "cross build edgeite for armv7" - stage: "unit tests" script: make edge_test arch: amd64 name: "unit test edge on amd64" - - script: make edge_integration_test - arch: amd64 - name: "integration test edgeo on amd64" - - script: make cloud_test - arch: amd64 - name: "unit test cloud on amd64" - - - stage: "e2e tests" - script: make e2e_test - arch: amd64 - name: "e2e_test on amd64" + - script: make edge_test + arch: arm64 + name: "unit test edge on arm64" + # - script: make edge_integration_test + # arch: amd64 + # name: "integration test edge on amd64" + # - script: make cloud_test + # arch: amd64 + # name: "unit test cloud on amd64" - - stage: "build docker images" - script: make cloudimage - arch: amd64 - name: "build cloudimage on amd64" - - script: make admissionimage - arch: amd64 - name: "build admission image on amd64" - - script: make edgeimage ARCH="amd64" - arch: amd64 - name: "build edge image on amd64" - - script: make edgesiteimage ARCH="amd64" - arch: amd64 - name: "build edgesite image on amd64" - - script: make bluetoothdevice_image - arch: amd64 - name: "build bluetoothdevice image on amd64" + # - stage: "e2e tests" + # script: make e2e_test + # arch: amd64 + # name: "e2e_test on amd64" + # + # - stage: "build docker images" + # script: make cloudimage + # arch: amd64 + # name: "build cloudimage on amd64" + # - script: make admissionimage + # arch: amd64 + # name: "build admission image on amd64" + # - script: make edgeimage ARCH="amd64" + # arch: amd64 + # name: "build edge image on amd64" + # - script: make edgesiteimage ARCH="amd64" + # arch: amd64 + # name: "build edgesite image on amd64" + # - script: make bluetoothdevice_image + # arch: amd64 + # name: "build bluetoothdevice image on amd64" # TODO: When the arm support of travis becomes stable, we will uncomment these cases. # - script: make cloudimage # arch: arm64 diff --git a/Makefile b/Makefile index 2783ef674bc..1f71411fbe7 100644 --- a/Makefile +++ b/Makefile @@ -99,7 +99,8 @@ keadm_lint: QEMU_ARCH ?= x86_64 ARCH ?= amd64 -IMAGE_TAG ?= $(shell git describe --tags) +#IMAGE_TAG ?= $(shell git describe --tags) +IMAGE_TAG ?= latest .PHONY: cloudimage cloudimage: @@ -126,6 +127,7 @@ edgeimage: .PHONY: edgesiteimage edgesiteimage: + $(info ARCH is $(ARCH)) mkdir -p ./build/edgesite/tmp rm -rf ./build/edgesite/tmp/* curl -L -o ./build/edgesite/tmp/qemu-${QEMU_ARCH}-static.tar.gz https://github.com/multiarch/qemu-user-static/releases/download/v3.0.0/qemu-${QEMU_ARCH}-static.tar.gz diff --git a/edge/Makefile b/edge/Makefile index 4c423adb05b..94f757571aa 100644 --- a/edge/Makefile +++ b/edge/Makefile @@ -20,6 +20,7 @@ endif export GOARCHAIUS_CONFIG_PATH=$(CURDIR) test: find ${TEST_DIR} -name "*_test.go"| xargs -I{} dirname {} | uniq | xargs -I{} go test ${T} {} + #bash test.sh # lint .PHONY: lint diff --git a/edge/pkg/devicetwin/dtmanager/communicate.go b/edge/pkg/devicetwin/dtmanager/communicate.go index 4a2ff739ce0..07d608c715a 100644 --- a/edge/pkg/devicetwin/dtmanager/communicate.go +++ b/edge/pkg/devicetwin/dtmanager/communicate.go @@ -37,13 +37,26 @@ func (cw CommWorker) Start() { return } if dtMsg, isDTMessage := msg.(*dttype.DTMessage); isDTMessage { + klog.Infof("Dave!!! action is: %v", dtMsg.Action) + klog.Errorf("Dave!!! action is: %v", dtMsg.Action) + klog.Infof("Dave!!! init value is: %v", msg) + klog.Errorf("Dave!!! init value is: %v", msg) + klog.Infof("Dave!!! check the value in the map: %v", ActionCallBack[dtMsg.Action]) + klog.Errorf("Dave!!! check the value in the map: %v", ActionCallBack[dtMsg.Action]) + for key := range ActionCallBack { + klog.Infof("Dave!!! value in the callback: %v", key) + klog.Errorf("Dave!!! value in the callback: %v", key) + } if fn, exist := ActionCallBack[dtMsg.Action]; exist { + klog.Errorf("Dave!!!find it: %v", fn) _, err := fn(cw.DTContexts, dtMsg.Identity, dtMsg.Msg) if err != nil { + klog.Error("Dave!!!function called but found a error") klog.Errorf("CommModule deal %s event failed: %v", dtMsg.Action, err) } } else { - klog.Errorf("CommModule deal %s event failed, not found callback", dtMsg.Action) + klog.Error("Dave!!!cannot find it") + klog.Errorf("CommModule deal %v event failed, not found callback", dtMsg.Action) } } @@ -81,7 +94,11 @@ func dealSendToCloud(context *dtcontext.DTContext, resource string, msg interfac if !ok { return nil, errors.New("msg not Message type") } - context.ModulesContext.Send(dtcommon.HubModule, *message) + klog.Infof("Dave!!! content of message is: %v", message.GetContent()) + klog.Errorf("Dave!!! content of message is: %v", message.GetContent()) + klog.Infof("Dave!!! ID of message is: %v", message.GetID()) + klog.Errorf("Dave!!! ID of message is: %v", message.GetID()) + context.ModulesContext.Send(dtcommon.HubModule, *message) //Dave: have something wrong to set to DB? msgID := message.GetID() context.ConfirmMap.Store(msgID, &dttype.DTMessage{Msg: message, Action: dtcommon.SendToCloud, Type: dtcommon.CommModule}) return nil, nil diff --git a/edge/pkg/devicetwin/dtmanager/communicate_test.go b/edge/pkg/devicetwin/dtmanager/communicate_test.go index d1f6268e820..caf76bd3ee2 100644 --- a/edge/pkg/devicetwin/dtmanager/communicate_test.go +++ b/edge/pkg/devicetwin/dtmanager/communicate_test.go @@ -17,14 +17,14 @@ limitations under the License. package dtmanager import ( - "errors" - "reflect" + //"errors" + //"reflect" "testing" "time" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - cloudconn "github.com/kubeedge/kubeedge/edge/pkg/common/cloudconnection" + //cloudconn "github.com/kubeedge/kubeedge/edge/pkg/common/cloudconnection" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" @@ -37,8 +37,8 @@ func TestStartAction(t *testing.T) { dtContextStateConnected.State = dtcommon.Connected receiveChanActionPresent := make(chan interface{}, 1) receiveChanActionPresent <- &dttype.DTMessage{Action: dtcommon.SendToCloud, Identity: "identity", Msg: &model.Message{Header: model.MessageHeader{ID: "message"}, Content: "msg"}} - receiveChanActionNotPresent := make(chan interface{}, 1) - receiveChanActionNotPresent <- &dttype.DTMessage{Action: "action", Identity: "identity", Msg: &model.Message{Content: "msg"}} + //receiveChanActionNotPresent := make(chan interface{}, 1) + //receiveChanActionNotPresent <- &dttype.DTMessage{Action: "action", Identity: "identity", Msg: &model.Message{Content: "msg"}} tests := []struct { name string Worker Worker @@ -50,13 +50,13 @@ func TestStartAction(t *testing.T) { DTContexts: dtContextStateConnected, }, }, - { - name: "StartTest-ActionNotPresentInActionCallback", - Worker: Worker{ - ReceiverChan: receiveChanActionNotPresent, - DTContexts: dtContextStateConnected, - }, - }, + //{ + // name: "StartTest-ActionNotPresentInActionCallback", + // Worker: Worker{ + // ReceiverChan: receiveChanActionNotPresent, + // DTContexts: dtContextStateConnected, + // }, + //}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -76,244 +76,244 @@ func TestStartAction(t *testing.T) { } // TestStartHeartBeat is function to test Start() when value is passed in HeartBeatChan. -func TestStartHeartBeat(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContexts, _ := dtcontext.InitDTContext(mainContext) - heartChanStop := make(chan interface{}, 1) - heartChanPing := make(chan interface{}, 1) - heartChanStop <- "stop" - heartChanPing <- "ping" - tests := []struct { - name string - Worker Worker - Group string - }{ - { - name: "StartTest-PingInHeartBeatChannel", - Worker: Worker{ - HeartBeatChan: heartChanPing, - DTContexts: dtContexts, - }, - Group: "group", - }, - { - name: "StartTest-StopInHeartBeatChannel", - Worker: Worker{ - HeartBeatChan: heartChanStop, - DTContexts: dtContexts, - }, - Group: "group", - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - cw := CommWorker{ - Worker: test.Worker, - Group: test.Group, - } - go cw.Start() - time.Sleep(1 * time.Millisecond) - if test.Worker.HeartBeatChan == heartChanPing { - _, exist := test.Worker.DTContexts.ModulesHealth.Load("group") - if !exist { - t.Errorf("Start Failed to add module in context") - } - } - }) - } -} - -// TestDealSendToEdge is function to test dealsendToedge(). -func TestDealSendToEdge(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContexts, _ := dtcontext.InitDTContext(mainContext) - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - }{ - { - name: "dealSendToEdgeTest", - context: dtContexts, - msg: &model.Message{}, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - dealSendToEdge(test.context, test.resource, test.msg) - }) - } -} - -// TestDealSendToCloud is function to test dealSendToCloud(). -func TestDealSendToCloud(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContextStateDisconnected, _ := dtcontext.InitDTContext(mainContext) - dtContextStateConnected, _ := dtcontext.InitDTContext(mainContext) - dtContextStateConnected.State = dtcommon.Connected - msg := &model.Message{Header: model.MessageHeader{ID: "message"}} - expectedMessage := &dttype.DTMessage{Msg: msg, Action: dtcommon.SendToCloud, Type: dtcommon.CommModule} - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - wantErr error - }{ - { - name: "dealSendToCloudTest-StateDisconnected", - context: dtContextStateDisconnected, - msg: "", - wantErr: nil, - }, - { - name: "dealSendToCloudTest-StateConnected", - context: dtContextStateConnected, - msg: "", - wantErr: errors.New("msg not Message type"), - }, - { - name: "dealSendToCloudTest-ActualMsg", - context: dtContextStateConnected, - msg: msg, - wantErr: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - _, err := dealSendToCloud(test.context, test.resource, test.msg) - if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("dealSendToCloud() error = %v, wantErr %v", err, test.wantErr) - return - } - // Testing whether the message is properly stored in ConfirmMap of context when correct message is passed - if err == nil && test.context.State == dtcommon.Connected { - gotMsg, exist := test.context.ConfirmMap.Load("message") - if !exist { - t.Errorf("dealSendToCloud() failed to store message in ConfirmMap") - return - } - if !reflect.DeepEqual(expectedMessage, gotMsg) { - t.Errorf("dealSendToCloud() failed due to wrong gotMsg in ConfirmMap Got =%v Want=%v", test.msg, gotMsg) - } - } - }) - } -} - -// TestDealLifeCycle is function to test dealLifeCycle(). -func TestDealLifeCycle(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContext, _ := dtcontext.InitDTContext(mainContext) - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - wantErr error - }{ - { - name: "dealLifeCycleTest-WrongMessageFormat", - context: dtContext, - msg: "", - wantErr: errors.New("msg not Message type"), - }, - { - name: "dealLifeCycleTest-CloudConnected", - context: dtContext, - msg: &model.Message{Content: cloudconn.CloudConnected}, - wantErr: nil, - }, - { - name: "dealLifeCycleTest-CloudNotConnected", - context: dtContext, - msg: &model.Message{Content: cloudconn.CloudDisconnected}, - wantErr: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - _, err := dealLifeCycle(test.context, test.resource, test.msg) - if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("dealLifeCycle() error = %v, wantErr %v", err, test.wantErr) - } - }) - } -} - -// TestDealConfirm is function to test dealConfirm(). -func TestDealConfirm(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContext, _ := dtcontext.InitDTContext(mainContext) - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - wantErr error - }{ - { - name: "dealConfirmTest-WrongMsg", - context: dtContext, - msg: "", - wantErr: errors.New("CommModule deal confirm, type not correct"), - }, - { - name: "dealConfirmTest-CorrectMsg", - context: dtContext, - msg: &model.Message{Header: model.MessageHeader{ID: "id", ParentID: "parentId"}}, - wantErr: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - _, err := dealConfirm(test.context, test.resource, test.msg) - if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("dealConfirm() error = %v, wantErr %v", err, test.wantErr) - return - } - if err == nil { - _, exist := test.context.ConfirmMap.Load("parentId") - if exist { - t.Errorf("dealConfirm failed() ParentMessageId still present in context ConfirmMap") - } - } - }) - } -} - -// TestCheckConfirm is function to test checkConfirm(). -func TestCheckConfirm(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContext, _ := dtcontext.InitDTContext(mainContext) - dtContext.State = dtcommon.Connected - dtContext.ConfirmMap.Store("emptyMessage", &dttype.DTMessage{}) - dtContext.ConfirmMap.Store("actionMessage", &dttype.DTMessage{Msg: &model.Message{}, Action: dtcommon.SendToCloud}) - tests := []struct { - name string - Worker Worker - context *dtcontext.DTContext - msg interface{} - }{ - { - name: "checkConfirmTest", - Worker: Worker{DTContexts: dtContext}, - context: dtContext, - msg: &dttype.DTMessage{Action: "action"}, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - cw := CommWorker{ - Worker: test.Worker, - } - cw.checkConfirm(test.context, test.msg) - _, exist := test.context.ConfirmMap.Load("actionMessage") - if !exist { - t.Errorf(" checkconfirm() failed because dealSendToCloud() failed to store message in ConfirmMap") - return - } - }) - } -} +//func TestStartHeartBeat(t *testing.T) { +// mainContext := context.GetContext(context.MsgCtxTypeChannel) +// dtContexts, _ := dtcontext.InitDTContext(mainContext) +// heartChanStop := make(chan interface{}, 1) +// heartChanPing := make(chan interface{}, 1) +// heartChanStop <- "stop" +// heartChanPing <- "ping" +// tests := []struct { +// name string +// Worker Worker +// Group string +// }{ +// { +// name: "StartTest-PingInHeartBeatChannel", +// Worker: Worker{ +// HeartBeatChan: heartChanPing, +// DTContexts: dtContexts, +// }, +// Group: "group", +// }, +// { +// name: "StartTest-StopInHeartBeatChannel", +// Worker: Worker{ +// HeartBeatChan: heartChanStop, +// DTContexts: dtContexts, +// }, +// Group: "group", +// }, +// } +// for _, test := range tests { +// t.Run(test.name, func(t *testing.T) { +// cw := CommWorker{ +// Worker: test.Worker, +// Group: test.Group, +// } +// go cw.Start() +// time.Sleep(1 * time.Millisecond) +// if test.Worker.HeartBeatChan == heartChanPing { +// _, exist := test.Worker.DTContexts.ModulesHealth.Load("group") +// if !exist { +// t.Errorf("Start Failed to add module in context") +// } +// } +// }) +// } +//} +// +//// TestDealSendToEdge is function to test dealsendToedge(). +//func TestDealSendToEdge(t *testing.T) { +// mainContext := context.GetContext(context.MsgCtxTypeChannel) +// dtContexts, _ := dtcontext.InitDTContext(mainContext) +// tests := []struct { +// name string +// context *dtcontext.DTContext +// resource string +// msg interface{} +// }{ +// { +// name: "dealSendToEdgeTest", +// context: dtContexts, +// msg: &model.Message{}, +// }, +// } +// for _, test := range tests { +// t.Run(test.name, func(t *testing.T) { +// dealSendToEdge(test.context, test.resource, test.msg) +// }) +// } +//} +// +//// TestDealSendToCloud is function to test dealSendToCloud(). +//func TestDealSendToCloud(t *testing.T) { +// mainContext := context.GetContext(context.MsgCtxTypeChannel) +// dtContextStateDisconnected, _ := dtcontext.InitDTContext(mainContext) +// dtContextStateConnected, _ := dtcontext.InitDTContext(mainContext) +// dtContextStateConnected.State = dtcommon.Connected +// msg := &model.Message{Header: model.MessageHeader{ID: "message"}} +// expectedMessage := &dttype.DTMessage{Msg: msg, Action: dtcommon.SendToCloud, Type: dtcommon.CommModule} +// tests := []struct { +// name string +// context *dtcontext.DTContext +// resource string +// msg interface{} +// wantErr error +// }{ +// { +// name: "dealSendToCloudTest-StateDisconnected", +// context: dtContextStateDisconnected, +// msg: "", +// wantErr: nil, +// }, +// { +// name: "dealSendToCloudTest-StateConnected", +// context: dtContextStateConnected, +// msg: "", +// wantErr: errors.New("msg not Message type"), +// }, +// { +// name: "dealSendToCloudTest-ActualMsg", +// context: dtContextStateConnected, +// msg: msg, +// wantErr: nil, +// }, +// } +// for _, test := range tests { +// t.Run(test.name, func(t *testing.T) { +// _, err := dealSendToCloud(test.context, test.resource, test.msg) +// if !reflect.DeepEqual(err, test.wantErr) { +// t.Errorf("dealSendToCloud() error = %v, wantErr %v", err, test.wantErr) +// return +// } +// // Testing whether the message is properly stored in ConfirmMap of context when correct message is passed +// if err == nil && test.context.State == dtcommon.Connected { +// gotMsg, exist := test.context.ConfirmMap.Load("message") +// if !exist { +// t.Errorf("dealSendToCloud() failed to store message in ConfirmMap") +// return +// } +// if !reflect.DeepEqual(expectedMessage, gotMsg) { +// t.Errorf("dealSendToCloud() failed due to wrong gotMsg in ConfirmMap Got =%v Want=%v", test.msg, gotMsg) +// } +// } +// }) +// } +//} +// +//// TestDealLifeCycle is function to test dealLifeCycle(). +//func TestDealLifeCycle(t *testing.T) { +// mainContext := context.GetContext(context.MsgCtxTypeChannel) +// dtContext, _ := dtcontext.InitDTContext(mainContext) +// tests := []struct { +// name string +// context *dtcontext.DTContext +// resource string +// msg interface{} +// wantErr error +// }{ +// { +// name: "dealLifeCycleTest-WrongMessageFormat", +// context: dtContext, +// msg: "", +// wantErr: errors.New("msg not Message type"), +// }, +// { +// name: "dealLifeCycleTest-CloudConnected", +// context: dtContext, +// msg: &model.Message{Content: cloudconn.CloudConnected}, +// wantErr: nil, +// }, +// { +// name: "dealLifeCycleTest-CloudNotConnected", +// context: dtContext, +// msg: &model.Message{Content: cloudconn.CloudDisconnected}, +// wantErr: nil, +// }, +// } +// for _, test := range tests { +// t.Run(test.name, func(t *testing.T) { +// _, err := dealLifeCycle(test.context, test.resource, test.msg) +// if !reflect.DeepEqual(err, test.wantErr) { +// t.Errorf("dealLifeCycle() error = %v, wantErr %v", err, test.wantErr) +// } +// }) +// } +//} +// +//// TestDealConfirm is function to test dealConfirm(). +//func TestDealConfirm(t *testing.T) { +// mainContext := context.GetContext(context.MsgCtxTypeChannel) +// dtContext, _ := dtcontext.InitDTContext(mainContext) +// tests := []struct { +// name string +// context *dtcontext.DTContext +// resource string +// msg interface{} +// wantErr error +// }{ +// { +// name: "dealConfirmTest-WrongMsg", +// context: dtContext, +// msg: "", +// wantErr: errors.New("CommModule deal confirm, type not correct"), +// }, +// { +// name: "dealConfirmTest-CorrectMsg", +// context: dtContext, +// msg: &model.Message{Header: model.MessageHeader{ID: "id", ParentID: "parentId"}}, +// wantErr: nil, +// }, +// } +// for _, test := range tests { +// t.Run(test.name, func(t *testing.T) { +// _, err := dealConfirm(test.context, test.resource, test.msg) +// if !reflect.DeepEqual(err, test.wantErr) { +// t.Errorf("dealConfirm() error = %v, wantErr %v", err, test.wantErr) +// return +// } +// if err == nil { +// _, exist := test.context.ConfirmMap.Load("parentId") +// if exist { +// t.Errorf("dealConfirm failed() ParentMessageId still present in context ConfirmMap") +// } +// } +// }) +// } +//} +// +//// TestCheckConfirm is function to test checkConfirm(). +//func TestCheckConfirm(t *testing.T) { +// mainContext := context.GetContext(context.MsgCtxTypeChannel) +// dtContext, _ := dtcontext.InitDTContext(mainContext) +// dtContext.State = dtcommon.Connected +// dtContext.ConfirmMap.Store("emptyMessage", &dttype.DTMessage{}) +// dtContext.ConfirmMap.Store("actionMessage", &dttype.DTMessage{Msg: &model.Message{}, Action: dtcommon.SendToCloud}) +// tests := []struct { +// name string +// Worker Worker +// context *dtcontext.DTContext +// msg interface{} +// }{ +// { +// name: "checkConfirmTest", +// Worker: Worker{DTContexts: dtContext}, +// context: dtContext, +// msg: &dttype.DTMessage{Action: "action"}, +// }, +// } +// for _, test := range tests { +// t.Run(test.name, func(t *testing.T) { +// cw := CommWorker{ +// Worker: test.Worker, +// } +// cw.checkConfirm(test.context, test.msg) +// _, exist := test.context.ConfirmMap.Load("actionMessage") +// if !exist { +// t.Errorf(" checkconfirm() failed because dealSendToCloud() failed to store message in ConfirmMap") +// return +// } +// }) +// } +//} diff --git a/edge/pkg/devicetwin/dtmanager/device_test.go b/edge/pkg/devicetwin/dtmanager/device_test.go deleted file mode 100644 index a3244cc5840..00000000000 --- a/edge/pkg/devicetwin/dtmanager/device_test.go +++ /dev/null @@ -1,492 +0,0 @@ -/* -Copyright 2019 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package dtmanager - -import ( - "encoding/json" - "errors" - "reflect" - "testing" - "time" - - "github.com/astaxie/beego/orm" - "github.com/golang/mock/gomock" - - "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" -) - -var called bool - -//testAction is a dummy function for testing Start -func testAction(context *dtcontext.DTContext, resource string, msg interface{}) (interface{}, error) { - called = true - return called, errors.New("Called the dummy function for testing") -} - -// TestDeviceStartAction is function to test Start() when value is passed in ReceiverChan. -func TestDeviceStartAction(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContextStateConnected, _ := dtcontext.InitDTContext(mainContext) - dtContextStateConnected.State = dtcommon.Connected - content := dttype.DeviceUpdate{} - bytes, _ := json.Marshal(content) - msg := model.Message{Content: bytes} - receiveChanActionPresent := make(chan interface{}, 1) - receiveChanActionPresent <- &dttype.DTMessage{Action: "testAction", Identity: "identity", Msg: &msg} - receiveChanActionNotPresent := make(chan interface{}, 1) - receiveChanActionNotPresent <- &dttype.DTMessage{Action: "action", Identity: "identity", Msg: &model.Message{Content: "msg"}} - tests := []struct { - name string - Worker Worker - }{ - { - name: "StartTest-ActionNotPresentInActionCallback", - Worker: Worker{ - ReceiverChan: receiveChanActionNotPresent, - DTContexts: dtContextStateConnected, - }, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - dw := DeviceWorker{ - Worker: test.Worker, - } - go dw.Start() - time.Sleep(1 * time.Millisecond) - //Adding a dummy function to callback to ensure Start is successful. - deviceActionCallBack["testAction"] = testAction - dw.ReceiverChan <- &dttype.DTMessage{Action: "testAction", Identity: "identity", Msg: &msg} - time.Sleep(1 * time.Millisecond) - if !called { - t.Errorf("Start failed") - } - }) - } -} - -// TestDevicetHeartBeat is function to test Start() when value is passed in HeartBeatChan. -func TestDeviceStartHeartBeat(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContexts, _ := dtcontext.InitDTContext(mainContext) - heartChanStop := make(chan interface{}, 1) - heartChanPing := make(chan interface{}, 1) - heartChanStop <- "stop" - heartChanPing <- "ping" - tests := []struct { - name string - Worker Worker - Group string - }{ - { - name: "StartTest-PingInHeartBeatChannel", - Worker: Worker{ - HeartBeatChan: heartChanPing, - DTContexts: dtContexts, - }, - Group: "group", - }, - { - name: "StartTest-StopInHeartBeatChannel", - Worker: Worker{ - HeartBeatChan: heartChanStop, - DTContexts: dtContexts, - }, - Group: "group", - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - dw := DeviceWorker{ - Worker: test.Worker, - Group: test.Group, - } - go dw.Start() - time.Sleep(1 * time.Millisecond) - if test.Worker.HeartBeatChan == heartChanPing { - _, exist := test.Worker.DTContexts.ModulesHealth.Load("group") - if !exist { - t.Errorf("Start Failed to add module in context") - } - } - }) - } -} - -// TestDealDeviceStatusUpdate test dealDeviceStatusUpdate -func TestDealDeviceStateUpdate(t *testing.T) { - initMocks(t) - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContexts, _ := dtcontext.InitDTContext(mainContext) - dtContexts.DeviceList.Store("DeviceC", "DeviceC") - deviceD := &dttype.Device{} - dtContexts.DeviceList.Store("DeviceD", deviceD) - var emptyDevUpdate dttype.DeviceUpdate - bytesEmptyDevUpdate, _ := json.Marshal(emptyDevUpdate) - devUpdate := &dttype.DeviceUpdate{State: "online"} - bytesDevUpdate, _ := json.Marshal(devUpdate) - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - want interface{} - wantErr error - // filterReturn is the return of mock interface querySeterMock's filter function - filterReturn orm.QuerySeter - // updateReturnInt is the first return of mock interface querySeterMock's update function - updateReturnInt int64 - // updateReturnErr is the second return of mock interface querySeterMocks's update function also expected error - updateReturnErr error - // queryTableReturn is the return of mock interface ormerMock's QueryTable function - queryTableReturn orm.QuerySeter - times int - }{ - { - name: "dealDeviceStateUpdateTest-WrongMessageType", - context: dtContexts, - resource: "DeviceA", - msg: "", - want: nil, - wantErr: errors.New("msg not Message type"), - }, - { - name: "dealDeviceStateUpdateTest-DeviceDoesNotExist", - context: dtContexts, - resource: "DeviceB", - msg: &model.Message{Content: bytesEmptyDevUpdate}, - want: nil, - wantErr: nil, - }, - { - name: "dealDeviceStateUpdateTest-DeviceExist", - context: dtContexts, - resource: "DeviceC", - msg: &model.Message{Content: bytesEmptyDevUpdate}, - want: nil, - wantErr: nil, - }, - { - name: "dealDeviceStateUpdateTest-CorrectDeviceType", - context: dtContexts, - resource: "DeviceD", - msg: &model.Message{Content: bytesEmptyDevUpdate}, - want: nil, - wantErr: nil, - }, - { - name: "dealDeviceStateUpdateTest-UpdatePresent", - context: dtContexts, - resource: "DeviceD", - msg: &model.Message{Content: bytesDevUpdate}, - want: nil, - wantErr: nil, - filterReturn: querySeterMock, - updateReturnInt: int64(1), - updateReturnErr: nil, - queryTableReturn: querySeterMock, - times: 2, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - querySeterMock.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(test.times) - querySeterMock.EXPECT().Update(gomock.Any()).Return(test.updateReturnInt, test.updateReturnErr).Times(test.times) - ormerMock.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(test.times) - got, err := dealDeviceStateUpdate(test.context, test.resource, test.msg) - if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("dealDeviceStateUpdate() error = %v, wantErr %v", err, test.wantErr) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("dealDeviceStateUpdate() = %v, want %v", got, test.want) - } - }) - } -} - -//TestDealDeviceUpdated is function to test dealDeviceUpdated(). -func TestDealDeviceUpdated(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContexts, _ := dtcontext.InitDTContext(mainContext) - content := dttype.DeviceUpdate{} - bytes, _ := json.Marshal(content) - msg := model.Message{Content: bytes} - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - want interface{} - wantErr error - }{ - { - name: "DealDeviceUpdatedTest-Wrong Message Type", - context: dtContexts, - resource: "Device", - msg: "", - want: nil, - wantErr: errors.New("msg not Message type"), - }, - { - name: "DealDeviceUpdatedTest-Correct Message Type", - context: dtContexts, - resource: "DeviceA", - msg: &msg, - want: nil, - wantErr: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got, err := dealDeviceUpdated(test.context, test.resource, test.msg) - if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("dealDeviceUpdated() error = %v, wantErr %v", err, test.wantErr) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("dealDeviceUpdated() = %v, want %v", got, test.want) - } - }) - } -} - -// TestDeviceUpdated is function to test DeviceUpdated(). -func TestDeviceUpdated(t *testing.T) { - initMocks(t) - // adds is fake DeviceAttr used as argument - adds := make([]dtclient.DeviceAttr, 0) - // deletes is fake DeviceDelete used as argument - deletes := make([]dtclient.DeviceDelete, 0) - // updates is fake DeviceAttrUpdate used as argument - updates := make([]dtclient.DeviceAttrUpdate, 0) - adds = append(adds, dtclient.DeviceAttr{DeviceID: "Test"}) - deletes = append(deletes, dtclient.DeviceDelete{DeviceID: "test", Name: "test"}) - updates = append(updates, dtclient.DeviceAttrUpdate{DeviceID: "test", Name: "test", Cols: make(map[string]interface{})}) - - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContexts, _ := dtcontext.InitDTContext(mainContext) - dtContexts.DeviceList.Store("EmptyDevice", "Device") - devA := &dttype.Device{ID: "DeviceA"} - dtContexts.DeviceList.Store("DeviceA", devA) - - messageAttributes := make(map[string]*dttype.MsgAttr) - optional := true - msgattr := &dttype.MsgAttr{Value: "ON", Optional: &optional, Metadata: &dttype.TypeMetadata{Type: "device"}} - messageAttributes["DeviceA"] = msgattr - baseMessage := dttype.BuildBaseMessage() - tests := []struct { - name string - context *dtcontext.DTContext - deviceID string - attributes map[string]*dttype.MsgAttr - baseMessage dttype.BaseMessage - dealType int - want interface{} - wantErr error - // commitTimes is number of times commit is expected - commitTimes int - // beginTimes is number of times begin is expected - beginTimes int - // filterReturn is the return of mock interface querySeterMock's filter function - filterReturn orm.QuerySeter - // filterTimes is the number of times filter is called - filterTimes int - // insertReturnInt is the first return of mock interface ormerMock's Insert function - insertReturnInt int64 - // insertReturnErr is the second return of mock interface ormerMock's Insert function - insertReturnErr error - // insertTimes is number of times Insert is expected - insertTimes int - // deleteReturnInt is the first return of mock interface ormerMock's Delete function - deleteReturnInt int64 - // deleteReturnErr is the second return of mock interface ormerMock's Delete function - deleteReturnErr error - // deleteTimes is number of times Delete is expected - deleteTimes int - // updateReturnInt is the first return of mock interface ormerMock's Update function - updateReturnInt int64 - // updateReturnErr is the second return of mock interface ormerMock's Update function - updateReturnErr error - // updateTimes is number of times Update is expected - updateTimes int - // queryTableReturn is the return of mock interface ormerMock's QueryTable function - queryTableReturn orm.QuerySeter - // queryTableTimes is the number of times queryTable is called - queryTableTimes int - }{ - { - name: "Test1", - context: dtContexts, - deviceID: "Device", - attributes: messageAttributes, - baseMessage: baseMessage, - want: nil, - wantErr: nil, - }, - { - name: "Test2", - context: dtContexts, - deviceID: "EmptyDevice", - attributes: messageAttributes, - baseMessage: baseMessage, - want: nil, - wantErr: nil, - }, - { - name: "Test3", - context: dtContexts, - deviceID: "DeviceA", - attributes: messageAttributes, - baseMessage: baseMessage, - wantErr: nil, - want: nil, - commitTimes: 1, - beginTimes: 1, - filterReturn: querySeterMock, - filterTimes: 6, - insertReturnInt: int64(1), - insertReturnErr: nil, - insertTimes: 1, - deleteReturnInt: int64(1), - deleteReturnErr: nil, - deleteTimes: 1, - updateReturnInt: int64(1), - updateReturnErr: nil, - updateTimes: 1, - queryTableReturn: querySeterMock, - queryTableTimes: 2, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - ormerMock.EXPECT().Commit().Return(nil).Times(test.commitTimes) - ormerMock.EXPECT().Begin().Return(nil).Times(test.beginTimes) - querySeterMock.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(test.filterTimes) - ormerMock.EXPECT().Insert(gomock.Any()).Return(test.insertReturnInt, test.insertReturnErr).Times(test.insertTimes) - querySeterMock.EXPECT().Delete().Return(test.deleteReturnInt, test.deleteReturnErr).Times(test.deleteTimes) - querySeterMock.EXPECT().Update(gomock.Any()).Return(test.updateReturnInt, test.updateReturnErr).Times(test.updateTimes) - ormerMock.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(test.queryTableTimes) - got, err := DeviceUpdated(test.context, test.deviceID, test.attributes, test.baseMessage, test.dealType) - if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("DeviceUpdated() error = %v, wantErr %v", err, test.wantErr) - return - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("DeviceUpdated() failed Got = %v, want %v", got, test.want) - } - }) - } -} - -// TestDealMsgAttr is function to test DealMsgAttr(). -func TestDealMsgAttr(t *testing.T) { - mainContext := context.GetContext(context.MsgCtxTypeChannel) - dtContextsEmptyAttributes, _ := dtcontext.InitDTContext(mainContext) - dtContextsNonEmptyAttributes, _ := dtcontext.InitDTContext(mainContext) - //Creating want and message attributes when device attribute is not present - devA := &dttype.Device{ID: "DeviceA"} - dtContextsEmptyAttributes.DeviceList.Store("DeviceA", devA) - messageAttributes := make(map[string]*dttype.MsgAttr) - optional := true - msgattr := &dttype.MsgAttr{Value: "ON", Optional: &optional, Metadata: &dttype.TypeMetadata{Type: "device"}} - messageAttributes["DeviceA"] = msgattr - add := []dtclient.DeviceAttr{} - add = append(add, dtclient.DeviceAttr{ID: 0, DeviceID: "DeviceA", Name: "DeviceA", Value: "ON", Optional: true, AttrType: "device", Metadata: "{}"}) - result := make(map[string]*dttype.MsgAttr) - result["DeviceA"] = msgattr - wantDealAttrResult := dttype.DealAttrResult{Add: add, Delete: []dtclient.DeviceDelete{}, Update: []dtclient.DeviceAttrUpdate{}, Result: result, Err: nil} - //Creating want and message attributes when device attribute is present - attributes := map[string]*dttype.MsgAttr{} - attributes["DeviceB"] = msgattr - attr := map[string]*dttype.MsgAttr{} - opt := false - attr["DeviceB"] = &dttype.MsgAttr{Value: "OFF", Optional: &opt, Metadata: &dttype.TypeMetadata{Type: "device"}} - devB := &dttype.Device{ID: "DeviceB", Attributes: attr} - update := []dtclient.DeviceAttrUpdate{} - cols := make(map[string]interface{}) - cols["value"] = "ON" - upd := dtclient.DeviceAttrUpdate{Name: "DeviceB", DeviceID: "DeviceB", Cols: cols} - update = append(update, upd) - dtContextsNonEmptyAttributes.DeviceList.Store("DeviceB", devB) - want := dttype.DealAttrResult{Add: []dtclient.DeviceAttr{}, Delete: []dtclient.DeviceDelete{}, Update: update} - tests := []struct { - name string - context *dtcontext.DTContext - deviceID string - msgAttributes map[string]*dttype.MsgAttr - dealType int - want dttype.DealAttrResult - }{ - { - name: "DealMsgAttrTest-DeviceAttribute not present", - context: dtContextsEmptyAttributes, - deviceID: "DeviceA", - msgAttributes: messageAttributes, - want: wantDealAttrResult, - }, - { - name: "DealMsgAttrTest-DeviceAttribute present", - context: dtContextsNonEmptyAttributes, - deviceID: "DeviceB", - msgAttributes: attributes, - dealType: 1, - want: want, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := DealMsgAttr(tt.context, tt.deviceID, tt.msgAttributes, tt.dealType) - if !reflect.DeepEqual(got.Add, tt.want.Add) { - t.Errorf("Add error , Got = %v, Want = %v", got.Add, tt.want.Add) - return - } - if !reflect.DeepEqual(got.Delete, tt.want.Delete) { - t.Errorf("Delete error , Got = %v, Want = %v", got.Delete, tt.want.Delete) - return - } - if !reflect.DeepEqual(got.Update, tt.want.Update) { - t.Errorf("Update error , Got = %v, Want = %v", got.Update, tt.want.Update) - return - } - if !reflect.DeepEqual(got.Err, tt.want.Err) { - t.Errorf("Error error , Got = %v, Want = %v", got.Update, tt.want.Update) - return - } - for key, value := range tt.want.Result { - check := false - for key1, value1 := range got.Result { - if key == key1 { - if value == value1 { - check = true - break - } - } - if check == false { - t.Errorf("Wrong Map") - return - } - } - } - }) - } -} diff --git a/edge/pkg/devicetwin/dtmanager/membership_test.go b/edge/pkg/devicetwin/dtmanager/membership_test.go deleted file mode 100644 index a2de8748842..00000000000 --- a/edge/pkg/devicetwin/dtmanager/membership_test.go +++ /dev/null @@ -1,363 +0,0 @@ -/* -Copyright 2019 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package dtmanager - -import ( - "encoding/json" - "errors" - "sync" - "testing" - - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/assert" - - "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/mocks/beego" - "github.com/kubeedge/kubeedge/edge/pkg/common/dbm" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" -) - -var ormerMock *beego.MockOrmer -var querySeterMock *beego.MockQuerySeter - -func initMocks(t *testing.T) { - mockCtrl := gomock.NewController(t) - defer mockCtrl.Finish() - ormerMock = beego.NewMockOrmer(mockCtrl) - querySeterMock = beego.NewMockQuerySeter(mockCtrl) - dbm.DBAccess = ormerMock -} - -func TestInitMemActionCallBack(t *testing.T) { - initMemActionCallBack() -} - -func TestGetRemoveList(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - } - - var device dttype.Device - dtc.DeviceList.Store("DeviceB", &device) - dArray := []dttype.Device{} - d := dttype.Device{ - ID: "123", - } - dArray = append(dArray, d) - value := getRemoveList(dtc, dArray) - for i := range value { - assert.Equal(t, "DeviceB", value[i].ID) - } -} - -func TestGetRemoveListProperDevideID(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - } - var device dttype.Device - dtc.DeviceList.Store("123", &device) - dArray := []dttype.Device{} - d := dttype.Device{ - ID: "123", - } - dArray = append(dArray, d) - value := getRemoveList(dtc, dArray) - for i := range value { - assert.Equal(t, "123", value[i].ID) - } -} - -func TestDealMembershipDetailInvalidEmptyMessage(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - value, err := dealMembershipDetail(dtc, "t", "invalid") - assert.Error(t, err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipDetailInvalidMsg(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - - var m = &model.Message{ - Content: "invalidmsg", - } - - value, err := dealMembershipDetail(dtc, "t", m) - assert.Error(t, err) - assert.Equal(t, errors.New("assertion failed"), err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipDetailInvalidContent(t *testing.T) { - - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - var cnt []uint8 - cnt = append(cnt, 1) - var m = &model.Message{ - Content: cnt, - } - - value, err := dealMembershipDetail(dtc, "t", m) - assert.Error(t, err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipDetailValid(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - Mutex: &sync.RWMutex{}, - GroupID: "1", - } - - payload := dttype.MembershipUpdate{AddDevices: []dttype.Device{{ID: "DeviceA", Name: "Router", - State: "unknown"}}, BaseMessage: dttype.BaseMessage{EventID: "eventid"}} - content, _ := json.Marshal(payload) - var m = &model.Message{ - Content: content, - } - value, err := dealMembershipDetail(dtc, "t", m) - assert.NoError(t, err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipUpdatedEmptyMessage(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - value, err := dealMembershipDetail(dtc, "t", "invalid") - assert.Error(t, err) - assert.Equal(t, errors.New("msg not Message type"), err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipUpdatedInvalidMsg(t *testing.T) { - - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - - var m = &model.Message{ - Content: "invalidmessage", - } - - value, err := dealMembershipUpdated(dtc, "t", m) - assert.Error(t, err) - assert.Equal(t, errors.New("assertion failed"), err) - assert.Equal(t, nil, value) -} -func TestDealMembershipUpdatedInvalidContent(t *testing.T) { - - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - - var cnt []uint8 - cnt = append(cnt, 1) - var m = &model.Message{ - Content: cnt, - } - - value, err := dealMembershipUpdated(dtc, "t", m) - assert.Error(t, err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipUpdatedValidAddedDevice(t *testing.T) { - initMocks(t) - ormerMock.EXPECT().Begin().Return(nil).Times(6) - ormerMock.EXPECT().Insert(gomock.Any()).Return(int64(1), nil).Times(3) - ormerMock.EXPECT().Commit().Return(nil).Times(1) - querySeterMock.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(querySeterMock).Times(1) - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - GroupID: "1", - } - - payload := dttype.MembershipUpdate{AddDevices: []dttype.Device{{ID: "DeviceA", Name: "Router", - State: "unknown"}}, BaseMessage: dttype.BaseMessage{EventID: "eventid"}} - content, _ := json.Marshal(payload) - var m = &model.Message{ - Content: content, - } - value, err := dealMembershipUpdated(dtc, "t", m) - assert.NoError(t, err) - assert.Equal(t, nil, value) -} - -func TestDealMembershipUpdatedValidRemovedDevice(t *testing.T) { - ormerMock.EXPECT().Begin().Return(nil).Times(1) - ormerMock.EXPECT().Insert(gomock.Any()).Return(int64(1), nil).Times(1) - ormerMock.EXPECT().Commit().Return(nil).Times(1) - ormerMock.EXPECT().QueryTable(gomock.Any()).Return(querySeterMock).Times(1) - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - GroupID: "1", - } - - payload := dttype.MembershipUpdate{RemoveDevices: []dttype.Device{{ID: "DeviceA", Name: "Router", - State: "unknown"}}, BaseMessage: dttype.BaseMessage{EventID: "eventid"}} - content, _ := json.Marshal(payload) - var m = &model.Message{ - Content: content, - } - value, err := dealMembershipUpdated(dtc, "t", m) - assert.NoError(t, err) - assert.Equal(t, nil, value) -} - -func TestDealMerbershipGetEmptyMsg(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - value, err := dealMerbershipGet(dtc, "t", "invalid") - assert.Error(t, err) - assert.Equal(t, errors.New("msg not Message type"), err) - assert.Equal(t, nil, value) -} - -func TestDealMerbershipGetInvalidMsg(t *testing.T) { - - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - GroupID: "1", - } - - var m = &model.Message{ - Content: "hello", - } - - value, err := dealMerbershipGet(dtc, "t", m) - assert.Error(t, err) - assert.Equal(t, errors.New("assertion failed"), err) - assert.Equal(t, nil, value) -} - -func TestDealMerbershipGetValid(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - GroupID: "1", - } - - payload := dttype.MembershipUpdate{AddDevices: []dttype.Device{{ID: "DeviceA", Name: "Router", - State: "unknown"}}, BaseMessage: dttype.BaseMessage{EventID: "eventid"}} - content, _ := json.Marshal(payload) - var m = &model.Message{ - Content: content, - } - value, err := dealMerbershipGet(dtc, "t", m) - assert.Equal(t, nil, value) - assert.NoError(t, err) -} - -func TestDealGetMembershipValid(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - GroupID: "1", - } - - payload := dttype.MembershipUpdate{AddDevices: []dttype.Device{{ID: "DeviceA", Name: "Router", - State: "unknown"}}, BaseMessage: dttype.BaseMessage{EventID: "eventid"}} - content, _ := json.Marshal(payload) - - err := DealGetMembership(dtc, content) - assert.NoError(t, err) -} - -func TestDealGetMembershipInValid(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - GroupID: "1", - } - - err := DealGetMembership(dtc, []byte("invalid")) - assert.NoError(t, err) -} - -/* Commented As we are not considering about the coverage incase for coverage we can uncomment below cases. -func TestAdded(t *testing.T) { - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.Mutex{}, - GroupID: "1", - } - - var d = []dttype.Device{{ - ID: "DeviceA", - Name: "Router", - State: "unknown", - }} - var b = dttype.BaseMessage{ - EventID: "eventid", - } - Added(dtc, d, b, true) -} - -func TestRemoved(t *testing.T) { - ormerMock.EXPECT().Begin().Return(nil).Times(1) - ormerMock.EXPECT().Rollback().Return(nil).Times(0) - ormerMock.EXPECT().Commit().Return(nil).Times(1) - querySeterMock.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(querySeterMock).Times(3) - ormerMock.EXPECT().QueryTable(gomock.Any()).Return(querySeterMock).Times(3) - // success delete - querySeterMock.EXPECT().Delete().Return(int64(1), nil).Times(3) - // fail delete - querySeterMock.EXPECT().Delete().Return(int64(1), errors.New("failed to delete")).Times(0) - - dtc := &dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.Mutex{}, - GroupID: "1", - } - - var device dttype.Device - dtc.DeviceList.Store("DeviceA", &device) - var d = []dttype.Device{{ - ID: "DeviceA", - Name: "Router", - State: "unknown", - }} - var b = dttype.BaseMessage{ - EventID: "eventid", - } - - Removed(dtc, d, b, true) -}*/ diff --git a/edge/pkg/devicetwin/dtmanager/twin_test.go b/edge/pkg/devicetwin/dtmanager/twin_test.go deleted file mode 100644 index 214bf12cdbb..00000000000 --- a/edge/pkg/devicetwin/dtmanager/twin_test.go +++ /dev/null @@ -1,1262 +0,0 @@ -/* -Copyright 2019 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package dtmanager - -import ( - "encoding/json" - "errors" - "reflect" - "sync" - "testing" - "time" - - "github.com/astaxie/beego/orm" - "github.com/golang/mock/gomock" - "k8s.io/klog" - - "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/mocks/beego" - "github.com/kubeedge/kubeedge/edge/pkg/common/dbm" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" -) - -var ( - deviceA = "DeviceA" - deviceB = "DeviceB" - deviceC = "DeviceC" - event1 = "Event1" - key1 = "key1" - mockOrmer *beego.MockOrmer - mockQuerySeter *beego.MockQuerySeter - typeDeleted = "deleted" - typeInt = "int" - typeString = "string" -) - -// mocksInit is function to mock DBAccess -func mocksInit(t *testing.T) { - mockCtrl := gomock.NewController(t) - defer mockCtrl.Finish() - mockOrmer = beego.NewMockOrmer(mockCtrl) - mockQuerySeter = beego.NewMockQuerySeter(mockCtrl) - dbm.DBAccess = mockOrmer -} - -// sendMsg sends message to receiverChannel and heartbeatChannel -func (tw TwinWorker) sendMsg(msg *dttype.DTMessage, msgHeart string, actionType string, contentType interface{}) { - if tw.ReceiverChan != nil { - msg.Action = actionType - msg.Msg.Content = contentType - tw.ReceiverChan <- msg - } - if tw.HeartBeatChan != nil { - tw.HeartBeatChan <- msgHeart - } -} - -// receiveMsg receives message from the commChannel -func receiveMsg(commChannel chan interface{}, message *dttype.DTMessage) { - msg, ok := <-commChannel - if !ok { - klog.Errorf("No message received from communication channel") - return - } - *message = *msg.(*dttype.DTMessage) -} - -// twinValueFunc returns a new TwinValue -func twinValueFunc() *dttype.TwinValue { - var twinValue dttype.TwinValue - value := "value" - valueMetaData := &dttype.ValueMetadata{Timestamp: time.Now().UnixNano() / 1e6} - twinValue.Value = &value - twinValue.Metadata = valueMetaData - return &twinValue -} - -// keyTwinUpdateFunc returns a new DeviceTwinUpdate -func keyTwinUpdateFunc() dttype.DeviceTwinUpdate { - var keyTwinUpdate dttype.DeviceTwinUpdate - twinKey := make(map[string]*dttype.MsgTwin) - twinKey[key1] = &dttype.MsgTwin{ - Expected: twinValueFunc(), - Actual: twinValueFunc(), - Metadata: &dttype.TypeMetadata{Type: "nil"}, - } - keyTwinUpdate.Twin = twinKey - keyTwinUpdate.BaseMessage = dttype.BaseMessage{EventID: event1} - return keyTwinUpdate -} - -// twinWorkerFunc returns a new TwinWorker -func twinWorkerFunc(receiverChannel chan interface{}, confirmChannel chan interface{}, heartBeatChannel chan interface{}, context dtcontext.DTContext, group string) TwinWorker { - return TwinWorker{ - Worker{ - receiverChannel, - confirmChannel, - heartBeatChannel, - &context, - }, - group, - } -} - -// contextFunc returns a new DTContext -func contextFunc(deviceID string) dtcontext.DTContext { - context := dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - } - var testMutex sync.Mutex - context.DeviceMutex.Store(deviceID, &testMutex) - var device dttype.Device - context.DeviceList.Store(deviceID, &device) - return context -} - -// msgTypeFunc returns a new Message -func msgTypeFunc(content interface{}) *model.Message { - return &model.Message{ - Content: content, - } -} - -// TestStart is function to test Start -func TestStart(t *testing.T) { - keyTwinUpdate := keyTwinUpdateFunc() - contentKeyTwin, _ := json.Marshal(keyTwinUpdate) - - commChan := make(map[string]chan interface{}) - commChannel := make(chan interface{}) - commChan[dtcommon.CommModule] = commChannel - - context := dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - CommChan: commChan, - ModulesHealth: &sync.Map{}, - } - var testMutex sync.Mutex - context.DeviceMutex.Store(deviceB, &testMutex) - msgAttr := make(map[string]*dttype.MsgAttr) - device := dttype.Device{ - ID: "id1", - Name: deviceB, - Attributes: msgAttr, - Twin: keyTwinUpdate.Twin, - } - context.DeviceList.Store(deviceB, &device) - - msg := &dttype.DTMessage{ - Msg: &model.Message{ - Header: model.MessageHeader{ - ID: "id1", - ParentID: "pid1", - Timestamp: 0, - Sync: false, - }, - Router: model.MessageRoute{ - Source: "source", - Resource: "resource", - Group: "group", - Operation: "op", - }, - Content: contentKeyTwin, - }, - Action: dtcommon.TwinGet, - Type: dtcommon.CommModule, - } - msgHeartPing := "ping" - msgHeartStop := "stop" - receiverChannel := make(chan interface{}) - heartbeatChannel := make(chan interface{}) - - tests := []struct { - name string - tw TwinWorker - actionType string - contentType interface{} - msgType string - }{ - { - name: "TestStart(): Case 1: ReceiverChan case when error is nil", - tw: twinWorkerFunc(receiverChannel, nil, nil, context, ""), - actionType: dtcommon.TwinGet, - contentType: contentKeyTwin, - }, - { - name: "TestStart(): Case 2: ReceiverChan case error log; TwinModule deal event failed, not found callback", - tw: twinWorkerFunc(receiverChannel, nil, nil, context, ""), - actionType: dtcommon.SendToEdge, - contentType: contentKeyTwin, - }, - { - name: "TestStart(): Case 3: ReceiverChan case error log; TwinModule deal event failed", - tw: twinWorkerFunc(receiverChannel, nil, nil, context, ""), - actionType: dtcommon.TwinGet, - }, - { - name: "TestStart(): Case 4: HeartBeatChan case when error is nil", - tw: twinWorkerFunc(nil, nil, heartbeatChannel, context, "Group1"), - msgType: msgHeartPing, - }, - { - name: "TestStart(): Case 5: HeartBeatChan case when error is not nil", - tw: twinWorkerFunc(nil, nil, heartbeatChannel, context, "Group1"), - msgType: msgHeartStop, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - go test.tw.sendMsg(msg, test.msgType, test.actionType, test.contentType) - go test.tw.Start() - time.Sleep(100 * time.Millisecond) - message := &dttype.DTMessage{} - go receiveMsg(commChannel, message) - time.Sleep(100 * time.Millisecond) - if (test.tw.ReceiverChan != nil) && !reflect.DeepEqual(message.Identity, msg.Identity) && !reflect.DeepEqual(message.Type, msg.Type) { - t.Errorf("DTManager.TestStart() case failed: got = %v, Want = %v", message, msg) - } - if _, exist := context.ModulesHealth.Load("Group1"); test.tw.HeartBeatChan != nil && !exist { - t.Errorf("DTManager.TestStart() case failed: HeartBeatChan received no string") - } - }) - } -} - -// TestDealTwinSync is function to test dealTwinSync -func TestDealTwinSync(t *testing.T) { - content, _ := json.Marshal(dttype.DeviceTwinUpdate{BaseMessage: dttype.BaseMessage{EventID: event1}}) - contentKeyTwin, _ := json.Marshal(keyTwinUpdateFunc()) - context := contextFunc(deviceB) - - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - err error - }{ - { - name: "TestDealTwinSync(): Case 1: msg not Message type", - context: &dtcontext.DTContext{}, - msg: model.Message{ - Content: dttype.BaseMessage{EventID: event1}, - }, - err: errors.New("msg not Message type"), - }, - { - name: "TestDealTwinSync(): Case 2: invalid message content", - context: &dtcontext.DTContext{}, - msg: msgTypeFunc(dttype.BaseMessage{EventID: event1}), - err: errors.New("invalid message content"), - }, - { - name: "TestDealTwinSync(): Case 3: Unmarshal update request body failed", - context: &dtcontext.DTContext{}, - msg: msgTypeFunc(content), - err: errors.New("Update twin error, the update request body not have key:twin"), - }, - { - name: "TestDealTwinSync(): Case 4: Success case", - context: &context, - resource: deviceB, - msg: msgTypeFunc(contentKeyTwin), - err: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if _, err := dealTwinSync(test.context, test.resource, test.msg); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealTwinSync() case failed: got = %v, Want = %v", err, test.err) - } - }) - } -} - -// TestDealTwinGet is function to test dealTwinGet -func TestDealTwinGet(t *testing.T) { - contentKeyTwin, _ := json.Marshal(keyTwinUpdateFunc()) - context := contextFunc(deviceB) - - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - err error - }{ - { - name: "TestDealTwinGet(): Case 1: msg not Message type", - context: &dtcontext.DTContext{}, - msg: model.Message{ - Content: dttype.BaseMessage{EventID: event1}, - }, - err: errors.New("msg not Message type"), - }, - { - name: "TestDealTwinGet(): Case 2: invalid message content", - context: &dtcontext.DTContext{}, - msg: msgTypeFunc(dttype.BaseMessage{EventID: event1}), - err: errors.New("invalid message content"), - }, - { - name: "TestDealTwinGet(): Case 3: Success; Unmarshal twin info fails in DealGetTwin()", - context: &context, - resource: deviceB, - msg: msgTypeFunc([]byte("")), - err: nil, - }, - { - name: "TestDealTwinGet(): Case 4: Success; Device not found while getting twin in DealGetTwin()", - context: &context, - resource: deviceB, - msg: msgTypeFunc(contentKeyTwin), - err: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if _, err := dealTwinGet(test.context, test.resource, test.msg); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealTwinGet() case failed: got = %v, Want = %v", err, test.err) - } - }) - } -} - -// TestDealTwinUpdate is function to test dealTwinUpdate -func TestDealTwinUpdate(t *testing.T) { - content, _ := json.Marshal(dttype.DeviceTwinUpdate{BaseMessage: dttype.BaseMessage{EventID: event1}}) - contentKeyTwin, _ := json.Marshal(keyTwinUpdateFunc()) - context := contextFunc(deviceB) - - tests := []struct { - name string - context *dtcontext.DTContext - resource string - msg interface{} - err error - }{ - { - name: "TestDealTwinUpdate(): Case 1: msg not Message type", - context: &dtcontext.DTContext{}, - msg: model.Message{ - Content: dttype.BaseMessage{EventID: event1}, - }, - err: errors.New("msg not Message type"), - }, - { - name: "TestDealTwinUpdate(): Case 2: invalid message content", - context: &dtcontext.DTContext{}, - msg: msgTypeFunc(dttype.BaseMessage{EventID: event1}), - err: errors.New("invalid message content"), - }, - { - name: "TestDealTwinUpdate(): Case 3: Success; Unmarshal update request body fails in Updated()", - context: &context, - resource: deviceB, - msg: msgTypeFunc(content), - err: nil, - }, - { - name: "TestDealTwinUpdate(): Case 4: Success; Begin to update twin of the device in Updated()", - context: &context, - resource: deviceA, - msg: msgTypeFunc(contentKeyTwin), - err: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if _, err := dealTwinUpdate(test.context, test.resource, test.msg); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealTwinUpdate() case failed: got = %v, Want = %v", err, test.err) - } - }) - } -} - -// TestDealDeviceTwin is function to test DealDeviceTwin -func TestDealDeviceTwin(t *testing.T) { - mocksInit(t) - str := typeString - optionTrue := true - msgTwin := make(map[string]*dttype.MsgTwin) - msgTwin[key1] = &dttype.MsgTwin{ - Expected: twinValueFunc(), - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - } - contextDeviceB := contextFunc(deviceB) - twinDeviceB := make(map[string]*dttype.MsgTwin) - twinDeviceB[deviceB] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - } - deviceBTwin := dttype.Device{Twin: twinDeviceB} - contextDeviceB.DeviceList.Store(deviceB, &deviceBTwin) - - contextDeviceC := dtcontext.DTContext{ - DeviceList: &sync.Map{}, - DeviceMutex: &sync.Map{}, - Mutex: &sync.RWMutex{}, - } - var testMutex sync.Mutex - contextDeviceC.DeviceMutex.Store(deviceC, &testMutex) - twinDeviceC := make(map[string]*dttype.MsgTwin) - twinDeviceC[deviceC] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - } - deviceCTwin := dttype.Device{Twin: twinDeviceC} - contextDeviceC.DeviceList.Store(deviceC, &deviceCTwin) - - tests := []struct { - name string - context *dtcontext.DTContext - deviceID string - eventID string - msgTwin map[string]*dttype.MsgTwin - dealType int - err error - filterReturn orm.QuerySeter - allReturnInt int64 - allReturnErr error - queryTableReturn orm.QuerySeter - }{ - { - name: "TestDealDeviceTwin(): Case 1: msgTwin is nil", - context: &contextDeviceB, - deviceID: deviceB, - dealType: RestDealType, - err: errors.New("Update twin error, the update request body not have key:twin"), - }, - { - name: "TestDealDeviceTwin(): Case 2: Success Case", - context: &contextDeviceC, - deviceID: deviceC, - msgTwin: msgTwin, - dealType: RestDealType, - err: nil, - filterReturn: mockQuerySeter, - allReturnInt: int64(1), - allReturnErr: nil, - queryTableReturn: mockQuerySeter, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - mockOrmer.EXPECT().Rollback().Return(nil).Times(1) - mockOrmer.EXPECT().Commit().Return(nil).Times(1) - mockOrmer.EXPECT().Begin().Return(nil).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(0) - mockOrmer.EXPECT().Insert(gomock.Any()).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Delete().Return(test.allReturnInt, test.allReturnErr).Times(0) - mockQuerySeter.EXPECT().Update(gomock.Any()).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(0) - if err := DealDeviceTwin(test.context, test.deviceID, test.eventID, test.msgTwin, test.dealType); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealDeviceTwin() case failed: got = %v, Want = %v", err, test.err) - } - }) - } -} - -// TestDealDeviceTwinResult is function to test DealDeviceTwin when dealTwinResult.Err is not nil -func TestDealDeviceTwinResult(t *testing.T) { - mocksInit(t) - str := typeString - optionTrue := true - value := "value" - msgTwinValue := make(map[string]*dttype.MsgTwin) - msgTwinValue[deviceB] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &value}, - Metadata: &dttype.TypeMetadata{Type: "nil"}, - } - contextDeviceA := contextFunc(deviceB) - twinDeviceA := make(map[string]*dttype.MsgTwin) - twinDeviceA[deviceA] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - } - deviceATwin := dttype.Device{Twin: twinDeviceA} - contextDeviceA.DeviceList.Store(deviceA, &deviceATwin) - - tests := []struct { - name string - context *dtcontext.DTContext - deviceID string - eventID string - msgTwin map[string]*dttype.MsgTwin - dealType int - err error - filterReturn orm.QuerySeter - allReturnInt int64 - allReturnErr error - queryTableReturn orm.QuerySeter - }{ - { - name: "TestDealDeviceTwinResult(): dealTwinResult error", - context: &contextDeviceA, - deviceID: deviceB, - msgTwin: msgTwinValue, - dealType: RestDealType, - err: errors.New("the value type is not allowed"), - filterReturn: mockQuerySeter, - allReturnInt: int64(1), - allReturnErr: nil, - queryTableReturn: mockQuerySeter, - }, - } - - fakeDevice := new([]dtclient.Device) - fakeDeviceArray := make([]dtclient.Device, 1) - fakeDeviceArray[0] = dtclient.Device{ID: deviceB} - fakeDevice = &fakeDeviceArray - - fakeDeviceAttr := new([]dtclient.DeviceAttr) - fakeDeviceAttrArray := make([]dtclient.DeviceAttr, 1) - fakeDeviceAttrArray[0] = dtclient.DeviceAttr{DeviceID: deviceB} - fakeDeviceAttr = &fakeDeviceAttrArray - - fakeDeviceTwin := new([]dtclient.DeviceTwin) - fakeDeviceTwinArray := make([]dtclient.DeviceTwin, 1) - fakeDeviceTwinArray[0] = dtclient.DeviceTwin{DeviceID: deviceB} - fakeDeviceTwin = &fakeDeviceTwinArray - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - mockQuerySeter.EXPECT().All(gomock.Any()).SetArg(0, *fakeDevice).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(1) - mockQuerySeter.EXPECT().All(gomock.Any()).SetArg(0, *fakeDeviceAttr).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(1) - mockQuerySeter.EXPECT().All(gomock.Any()).SetArg(0, *fakeDeviceTwin).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(1) - if err := DealDeviceTwin(test.context, test.deviceID, test.eventID, test.msgTwin, test.dealType); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealDeviceTwinResult() case failed: got = %v, Want = %v", err, test.err) - } - }) - } -} - -// TestDealDeviceTwinTrans is function to test DealDeviceTwin when DeviceTwinTrans() return error -func TestDealDeviceTwinTrans(t *testing.T) { - mocksInit(t) - str := typeString - optionTrue := true - msgTwin := make(map[string]*dttype.MsgTwin) - msgTwin[key1] = &dttype.MsgTwin{ - Expected: twinValueFunc(), - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - } - contextDeviceB := contextFunc(deviceB) - twinDeviceB := make(map[string]*dttype.MsgTwin) - twinDeviceB[deviceB] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - } - deviceBTwin := dttype.Device{Twin: twinDeviceB} - contextDeviceB.DeviceList.Store(deviceB, &deviceBTwin) - - tests := []struct { - name string - context *dtcontext.DTContext - deviceID string - eventID string - msgTwin map[string]*dttype.MsgTwin - dealType int - err error - filterReturn orm.QuerySeter - insertReturnInt int64 - insertReturnErr error - deleteReturnInt int64 - deleteReturnErr error - updateReturnInt int64 - updateReturnErr error - allReturnInt int64 - allReturnErr error - queryTableReturn orm.QuerySeter - }{ - { - name: "TestDealDeviceTwinTrans(): DeviceTwinTrans error", - context: &contextDeviceB, - deviceID: deviceB, - msgTwin: msgTwin, - dealType: RestDealType, - err: errors.New("Failed DB Operation"), - filterReturn: mockQuerySeter, - insertReturnInt: int64(1), - insertReturnErr: errors.New("Failed DB Operation"), - deleteReturnInt: int64(1), - deleteReturnErr: nil, - updateReturnInt: int64(1), - updateReturnErr: nil, - allReturnInt: int64(1), - allReturnErr: nil, - queryTableReturn: mockQuerySeter, - }, - } - - fakeDevice := new([]dtclient.Device) - fakeDeviceArray := make([]dtclient.Device, 1) - fakeDeviceArray[0] = dtclient.Device{ID: deviceB} - fakeDevice = &fakeDeviceArray - - fakeDeviceAttr := new([]dtclient.DeviceAttr) - fakeDeviceAttrArray := make([]dtclient.DeviceAttr, 1) - fakeDeviceAttrArray[0] = dtclient.DeviceAttr{DeviceID: deviceB} - fakeDeviceAttr = &fakeDeviceAttrArray - - fakeDeviceTwin := new([]dtclient.DeviceTwin) - fakeDeviceTwinArray := make([]dtclient.DeviceTwin, 1) - fakeDeviceTwinArray[0] = dtclient.DeviceTwin{DeviceID: deviceB} - fakeDeviceTwin = &fakeDeviceTwinArray - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - mockOrmer.EXPECT().Rollback().Return(nil).Times(5) - mockOrmer.EXPECT().Commit().Return(nil).Times(0) - mockOrmer.EXPECT().Begin().Return(nil).Times(5) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(0) - mockOrmer.EXPECT().Insert(gomock.Any()).Return(test.insertReturnInt, test.insertReturnErr).Times(5) - mockQuerySeter.EXPECT().Delete().Return(test.deleteReturnInt, test.deleteReturnErr).Times(0) - mockQuerySeter.EXPECT().Update(gomock.Any()).Return(test.updateReturnInt, test.updateReturnErr).Times(0) - mockQuerySeter.EXPECT().All(gomock.Any()).SetArg(0, *fakeDevice).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(1) - mockQuerySeter.EXPECT().All(gomock.Any()).SetArg(0, *fakeDeviceAttr).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(1) - mockQuerySeter.EXPECT().All(gomock.Any()).SetArg(0, *fakeDeviceTwin).Return(test.allReturnInt, test.allReturnErr).Times(1) - mockQuerySeter.EXPECT().Filter(gomock.Any(), gomock.Any()).Return(test.filterReturn).Times(1) - mockOrmer.EXPECT().QueryTable(gomock.Any()).Return(test.queryTableReturn).Times(1) - if err := DealDeviceTwin(test.context, test.deviceID, test.eventID, test.msgTwin, test.dealType); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealDeviceTwinTrans() case failed: got = %v, Want = %v", err, test.err) - } - }) - } -} - -// TestDealVersion is function to test dealVersion -func TestDealVersion(t *testing.T) { - twinCloudEdgeVersion := dttype.TwinVersion{ - CloudVersion: 1, - EdgeVersion: 1, - } - twinCloudVersion := dttype.TwinVersion{ - CloudVersion: 1, - EdgeVersion: 0, - } - - tests := []struct { - name string - version *dttype.TwinVersion - reqVersion *dttype.TwinVersion - dealType int - errorWant bool - err error - }{ - { - name: "TestDealVersion(): Case 1: dealType=3", - version: &dttype.TwinVersion{}, - dealType: SyncTwinDeleteDealType, - errorWant: true, - err: nil, - }, - { - name: "TestDealVersion(): Case 2: dealType>=1 && version.EdgeVersion>reqVersion.EdgeVersion", - version: &twinCloudEdgeVersion, - reqVersion: &twinCloudVersion, - dealType: SyncDealType, - errorWant: false, - err: errors.New("Not allowed to sync due to version conflict"), - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got, err := dealVersion(test.version, test.reqVersion, test.dealType) - if !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealVersion() case failed: got = %v, Want = %v", err, test.err) - return - } - if !reflect.DeepEqual(got, test.errorWant) { - t.Errorf("DTManager.TestDealVersion() case failed: got = %v, want %v", got, test.errorWant) - } - }) - } -} - -// TestDealTwinDelete is function to test dealTwinDelete -func TestDealTwinDelete(t *testing.T) { - optionTrue := true - optionFalse := false - str := typeString - doc := make(map[string]*dttype.TwinDoc) - doc[key1] = &dttype.TwinDoc{} - sync := make(map[string]*dttype.MsgTwin) - sync[key1] = &dttype.MsgTwin{ - Expected: twinValueFunc(), - Actual: twinValueFunc(), - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - } - result := make(map[string]*dttype.MsgTwin) - result[key1] = &dttype.MsgTwin{} - - tests := []struct { - name string - returnResult *dttype.DealTwinResult - deviceID string - key string - twin *dttype.MsgTwin - msgTwin *dttype.MsgTwin - dealType int - err error - }{ - { - name: "TestDealTwinDelete(): Case 1: msgTwin is not nil; isChange is false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - }, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeString}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinDelete(): Case 2: hasTwinExpected is true; dealVersion() returns false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeString}, - ExpectedVersion: &dttype.TwinVersion{CloudVersion: 1}, - }, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{CloudVersion: 0}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinDelete(): Case 3: hasTwinActual is true; dealVersion() returns false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeString}, - ActualVersion: &dttype.TwinVersion{CloudVersion: 1}, - }, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{CloudVersion: 0}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinDelete(): Case 4: hasTwinExpected is true; hasTwinActual is true", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeString}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: RestDealType, - err: nil, - }, - { - name: "TestDealTwinDelete(): Case 5: hasTwinExpected is true; hasTwinActual is false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeString}, - ExpectedVersion: &dttype.TwinVersion{}, - }, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if err := dealTwinDelete(test.returnResult, test.deviceID, test.key, test.twin, test.msgTwin, test.dealType); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealTwinDelete() case failed: got = %+v, Want = %+v", err, test.err) - } - }) - } -} - -// TestDealTwinCompare is function to test dealTwinCompare -func TestDealTwinCompare(t *testing.T) { - optionTrue := true - optionFalse := false - str := typeString - doc := make(map[string]*dttype.TwinDoc) - doc[key1] = &dttype.TwinDoc{} - sync := make(map[string]*dttype.MsgTwin) - sync[key1] = &dttype.MsgTwin{ - Expected: twinValueFunc(), - Actual: twinValueFunc(), - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - } - result := make(map[string]*dttype.MsgTwin) - result[key1] = &dttype.MsgTwin{} - - tests := []struct { - name string - returnResult *dttype.DealTwinResult - deviceID string - key string - twin *dttype.MsgTwin - msgTwin *dttype.MsgTwin - dealType int - err error - }{ - { - name: "TestDealTwinCompare(): Case 1: msgTwin nil", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - }, - dealType: RestDealType, - err: nil, - }, - { - name: "TestDealTwinCompare(): Case 2: actualOk is false; actualErr is not nil", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - }, - msgTwin: &dttype.MsgTwin{ - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeInt}, - }, - dealType: RestDealType, - err: errors.New("the value is not int"), - }, - { - name: "TestDealTwinCompare(): Case 3: expectedOk is true; dealVersion() returns false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeString}, - }, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeInt}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinCompare(): Case 4: actualOk is true; dealVersion() returns false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - }, - msgTwin: &dttype.MsgTwin{ - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeString}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinCompare(): Case 5: expectedOk is true; actualOk is true", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - }, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeString}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: RestDealType, - err: nil, - }, - { - name: "TestDealTwinCompare(): Case 6: expectedOk is false; actualOk is false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twin: &dttype.MsgTwin{ - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - }, - msgTwin: &dttype.MsgTwin{ - Optional: &optionFalse, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if err := dealTwinCompare(test.returnResult, test.deviceID, test.key, test.twin, test.msgTwin, test.dealType); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealTwinCompare() case failed: got = %+v, Want = %+v", err, test.err) - } - }) - } -} - -// TestDealTwinAdd is function to test dealTwinAdd -func TestDealTwinAdd(t *testing.T) { - optionTrue := true - str := typeString - doc := make(map[string]*dttype.TwinDoc) - doc[key1] = &dttype.TwinDoc{} - sync := make(map[string]*dttype.MsgTwin) - sync[key1] = &dttype.MsgTwin{} - result := make(map[string]*dttype.MsgTwin) - result[key1] = &dttype.MsgTwin{} - - twinDelete := make(map[string]*dttype.MsgTwin) - twinDelete[key1] = &dttype.MsgTwin{Metadata: &dttype.TypeMetadata{Type: typeDeleted}} - twinInt := make(map[string]*dttype.MsgTwin) - twinInt[key1] = &dttype.MsgTwin{Metadata: &dttype.TypeMetadata{Type: typeInt}} - - tests := []struct { - name string - returnResult *dttype.DealTwinResult - deviceID string - key string - twins map[string]*dttype.MsgTwin - msgTwin *dttype.MsgTwin - dealType int - err error - }{ - { - name: "TestDealTwinAdd(): Case 1: msgTwin nil", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - dealType: RestDealType, - err: errors.New("The request body is wrong"), - }, - { - name: "TestDealTwinAdd(): Case 2: msgTwin.Expected is not nil; dealVersion() returns false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinDelete, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinAdd(): Case 3: msgTwin.Expected is not nil; ValidateValue() returns error", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinDelete, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeInt}, - ExpectedVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinAdd(): Case 4: msgTwin.Actual is not nil; dealVersion() returns false", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinDelete, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinAdd(): Case 5: msgTwin.Actual is not nil; ValidateValue() returns error; dealType=0", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinDelete, - msgTwin: &dttype.MsgTwin{ - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeInt}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: RestDealType, - err: errors.New("the value is not int"), - }, - { - name: "TestDealTwinAdd(): Case 6: msgTwin.Actual is not nil; ValidateValue() returns error; dealType=1", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinDelete, - msgTwin: &dttype.MsgTwin{ - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeInt}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - { - name: "TestDealTwinAdd(): Case 7: msgTwin.Expected is nil; msgTwin.Actual is nil", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinInt, - msgTwin: &dttype.MsgTwin{ - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: RestDealType, - err: nil, - }, - { - name: "TestDealTwinAdd(): Case 8: msgTwin.Expected is not nil; msgTwin.Actual is not nil", - returnResult: &dttype.DealTwinResult{Document: doc, SyncResult: sync, Result: result}, - deviceID: deviceA, - key: key1, - twins: twinDelete, - msgTwin: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - ExpectedVersion: &dttype.TwinVersion{}, - ActualVersion: &dttype.TwinVersion{}, - }, - dealType: SyncDealType, - err: nil, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if err := dealTwinAdd(test.returnResult, test.deviceID, test.key, test.twins, test.msgTwin, test.dealType); !reflect.DeepEqual(err, test.err) { - t.Errorf("DTManager.TestDealTwinAdd() case failed: got = %+v, Want = %+v", err, test.err) - } - }) - } -} - -// TestDealMsgTwin is function to test DealMsgTwin -func TestDealMsgTwin(t *testing.T) { - value := "value" - str := typeString - optionTrue := true - optionFalse := false - add := make([]dtclient.DeviceTwin, 0) - deletes := make([]dtclient.DeviceDelete, 0) - update := make([]dtclient.DeviceTwinUpdate, 0) - result := make(map[string]*dttype.MsgTwin) - syncResult := make(map[string]*dttype.MsgTwin) - syncResultDevice := make(map[string]*dttype.MsgTwin) - syncResultDevice[deviceA] = &dttype.MsgTwin{} - document := make(map[string]*dttype.TwinDoc) - documentDevice := make(map[string]*dttype.TwinDoc) - documentDevice[deviceA] = &dttype.TwinDoc{LastState: nil} - documentDeviceTwin := make(map[string]*dttype.TwinDoc) - documentDeviceTwin[deviceA] = &dttype.TwinDoc{LastState: &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - }, - } - - msgTwin := make(map[string]*dttype.MsgTwin) - msgTwin[deviceB] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &value}, - Metadata: &dttype.TypeMetadata{Type: "nil"}, - } - msgTwinDevice := make(map[string]*dttype.MsgTwin) - msgTwinDevice[deviceA] = nil - msgTwinDeviceTwin := make(map[string]*dttype.MsgTwin) - msgTwinDeviceTwin[deviceA] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionFalse, - Metadata: &dttype.TypeMetadata{Type: typeInt}, - ActualVersion: &dttype.TwinVersion{}, - } - - context := contextFunc(deviceB) - twin := make(map[string]*dttype.MsgTwin) - twin[deviceA] = &dttype.MsgTwin{ - Expected: &dttype.TwinValue{Value: &str}, - Actual: &dttype.TwinValue{Value: &str}, - Optional: &optionTrue, - Metadata: &dttype.TypeMetadata{Type: typeDeleted}, - } - device := dttype.Device{Twin: twin} - context.DeviceList.Store(deviceA, &device) - - tests := []struct { - name string - context *dtcontext.DTContext - deviceID string - msgTwins map[string]*dttype.MsgTwin - dealType int - want dttype.DealTwinResult - }{ - { - name: "TestDealMsgTwin(): Case1: invalid device id", - context: &context, - deviceID: deviceC, - msgTwins: msgTwin, - dealType: RestDealType, - want: dttype.DealTwinResult{ - Add: add, - Delete: deletes, - Update: update, - Result: result, - SyncResult: syncResult, - Document: document, - Err: errors.New("invalid device id"), - }, - }, - { - name: "TestDealMsgTwin(): Case 2: dealTwinCompare error", - context: &context, - deviceID: deviceA, - msgTwins: msgTwinDeviceTwin, - dealType: RestDealType, - want: dttype.DealTwinResult{ - Add: add, - Delete: deletes, - Update: update, - Result: result, - SyncResult: syncResultDevice, - Document: documentDevice, - Err: errors.New("the value is not int"), - }, - }, - { - name: "TestDealMsgTwin(): Case 3: Success case", - context: &context, - deviceID: deviceA, - msgTwins: msgTwinDevice, - dealType: RestDealType, - want: dttype.DealTwinResult{ - Add: add, - Delete: deletes, - Update: update, - Result: result, - SyncResult: syncResultDevice, - Document: documentDeviceTwin, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := DealMsgTwin(tt.context, tt.deviceID, tt.msgTwins, tt.dealType); !reflect.DeepEqual(got, tt.want) { - t.Errorf("DTManager.DealMsgTwin() case failed: got = %+v, want = %+v", got, tt.want) - } - }) - } -} diff --git a/edge/test.sh b/edge/test.sh new file mode 100644 index 00000000000..2c86f0ef2c1 --- /dev/null +++ b/edge/test.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +go test github.com/kubeedge/kubeedge/edge/pkg/eventbus/common/util +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtmodule +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin +# has issue on ARM +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtmanager +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient +go test github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype +go test github.com/kubeedge/kubeedge/edge/pkg/common/dbm +go test github.com/kubeedge/kubeedge/edge/pkg/servicebus/util +#has issue on ARM +go test github.com/kubeedge/kubeedge/edge/pkg/edgehub/config +go test github.com/kubeedge/kubeedge/edge/pkg/edgehub +go test github.com/kubeedge/kubeedge/edge/pkg/edgehub/clients +go test github.com/kubeedge/kubeedge/edge/pkg/edgehub/clients/wsclient +go test github.com/kubeedge/kubeedge/edge/pkg/edgehub/common/http +go test github.com/kubeedge/kubeedge/edge/pkg/edgehub +go test github.com/kubeedge/kubeedge/edge/pkg/metamanager/dao +go test github.com/kubeedge/kubeedge/edge/pkg/metamanager diff --git a/pkg/util/flag/flags.go b/pkg/util/flag/flags.go index eedac1f1770..47261079b1b 100644 --- a/pkg/util/flag/flags.go +++ b/pkg/util/flag/flags.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. @CHANGELOG -KubeEdge Authors: delete useless functions +KubeEdge Authors: delete useless functions. */ package flag @@ -24,7 +24,7 @@ import ( "k8s.io/klog" ) -// PrintFlags logs the flags in the flagset +// PrintFlags logs the flags in the flagset. func PrintFlags(flags *pflag.FlagSet) { flags.VisitAll(func(flag *pflag.Flag) { klog.V(1).Infof("FLAG: --%s=%q", flag.Name, flag.Value)