default_test.go 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package test
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "path/filepath"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "sws_xcx/models"
  11. _ "sws_xcx/routers"
  12. "sws_xcx/service"
  13. "sws_xcx/utils"
  14. "testing"
  15. //beego "github.com/beego/beego/v2/server/web"
  16. //"github.com/beego/beego/v2/core/logs"
  17. "github.com/astaxie/beego"
  18. "github.com/jinzhu/gorm"
  19. "github.com/medivhzhan/weapp/v3/auth"
  20. // "github.com/smartystreets/goconvey/convey"
  21. )
  22. func init() {
  23. _, file, _, _ := runtime.Caller(0)
  24. apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
  25. beego.TestBeegoInit(apppath)
  26. }
  27. // TestGet is a sample to run an endpoint test
  28. func TestGet(t *testing.T) {
  29. // r, _ := http.NewRequest("GET", "/v1/object", nil)
  30. // w := httptest.NewRecorder()
  31. // beego.BeeApp.Handlers.ServeHTTP(w, r)
  32. // logs.Info("testing", "TestGet", "Code[%d]\n%s", w.Code, w.Body.String())
  33. // Convey("Subject: Test Station Endpoint\n", t, func() {
  34. // Convey("Status Code Should Be 200", func() {
  35. // So(w.Code, ShouldEqual, 200)
  36. // })
  37. // Convey("The Result Should Not Be Empty", func() {
  38. // So(w.Body.Len(), ShouldBeGreaterThan, 0)
  39. // })
  40. // })
  41. t.Log("TestGet")
  42. }
  43. func TestWxappSessionCode(t *testing.T) {
  44. sdk := service.GetWxSdk()
  45. wxcli := sdk.NewAuth()
  46. code := "0d3eVp100qtUES1jgD300t5yN21eVp1t"
  47. resp, err := wxcli.Code2Session(&auth.Code2SessionRequest{JsCode: code, GrantType: "authorization_code", Appid: beego.AppConfig.String("appid"), Secret: beego.AppConfig.String("appsecret")})
  48. if err != nil {
  49. t.Error(err)
  50. return
  51. }
  52. if resp.CommonError.ErrCode != 0 {
  53. t.Errorf("err code:%v msg:%v", resp.CommonError.ErrCode, resp.CommonError.ErrMSG)
  54. return
  55. }
  56. t.Logf("resp: %+v", *resp)
  57. }
  58. func TestJson(t *testing.T) {
  59. req := `{"id":1,"nick_name":"zhangsan","ctime":"2019-11-20 16:49:08"}`
  60. u := models.UserInfoResp{}
  61. err := json.Unmarshal([]byte(req), &u)
  62. if err != nil {
  63. t.Error(err)
  64. }
  65. t.Logf("u:%+v", u)
  66. }
  67. func TestHandleMsg(t *testing.T) {
  68. 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}}`)
  69. const EventType string = "emq"
  70. msg := &models.OpenEmqMsgReqV0{}
  71. err := json.Unmarshal(req, msg)
  72. if err != nil {
  73. t.Error(err)
  74. }
  75. ds := service.NewDeviceService()
  76. device, err := ds.GetDeviceByNo(msg.DeviceName)
  77. if err != nil && err != gorm.ErrRecordNotFound {
  78. utils.ErrorLog("GetDeviceByNo %v:", err)
  79. t.Error(err)
  80. }
  81. if device == nil {
  82. utils.WarningLog("非本系统设备,数据废弃")
  83. return
  84. }
  85. err = ds.CreateDeviceMessageLog(models.DeviceMessageLog{
  86. DeviceName: msg.DeviceName,
  87. Content: string(req),
  88. EventType: EventType,
  89. MessageId: msg.Id,
  90. Topic: msg.Topic,
  91. })
  92. if err != nil {
  93. utils.ErrorLog("CreateDeviceMessageLog %v:", err)
  94. t.Error(err)
  95. }
  96. payload := &models.OpenEmqPayloadReqVO{}
  97. err = json.Unmarshal([]byte(msg.Payload), payload)
  98. if err != nil {
  99. utils.ErrorLog("json.Unmarshal %v:", err)
  100. t.Error(err)
  101. }
  102. if payload.Len != 23 {
  103. utils.WarningLog("非标准数据,数据废弃:%v", msg.Payload)
  104. }
  105. dr, err := ds.GetDeviceRelateByDeviceId(device.Id)
  106. if err != nil {
  107. utils.ErrorLog("GetDeviceRelateByDeviceId %v:", err)
  108. t.Error(err)
  109. }
  110. checkRecord := &models.CheckRecord{
  111. Acc: payload.Acc,
  112. PutSources: EventType,
  113. MessageId: msg.Id,
  114. DeviceId: device.Id,
  115. UserId: dr.UserId,
  116. DeviceStatus: device.Status,
  117. }
  118. if dr.UserId > 0 {
  119. hp, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(dr.UserId)
  120. if err != nil {
  121. utils.ErrorLog("GetUserHealthProfileByUserId %v:", err)
  122. t.Error(err)
  123. }
  124. checkRecord.UserHealthProfileId = int64(hp.Id)
  125. }
  126. crs := service.NewCheckRecordService()
  127. err = crs.CreateCheckRecord(checkRecord)
  128. if err != nil {
  129. utils.ErrorLog("CreateCheckRecord %v:", err)
  130. t.Error(err)
  131. }
  132. t.Log(checkRecord.Id)
  133. t.Log(payload.Data)
  134. da := strings.Split(payload.Data, ",")
  135. count := payload.Count
  136. if len(da) != count {
  137. t.Logf("数据长度不匹配,截取存储 %+v", payload)
  138. if len(da) < count {
  139. count = len(da)
  140. }
  141. }
  142. checkItems, err := service.NewCheckItemService().GetCheckItems("cn", device.DeviceType)
  143. if err != nil {
  144. utils.ErrorLog("GetCheckItems %v:", err)
  145. t.Error(err)
  146. }
  147. if len(checkItems) < count {
  148. t.Error("接收的数据于检查项目配置不一致")
  149. }
  150. alerts := make([]string, 0)
  151. for i := 0; i < count; i++ {
  152. vi, _ := strconv.Atoi(da[i])
  153. err = createCheckRecordItem(checkItems, checkRecord.Id, alerts, vi, i+1)
  154. if err != nil {
  155. utils.ErrorLog("createCheckRecordItem valule:%v, err:%v:", vi, err)
  156. }
  157. }
  158. if len(alerts) > 0 {
  159. //save alerts
  160. }
  161. }
  162. func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts []string, vi, n int) error {
  163. item := findItem(items, n)
  164. if item == nil {
  165. return fmt.Errorf("检测项目不匹配,需要检查基础数据!序号:%v", n)
  166. }
  167. cri := models.CheckRecordItem{
  168. CheckId: crId,
  169. CheckItemId: n,
  170. CheckValueIndex: vi,
  171. }
  172. scopes := []*models.CheckItemScopeVO{}
  173. err := json.Unmarshal([]byte(item.ScopeList), &scopes)
  174. if err != nil {
  175. return fmt.Errorf("检测项目数值范围定义不正确 err:%v", err)
  176. }
  177. scope := findScope(scopes, vi)
  178. if scope == nil {
  179. return errors.New("检测结果不匹配")
  180. }
  181. cri.CheckValue = scope.Value
  182. if scope.Type == 1 {
  183. alerts = append(alerts, strconv.Itoa(n))
  184. }
  185. //create cri
  186. return nil
  187. }
  188. func findScope(scopes []*models.CheckItemScopeVO, vi int) *models.CheckItemScopeVO {
  189. for _, scope := range scopes {
  190. if scope.Index == vi {
  191. return scope
  192. }
  193. }
  194. return nil
  195. }
  196. func findItem(items []*models.CheckItem, itemNumber int) *models.CheckItem {
  197. //循环items
  198. for _, item := range items {
  199. if item.CheckItemNumber == itemNumber {
  200. return item
  201. }
  202. }
  203. return nil
  204. }