Files
go-sms-V2/internal/service/account/service_warning_test.go
T

269 lines
8.6 KiB
Go

// service_warning_test.go(原 Day27):余额预警——阈值触发/冷却去重/可用额度/停用跳过/配置 upsert。
package account
import (
"context"
"strings"
"sync"
"testing"
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
"go-sms/internal/pkg/notify"
)
// fakeNotifier 计数型假通知器(可注入失败)。
type fakeNotifier struct {
mu sync.Mutex
calls int
titles []string
err error
}
func (f *fakeNotifier) Send(_ context.Context, title, _ string) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.err != nil {
return f.err
}
f.calls++
f.titles = append(f.titles, title)
return nil
}
func (f *fakeNotifier) count() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls
}
// newWarn27 内存库(单连接独享,完全隔离)+ 假通知器注入。
func newWarn27(t *testing.T) (*WarningService, *fakeNotifier) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if sqlDB, err := db.DB(); err == nil { // 单连接:避免 :memory: 多连接各自建库
sqlDB.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.MessageDetail{},
&entity.AccountBalanceLog{}, &entity.SystemAlertRule{}); err != nil {
t.Fatal(err)
}
fn := &fakeNotifier{}
return NewWarningService(db, func(string, string) notify.Notifier { return fn }), fn
}
// newTestServiceFromDB27 复用 WarningService 同一 db 构造账号服务(开户辅助)。
func newTestServiceFromDB27(t *testing.T, w *WarningService) *Service {
t.Helper()
return NewService(w.db, BcryptMinCost)
}
// TestWarning_TriggerAndNotify 验收:余额低于阈值 → 1 轮扫描内收到告警。
func TestWarning_TriggerAndNotify(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, err := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-cust", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err != nil {
t.Fatal(err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{
Threshold: 200, NotifyType: "wechat", NotifyTo: "http://hook/x",
}); err != nil {
t.Fatal(err)
}
res, err := w.ScanOnce(ctx)
if err != nil {
t.Fatal(err)
}
if res.Rules != 1 || res.Triggered != 1 || fn.count() != 1 {
t.Fatalf("rules/triggered/notified = %d/%d/%d, 期望 1/1/1", res.Rules, res.Triggered, fn.count())
}
}
// TestWarning_CooldownDedup 验收:同账号冷却期内不重复通知;冷却过后恢复。
func TestWarning_CooldownDedup(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-cool", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 100, CooldownMin: 30}); err != nil {
t.Fatal(err)
}
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
for i := 0; i < 3; i++ { // 冷却期内再扫 3 轮:不再通知
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
}
if fn.count() != 1 {
t.Fatalf("冷却期内通知次数 = %d, 期望 1", fn.count())
}
// 回拨 LastAlertAt 超过冷却 → 恢复通知
past := time.Now().Add(-time.Hour)
if err := w.db.WithContext(ctx).Model(&entity.SystemAlertRule{}).
Where("target_id = ?", u.ID).Update("last_alert_at", past).Error; err != nil {
t.Fatal(err)
}
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
if fn.count() != 2 {
t.Fatalf("冷却过后应再次通知, 次数 = %d", fn.count())
}
}
// TestWarning_NotifyFailRetry 通知失败不写 LastAlertAt → 下轮重试成功。
func TestWarning_NotifyFailRetry(t *testing.T) {
w, fn := newWarn27(t)
fn.err = context.Canceled // 先制造失败
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-retry", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 100, CooldownMin: 30})
if res, _ := w.ScanOnce(ctx); res.Triggered != 0 {
t.Fatal("失败轮不应计入 triggered")
}
rule, _ := w.GetWarningConfig(ctx, u.ID)
if rule.LastAlertAt != nil {
t.Fatal("通知失败不应写 LastAlertAt")
}
fn.err = nil // 恢复
if res, _ := w.ScanOnce(ctx); res.Triggered != 1 {
t.Fatal("下轮应重试成功")
}
}
// TestWarning_CreditCounts 可用额度=余额+授信:透支额度充足不告警。
func TestWarning_CreditCounts(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-credit", Password: "secret66", Role: "customer", Business: BusinessSMS,
CreditBalance: 5000,
})
// 余额 0 + 授信 5000,阈值 2000 → 可用 5000 ≥ 2000 不触发
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 2000})
if res, _ := w.ScanOnce(ctx); res.Triggered != 0 || fn.count() != 0 {
t.Fatal("授信额度充足不应告警")
}
// 阈值 8000 > 5000 → 触发(配置变更重置冷却)
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 8000})
if res, _ := w.ScanOnce(ctx); res.Triggered != 1 {
t.Fatal("可用额度低于阈值应告警")
}
}
// TestWarning_SkipDisabled 规则停用/账号禁用均跳过。
func TestWarning_SkipDisabled(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u1, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-off-rule", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
u2, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-off-acct", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
_ = w.SetWarningConfig(ctx, u1.ID, &WarningConfig{Threshold: 100})
_ = w.SetWarningConfig(ctx, u2.ID, &WarningConfig{Threshold: 100})
if err := w.DisableWarningConfig(ctx, u1.ID); err != nil {
t.Fatal(err)
}
if err := s.SetStatus(ctx, u2.ID, 0); err != nil { // 账号禁用
t.Fatal(err)
}
if res, _ := w.ScanOnce(ctx); res.Triggered != 0 {
t.Fatal("规则停用/账号禁用均不应触发")
}
if fn.count() != 0 {
t.Fatal("不应发出任何通知")
}
}
// TestWarningConfig_Validation 参数校验与 upsert。
func TestWarningConfig_Validation(t *testing.T) {
w, _ := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-cfg", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 0}); err == nil {
t.Fatal("阈值 0 应 400")
} else if b, ok := err.(*errs.Error); !ok || b.Code != errs.InvalidParam.Code {
t.Fatalf("应 ISC:400: %v", err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 10, NotifyType: "sms"}); err == nil {
t.Fatal("sms 渠道应 400")
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 10, CooldownMin: 2000}); err == nil {
t.Fatal("冷却超 1440 应 400")
}
// upsert:两次设置仅一条规则且参数更新
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 10, CooldownMin: 5}); err != nil {
t.Fatal(err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 20, CooldownMin: 10}); err != nil {
t.Fatal(err)
}
rule, err := w.GetWarningConfig(ctx, u.ID)
if err != nil || rule == nil {
t.Fatalf("规则应存在: %v", err)
}
if rule.Threshold != 20 || rule.CooldownMin != 10 {
t.Fatalf("upsert 参数未更新: %+v", rule)
}
var n int64
w.db.WithContext(ctx).Model(&entity.SystemAlertRule{}).Where("target_id = ?", u.ID).Count(&n)
if n != 1 {
t.Fatalf("规则条数 = %d, 期望 1", n)
}
if err := w.SetWarningConfig(ctx, 99999, &WarningConfig{Threshold: 10}); err == nil {
t.Fatal("不存在账号应报错")
}
if r, _ := w.GetWarningConfig(ctx, 88888); r != nil {
t.Fatal("未配置应返回 nil")
}
}
// TestWarning_ContentContainsContext 告警标题完整(信息可辨识)。
func TestWarning_ContentContainsContext(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-ctx", Password: "secret66", Role: "customer", Business: BusinessSMS,
CreditBalance: 77,
})
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 500})
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
fn.mu.Lock()
defer fn.mu.Unlock()
if fn.calls != 1 {
t.Fatal("应通知一次")
}
if !strings.Contains(fn.titles[0], "余额预警") {
t.Fatalf("标题异常: %q", fn.titles[0])
}
}