sms_notifications_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package server
  2. import (
  3. "strings"
  4. "testing"
  5. "time"
  6. )
  7. func TestSMSNotificationTextMatchesUserFacingTemplate(t *testing.T) {
  8. location := time.FixedZone("UTC+8", 8*60*60)
  9. previousLocation := time.Local
  10. time.Local = location
  11. t.Cleanup(func() { time.Local = previousLocation })
  12. message := smsNotification{
  13. DeviceID: "device-1", DeviceLabel: "EC20", Number: "+447386",
  14. Time: time.Date(2026, 8, 8, 17, 25, 35, 0, location), Content: "你好鸭",
  15. }
  16. want := "收到新短信\n设备 EC20\n号码 +447386\n时间 2026-08-08 17:25:35\n内容 你好鸭"
  17. if got := message.Text(); got != want {
  18. t.Fatalf("smsNotification.Text() = %q, want %q", got, want)
  19. }
  20. if strings.HasPrefix(message.DetailText(), "收到新短信") {
  21. t.Fatalf("DetailText() unexpectedly repeats the title: %q", message.DetailText())
  22. }
  23. }
  24. func TestRenderSMSWebhookTemplate(t *testing.T) {
  25. message := smsNotification{
  26. DeviceID: "device-1", DeviceName: "客厅", DeviceLabel: "EC20",
  27. Number: "+447386", Time: time.Unix(1_700_000_000, 0), Content: "hello",
  28. }
  29. got := renderSMSWebhookTemplate("{{event}}|{{device_id}}|{{device_name}}|{{device_label}}|{{number}}|{{text}}|{{content}}", message)
  30. want := "sms.received|device-1|客厅|EC20|+447386|hello|hello"
  31. if got != want {
  32. t.Fatalf("renderSMSWebhookTemplate() = %q, want %q", got, want)
  33. }
  34. }
  35. func TestValidateSMSNotificationConfig(t *testing.T) {
  36. valid := map[string]map[string]any{
  37. "bark": {"urls": []any{"https://api.day.app/key"}},
  38. "email": {"smtp_host": "smtp.example.com", "from_address": "[email protected]", "to_addresses": []any{"[email protected]"}},
  39. "pushplus": {"token": "secret"},
  40. "webhook": {"urls": []any{"https://example.com/hook"}},
  41. }
  42. for channel, config := range valid {
  43. if err := validateSMSNotificationConfig(channel, config); err != nil {
  44. t.Errorf("validateSMSNotificationConfig(%q) error = %v", channel, err)
  45. }
  46. }
  47. if err := validateSMSNotificationConfig("pushplus", map[string]any{}); err == nil {
  48. t.Fatal("missing Pushplus token was accepted")
  49. }
  50. }