Files
tyapi-server/internal/infrastructure/external/notification/wechat_work_service_test.go

149 lines
3.8 KiB
Go
Raw Normal View History

2026-02-25 19:33:56 +08:00
package notification_test
import (
"context"
"fmt"
"os"
"testing"
"time"
"go.uber.org/zap"
"tyapi-server/internal/infrastructure/external/notification"
)
// newTestWeChatWorkService 创建用于测试的企业微信服务实例
// 默认使用环境变量 WECOM_WEBHOOK若未设置则使用项目配置中的 webhook。
func newTestWeChatWorkService(t *testing.T) *notification.WeChatWorkService {
t.Helper()
webhook := os.Getenv("WECOM_WEBHOOK")
if webhook == "" {
// 使用你提供的 webhook 地址
webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=649bf737-28ca-4f30-ad5f-cfb65b2af113"
}
logger, _ := zap.NewDevelopment()
return notification.NewWeChatWorkService(webhook, "", logger)
}
// TestWeChatWork_SendAllBusinessNotifications
// 手动运行该用例,将依次向企业微信群推送 5 种业务场景的通知:
// 1. 用户充值成功
// 2. 用户申请开发票
// 3. 用户企业认证成功
// 4. 用户余额低于阈值
// 5. 用户余额欠费
//
// 注意:
// - 通知中只使用企业名称和手机号码不展示用户ID
// - 默认使用示例企业名称和手机号,实际使用时请根据需要修改
func TestWeChatWork_SendAllBusinessNotifications(t *testing.T) {
svc := newTestWeChatWorkService(t)
ctx := context.Background()
// 示例企业信息(实际可按需修改)
enterpriseName := "测试企业有限公司"
phone := "13800000000"
now := time.Now().Format("2006-01-02 15:04:05")
tests := []struct {
name string
content string
}{
{
name: "recharge_success",
content: fmt.Sprintf(
"### 【天远API】用户充值成功通知\n"+
"> 企业名称:%s\n"+
"> 联系手机:%s\n"+
"> 充值金额:%s 元\n"+
"> 入账总额:%s 元(含赠送)\n"+
"> 时间:%s\n",
enterpriseName,
phone,
"1000.00",
"1050.00",
now,
),
},
{
name: "invoice_applied",
content: fmt.Sprintf(
"### 【天远API】用户申请开发票\n"+
"> 企业名称:%s\n"+
"> 联系手机:%s\n"+
"> 申请开票金额:%s 元\n"+
"> 发票类型:%s\n"+
"> 申请时间:%s\n"+
"\n请财务尽快审核并开具发票。",
enterpriseName,
phone,
"500.00",
"增值税专用发票",
now,
),
},
{
name: "certification_completed",
content: fmt.Sprintf(
"### 【天远API】企业认证成功\n"+
"> 企业名称:%s\n"+
"> 联系手机:%s\n"+
"> 完成时间:%s\n"+
"\n该企业已完成认证请相关同事同步更新内部系统并关注后续接入情况。",
enterpriseName,
phone,
now,
),
},
{
name: "low_balance_alert",
content: fmt.Sprintf(
"### 【天远API】用户余额预警\n"+
"<font color=\"warning\">用户余额已低于预警阈值,请及时跟进。</font>\n"+
"> 企业名称:%s\n"+
"> 联系手机:%s\n"+
"> 当前余额:%s 元\n"+
"> 预警阈值:%s 元\n"+
"> 时间:%s\n",
enterpriseName,
phone,
"180.00",
"200.00",
now,
),
},
{
name: "arrears_alert",
content: fmt.Sprintf(
"### 【天远API】用户余额欠费告警\n"+
"<font color=\"warning\">该企业已发生欠费,请及时联系并处理。</font>\n"+
"> 企业名称:%s\n"+
"> 联系手机:%s\n"+
"> 当前余额:%s 元\n"+
"> 欠费金额:%s 元\n"+
"> 时间:%s\n",
enterpriseName,
phone,
"-50.00",
"50.00",
now,
),
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
if err := svc.SendMarkdownMessage(ctx, tc.content); err != nil {
t.Fatalf("发送场景[%s]通知失败: %v", tc.name, err)
}
// 简单间隔,避免瞬时发送过多消息
time.Sleep(500 * time.Millisecond)
})
}
}