package main import ( "encoding/json" "strings" "testing" ) func TestValidateConfig(t *testing.T) { cfg := &Config{Rules: []Rule{ {ID: "r1", Name: "好规则", Trigger: TriggerConfig{Type: "mouse_corner"}, Actions: []ActionConfig{{Type: "volume_up"}}}, {ID: "r2", Name: "坏触发器", Trigger: TriggerConfig{Type: "nope"}, Actions: []ActionConfig{{Type: "volume_up"}}}, {ID: "r3", Name: "空动作", Trigger: TriggerConfig{Type: "hotkey"}}, {ID: "r1", Name: "重复ID", Trigger: TriggerConfig{Type: "hotkey"}, Actions: []ActionConfig{{Type: "open_url"}}}, {ID: "r5", Name: "坏动作", Trigger: TriggerConfig{Type: "hotkey"}, Actions: []ActionConfig{{Type: "evil"}}}, }} errs := ValidateConfig(cfg) if len(errs) != 4 { t.Fatalf("errs = %d, want 4: %v", len(errs), errs) } joined := strings.Join(errs, "\n") for _, want := range []string{"未知触发器", "至少需要一个动作", "id 重复", "未知动作类型"} { if !strings.Contains(joined, want) { t.Errorf("missing error %q in: %s", want, joined) } } } func TestTriggerConfigRoundTrip(t *testing.T) { src := `{"type":"mouse_corner","corner":"bottom_left","screen":"all","threshold_px":32}` var tc TriggerConfig if err := json.Unmarshal([]byte(src), &tc); err != nil { t.Fatal(err) } if tc.Type != "mouse_corner" || tc.Params["corner"] != "bottom_left" { t.Fatalf("unmarshal wrong: %+v", tc) } out, err := json.Marshal(&tc) if err != nil { t.Fatal(err) } var back TriggerConfig if err := json.Unmarshal(out, &back); err != nil { t.Fatal(err) } if back.Type != "mouse_corner" || back.Params["threshold_px"] != float64(32) { t.Fatalf("round trip lost data: %s", out) } } func TestSanitizeRule(t *testing.T) { r := &Rule{ Trigger: TriggerConfig{Type: "hotkey", Params: map[string]any{"hotkey": " ctrl+alt+d "}}, Actions: []ActionConfig{{Type: "volume_up"}}, // params nil } sanitizeRule(r) if r.Trigger.Params["hotkey"] != "ctrl+alt+d" { t.Fatalf("hotkey not trimmed: %v", r.Trigger.Params) } if r.Actions[0].Params == nil { t.Fatal("action params should be initialized") } }