faultRecordDevices_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package services
  2. import (
  3. "encoding/json"
  4. "os"
  5. "strings"
  6. "testing"
  7. "fwh-toolbox-server/domain"
  8. )
  9. const deviceInfoHar = "../../docs/fault-record/设备信息.test.franklinwh.com.har"
  10. // 从 HAR 中取出指定接口的 result
  11. func harResult[T any](t *testing.T, api string) *T {
  12. t.Helper()
  13. b, err := os.ReadFile(deviceInfoHar)
  14. if err != nil {
  15. t.Skipf("har not found: %v", err)
  16. }
  17. var har struct {
  18. Log struct {
  19. Entries []struct {
  20. Request struct{ URL string } `json:"request"`
  21. Response struct {
  22. Content struct{ Text string } `json:"content"`
  23. } `json:"response"`
  24. } `json:"entries"`
  25. } `json:"log"`
  26. }
  27. if err := json.Unmarshal(b, &har); err != nil {
  28. t.Fatal(err)
  29. }
  30. for _, e := range har.Log.Entries {
  31. if strings.Contains(e.Request.URL, "/manage/"+api) {
  32. var res domain.FwhResponse[T]
  33. if err := json.Unmarshal([]byte(e.Response.Content.Text), &res); err != nil {
  34. t.Fatal(err)
  35. }
  36. return res.Result
  37. }
  38. }
  39. t.Fatalf("%s not in har", api)
  40. return nil
  41. }
  42. func TestBuildFaultRecordDevicesFromHar(t *testing.T) {
  43. devInfo := harResult[domain.FwhDeviceInfo](t, "getDeviceInfo")
  44. power := harResult[domain.FwhGatewayPower](t, "selectGatewayPower")
  45. got := BuildFaultRecordDevices("10070052S00X25150083", devInfo, power)
  46. var lines []string
  47. for _, d := range got {
  48. ver := -1
  49. if d.HwVer != nil {
  50. ver = *d.HwVer
  51. }
  52. lines = append(lines, d.Kind+"|"+d.Sn+"|"+d.Model+"|"+map[bool]string{true: "ok", false: "pending"}[d.Supported]+"|"+string(rune('0'+ver%10)))
  53. t.Logf("%-10s %-22s %-9s type=%-5q supported=%v hwVer=%d", d.Kind, d.Sn, d.Model, d.Type, d.Supported, ver)
  54. }
  55. want := []string{
  56. "aGate|10070052S00X25150083||ok",
  57. "aPowerPE|10050015S00W24240002|aPower 2|ok",
  58. "aPowerPE|10050019S01X25350643|aPower S|ok",
  59. "aPowerMPPT|10050019S01X25350643|aPower S|ok", // 版本 21 支持 MPPT
  60. "aHub|10070053S00X25270092||ok",
  61. }
  62. if len(got) != len(want) {
  63. t.Fatalf("devices = %d, want %d", len(got), len(want))
  64. }
  65. for i, w := range want {
  66. if !strings.HasPrefix(lines[i], w) {
  67. t.Errorf("device %d = %s, want prefix %s", i, lines[i], w)
  68. }
  69. }
  70. }
  71. func TestBuildFaultRecordDevicesFallback(t *testing.T) {
  72. // getDeviceInfo 失败时退回站点信息的 fhpSn:没有硬件版本,不生成 aPower-MPPT
  73. got := BuildFaultRecordDevices("GW", &domain.FwhDeviceInfo{FhpSn: "A1, A2"}, nil)
  74. if len(got) != 3 || got[1].Sn != "A1" || got[2].Sn != "A2" || got[2].HwVer != nil {
  75. t.Fatalf("devices = %+v", got)
  76. }
  77. }