Files
ARTEX-chixuweihu/server/schedule_tools_test.go
T
ji ruo e6241dda09 feat(chat,proxy): add @schedule mentions and localize proxy/schedule errors
- Support @schedule mentions in DB search, server mention resolution, and frontend mention parsing/i18n.
- Return structured product error codes for proxy route validation and localize them in proxy/schedule UI.
- Preserve unchanged proxy routes when rescheduling an existing schedule whose pool has no active nodes.
2026-12-03 14:15:52 +08:00

170 lines
5.9 KiB
Go

package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestChatMentionScheduleParsing(t *testing.T) {
refs, err := parseChatMentions("请修改 @[计划任务#3 夜间扫描] 和 @[schedule#3 重复] 以及 @[schedule#9 应急复测] 和 @[计划#12 周末巡检]")
if err != nil {
t.Fatalf("parseChatMentions error: %v", err)
}
if len(refs) != 3 {
t.Fatalf("expected 3 deduplicated schedule refs, got %+v", refs)
}
for i, wantID := range []int64{3, 9, 12} {
if refs[i].Kind != "schedule" || refs[i].ID != wantID {
t.Fatalf("ref[%d] = %+v, want schedule #%d", i, refs[i], wantID)
}
}
}
func TestChatScheduleToolsAndServerClock(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
if dsn == "" {
t.Skip("requires ARTEX_PG_DSN")
}
pg, err := db.Open(dsn)
if err != nil {
t.Fatalf("open pg: %v", err)
}
defer pg.Close()
m := &Manager{
pg: pg,
dir: t.TempDir(),
tasks: map[string]*Task{},
proxyPool: &proxyPoolState{
active: "pool-1",
entries: []proxyPoolEntry{
{
ProxyPoolEntry: ProxyPoolEntry{ID: "pool-1", Name: "Node1", URL: "http://127.0.0.1:19801", Enabled: true, Health: "healthy"},
RawURL: "http://127.0.0.1:19801",
},
},
},
globalProxy: "http://127.0.0.1:19801",
}
s := &Server{m: m}
s.initProxyRoutesAndGateway()
task, err := m.CreateTask("calendar-chat-task", "test calendar creation from chat", nil, 0, 0)
if err != nil {
t.Fatalf("CreateTask: %v", err)
}
// 1. Create schedule from chat tool with proxy_mode=pool.
createTool := s.toolCreateTaskSchedule()
in := fmt.Sprintf(`{"name":"工作日夜间扫描","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"18:00","end_time":"23:00","task_ids":[%q],"proxy_mode":"pool"}`, task.ID)
res, err := createTool.Call(context.Background(), json.RawMessage(in), nil)
if err != nil || res.IsError {
t.Fatalf("create_task_schedule failed: err=%v res=%+v", err, res)
}
text := ""
for _, b := range res.Content {
text += b.Text
}
var created map[string]any
if err := json.Unmarshal([]byte(text), &created); err != nil {
t.Fatalf("decode create_task_schedule: %v (%s)", err, text)
}
schedID := int64(created["id"].(float64))
if created["proxy_mode"] != "pool" {
t.Fatalf("expected proxy_mode=pool, got %+v", created)
}
// Verify bound task inherited proxy_mode=pool immediately.
view, _ := s.containerProxyRouteView("task", task.ID)
if view.Mode != "pool" {
t.Fatalf("expected task route mode=pool after create_task_schedule, got %+v", view)
}
// 2. List schedules via HTTP GET /api/schedules -> verify top-level server_time & offset.
rec := httptest.NewRecorder()
s.listSchedules(rec, httptest.NewRequest(http.MethodGet, "/api/schedules", nil))
if rec.Code != http.StatusOK {
t.Fatalf("listSchedules: %d %s", rec.Code, rec.Body.String())
}
var listResp map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &listResp); err != nil {
t.Fatalf("decode listSchedules: %v", err)
}
if listResp["server_time"] == "" || listResp["server_timezone"] == "" || listResp["server_utc_offset_minutes"] == nil {
t.Fatalf("expected server clock metadata in /api/schedules, got %+v", listResp)
}
// 3. Update schedule via chat tool (partial update).
updTool := s.toolUpdateTaskSchedule()
updIn := fmt.Sprintf(`{"schedule_id":%d,"end_time":"23:45"}`, schedID)
updRes, err := updTool.Call(context.Background(), json.RawMessage(updIn), nil)
if err != nil || updRes.IsError {
t.Fatalf("update_task_schedule failed: err=%v res=%+v", err, updRes)
}
updText := ""
// 2b. Search schedule mentions via DB and compose @[schedule#ID] snapshot.
page, err := pg.SearchChatMentionsPage(context.Background(), "schedule", "工作日", "")
if err != nil {
t.Fatalf("SearchChatMentionsPage(schedule): %v", err)
}
foundMention := false
for _, item := range page.Items {
if item.Kind == "schedule" && item.ID == schedID {
foundMention = true
if !strings.Contains(item.Description, "18:00-23:45") {
t.Fatalf("expected schedule time window in mention description, got %+v", item)
}
}
}
if !foundMention {
t.Fatalf("expected schedule #%d in SearchChatMentionsPage results, got %+v", schedID, page.Items)
}
injected, err := composeChatMentionMessage(pg, fmt.Sprintf("把 @[schedule#%d 工作日夜间扫描] 改成 23:45 结束", schedID))
if err != nil {
t.Fatalf("composeChatMentionMessage(schedule): %v", err)
}
if !strings.Contains(injected, "工作日夜间扫描") || !strings.Contains(injected, `"proxy_mode":"pool"`) || !strings.Contains(injected, `"server_time"`) {
t.Fatalf("unexpected injected schedule snapshot: %s", injected)
}
for _, b := range updRes.Content {
updText += b.Text
}
if !strings.Contains(updText, "23:45") || !strings.Contains(updText, "工作日夜间扫描") {
t.Fatalf("unexpected update_task_schedule output: %s", updText)
}
// 4. List via chat tool.
listTool := s.toolListTaskSchedules()
listRes, err := listTool.Call(context.Background(), json.RawMessage(`{}`), nil)
if err != nil || listRes.IsError {
t.Fatalf("list_task_schedules failed: err=%v res=%+v", err, listRes)
}
listText := ""
for _, b := range listRes.Content {
listText += b.Text
}
if !strings.Contains(listText, `"server_time"`) || !strings.Contains(listText, "工作日夜间扫描") {
t.Fatalf("unexpected list_task_schedules output: %s", listText)
}
// 5. Delete via chat tool.
delTool := s.toolDeleteTaskSchedule()
delRes, err := delTool.Call(context.Background(), json.RawMessage(fmt.Sprintf(`{"schedule_id":%d}`, schedID)), nil)
if err != nil || delRes.IsError {
t.Fatalf("delete_task_schedule failed: err=%v res=%+v", err, delRes)
}
// Verify deleted schedule mention returns a clean input error.
if _, err := composeChatMentionMessage(pg, fmt.Sprintf("查看 @[schedule#%d 已删]", schedID)); err == nil {
t.Fatalf("expected error for deleted schedule mention")
}
}