package test import ( "encoding/json" "errors" "fmt" "path/filepath" "runtime" "strconv" "strings" "sws_xcx/models" _ "sws_xcx/routers" "sws_xcx/service" "sws_xcx/utils" "testing" //beego "github.com/beego/beego/v2/server/web" //"github.com/beego/beego/v2/core/logs" "github.com/astaxie/beego" "github.com/jinzhu/gorm" "github.com/medivhzhan/weapp/v3/auth" // "github.com/smartystreets/goconvey/convey" ) func init() { _, file, _, _ := runtime.Caller(0) apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator)))) beego.TestBeegoInit(apppath) } // TestGet is a sample to run an endpoint test func TestGet(t *testing.T) { // r, _ := http.NewRequest("GET", "/v1/object", nil) // w := httptest.NewRecorder() // beego.BeeApp.Handlers.ServeHTTP(w, r) // logs.Info("testing", "TestGet", "Code[%d]\n%s", w.Code, w.Body.String()) // Convey("Subject: Test Station Endpoint\n", t, func() { // Convey("Status Code Should Be 200", func() { // So(w.Code, ShouldEqual, 200) // }) // Convey("The Result Should Not Be Empty", func() { // So(w.Body.Len(), ShouldBeGreaterThan, 0) // }) // }) t.Log("TestGet") } func TestWxappSessionCode(t *testing.T) { sdk := service.GetWxSdk() wxcli := sdk.NewAuth() code := "0d3eVp100qtUES1jgD300t5yN21eVp1t" resp, err := wxcli.Code2Session(&auth.Code2SessionRequest{JsCode: code, GrantType: "authorization_code", Appid: beego.AppConfig.String("appid"), Secret: beego.AppConfig.String("appsecret")}) if err != nil { t.Error(err) return } if resp.CommonError.ErrCode != 0 { t.Errorf("err code:%v msg:%v", resp.CommonError.ErrCode, resp.CommonError.ErrMSG) return } t.Logf("resp: %+v", *resp) } func TestJson(t *testing.T) { req := `{"id":1,"nick_name":"zhangsan","ctime":"2019-11-20 16:49:08"}` u := models.UserInfoResp{} err := json.Unmarshal([]byte(req), &u) if err != nil { t.Error(err) } t.Logf("u:%+v", u) } func TestHandleMsg(t *testing.T) { req := []byte(`{"publish_received_at":1722839054218,"pub_props":{"User-Property":{}},"peerhost":"124.133.43.122","qos":0,"topic":"/CH-U100/09012201100010104/user/checkresult","clientid":"42915152F3F1","payload":"{\"productKey\":\"CH-U100\",\"deviceName\":\"09012201100010104\",\"acc\":12378,\"type\":0,\"count\":14,\"datatype\":0,\"verifycode\":212,\"data\":\"0,0,0,2,2,0,0,0,0,0,4,3,0,1\",\"origin\":\"4243305A0000010E0000000202000000000004030001D4\",\"len\":23}","username":"09012201100010104","event":"message.publish","metadata":{"rule_id":"checkresult"},"timestamp":1722839054218,"node":"emqx@127.0.0.1","id":"00061EE9B9D4F6AFF445000924860003","flags":{"retain":false,"dup":false}}`) const EventType string = "emq" msg := &models.OpenEmqMsgReqV0{} err := json.Unmarshal(req, msg) if err != nil { t.Error(err) } ds := service.NewDeviceService() device, err := ds.GetDeviceByNo(msg.DeviceName) if err != nil && err != gorm.ErrRecordNotFound { utils.ErrorLog("GetDeviceByNo %v:", err) t.Error(err) } if device == nil { utils.WarningLog("非本系统设备,数据废弃") return } err = ds.CreateDeviceMessageLog(models.DeviceMessageLog{ DeviceName: msg.DeviceName, Content: string(req), EventType: EventType, MessageId: msg.Id, Topic: msg.Topic, }) if err != nil { utils.ErrorLog("CreateDeviceMessageLog %v:", err) t.Error(err) } payload := &models.OpenEmqPayloadReqVO{} err = json.Unmarshal([]byte(msg.Payload), payload) if err != nil { utils.ErrorLog("json.Unmarshal %v:", err) t.Error(err) } if payload.Len != 23 { utils.WarningLog("非标准数据,数据废弃:%v", msg.Payload) } dr, err := ds.GetDeviceRelateByDeviceId(device.Id) if err != nil { utils.ErrorLog("GetDeviceRelateByDeviceId %v:", err) t.Error(err) } checkRecord := &models.CheckRecord{ Acc: payload.Acc, PutSources: EventType, MessageId: msg.Id, DeviceId: device.Id, UserId: dr.UserId, DeviceStatus: device.Status, } if dr.UserId > 0 { hp, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(dr.UserId) if err != nil { utils.ErrorLog("GetUserHealthProfileByUserId %v:", err) t.Error(err) } checkRecord.UserHealthProfileId = int64(hp.Id) } crs := service.NewCheckRecordService() err = crs.CreateCheckRecord(checkRecord) if err != nil { utils.ErrorLog("CreateCheckRecord %v:", err) t.Error(err) } t.Log(checkRecord.Id) t.Log(payload.Data) da := strings.Split(payload.Data, ",") count := payload.Count if len(da) != count { t.Logf("数据长度不匹配,截取存储 %+v", payload) if len(da) < count { count = len(da) } } checkItems, err := service.NewCheckItemService().GetCheckItems("cn", device.DeviceType) if err != nil { utils.ErrorLog("GetCheckItems %v:", err) t.Error(err) } if len(checkItems) < count { t.Error("接收的数据于检查项目配置不一致") } alerts := make([]string, 0) for i := 0; i < count; i++ { vi, _ := strconv.Atoi(da[i]) err = createCheckRecordItem(checkItems, checkRecord.Id, alerts, vi, i+1) if err != nil { utils.ErrorLog("createCheckRecordItem valule:%v, err:%v:", vi, err) } } if len(alerts) > 0 { //save alerts } } func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts []string, vi, n int) error { item := findItem(items, n) if item == nil { return fmt.Errorf("检测项目不匹配,需要检查基础数据!序号:%v", n) } cri := models.CheckRecordItem{ CheckId: crId, CheckItemId: n, CheckValueIndex: vi, } scopes := []*models.CheckItemScopeVO{} err := json.Unmarshal([]byte(item.ScopeList), &scopes) if err != nil { return fmt.Errorf("检测项目数值范围定义不正确 err:%v", err) } scope := findScope(scopes, vi) if scope == nil { return errors.New("检测结果不匹配") } cri.CheckValue = scope.Value if scope.Type == 1 { alerts = append(alerts, strconv.Itoa(n)) } //create cri return nil } func findScope(scopes []*models.CheckItemScopeVO, vi int) *models.CheckItemScopeVO { for _, scope := range scopes { if scope.Index == vi { return scope } } return nil } func findItem(items []*models.CheckItem, itemNumber int) *models.CheckItem { //循环items for _, item := range items { if item.CheckItemNumber == itemNumber { return item } } return nil }