package rule import ( "context" "errors" "log/slog" "sync" "testing" "time" "zerorigin/internal/action" "zerorigin/internal/config" "zerorigin/internal/trigger" ) // fakeAction 记录执行顺序与参数的可编程动作。 type fakeAction struct { id string validate func(map[string]any) error execute func(ctx context.Context) error executed []string mu sync.Mutex block chan struct{} // 非 nil 时 Execute 阻塞等待 } func (f *fakeAction) ID() string { return f.id } func (f *fakeAction) Name() string { return f.id } func (f *fakeAction) Schema() action.ActionSchema { return action.ActionSchema{} } func (f *fakeAction) Validate(p map[string]any) error { if f.validate != nil { return f.validate(p) } return nil } func (f *fakeAction) Execute(ctx context.Context, p map[string]any) error { f.mu.Lock() f.executed = append(f.executed, f.id) f.mu.Unlock() if f.block != nil { select { case <-f.block: case <-ctx.Done(): return ctx.Err() } } if f.execute != nil { return f.execute(ctx) } return nil } func (f *fakeAction) Executed() []string { f.mu.Lock() defer f.mu.Unlock() return append([]string(nil), f.executed...) } // fakeRegistry 供测试注入的动作工厂。 type fakeRegistry struct { acts map[string]*fakeAction } func (r *fakeRegistry) newAction(id string) (action.Action, error) { a, ok := r.acts[id] if !ok { return nil, errors.New("no such action") } return a, nil } func newTestEngine(t *testing.T, reg *fakeRegistry) *Engine { logger := slog.New(slog.NewTextHandler(discard{}, nil)) e := New(logger, reg.newAction) t.Cleanup(e.Wait) return e } type discard struct{} func (discard) Write(p []byte) (int, error) { return len(p), nil } func testRule(id string, priority int, trType string, trParams map[string]any, actions []config.ActionConfig, cooldown int) *config.Rule { return &config.Rule{ ID: id, Name: id, Enabled: true, Priority: priority, Trigger: config.TriggerConfig{Type: trType, Params: trParams}, Actions: actions, CooldownMs: cooldown, } } func TestMatches(t *testing.T) { r := testRule("r1", 100, "mouse_corner", map[string]any{"corner": "bottom_left"}, nil, 0) ev := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "bottom_left"}} if !matches(r, ev) { t.Fatal("should match") } ev2 := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "top_left"}} if matches(r, ev2) { t.Fatal("different corner should not match") } ev3 := trigger.Event{Type: "mouse_edge_wheel", Payload: map[string]any{"corner": "bottom_left"}} if matches(r, ev3) { t.Fatal("different type should not match") } // 事件多余字段不参与匹配 ev4 := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "bottom_left", "direction": "up"}} if !matches(r, ev4) { t.Fatal("extra event field should not break match") } } func TestBuildSnapshotSkipsBadRules(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "a1": {id: "a1"}, }} cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("good", 100, "mouse_corner", map[string]any{"corner": "bottom_left"}, []config.ActionConfig{{Type: "a1"}}, 0), *testRule("bad-action", 100, "mouse_corner", map[string]any{"corner": "top_left"}, []config.ActionConfig{{Type: "nope"}}, 0), *testRule("bad-trigger", 100, "no_such", nil, []config.ActionConfig{{Type: "a1"}}, 0), *testRule("bad-conditions", 100, "mouse_corner", map[string]any{"corner": "top_right"}, []config.ActionConfig{{Type: "a1"}}, 0, // 注意:Conditions 手动设置 ), }} cfg.Rules[3].Conditions = []config.ConditionConfig{{Type: "x"}} snap := BuildSnapshot(cfg, reg.newAction) if len(snap.Rules) != 1 { t.Fatalf("active rules = %d, want 1", len(snap.Rules)) } if snap.BadCount != 3 { t.Fatalf("bad count = %d, want 3", snap.BadCount) } } func TestPriorityOrder(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "a": {id: "a"}, }} e := newTestEngine(t, reg) // 两条规则同触发器:低优先级在前(模拟配置顺序),高优先级应优先执行 cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("low", 10, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0), *testRule("high", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0), }} e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) // 快照应按优先级降序 snap := e.Snapshot() if snap.Rules[0].ID != "high" || snap.Rules[1].ID != "low" { t.Fatalf("sort order wrong: %s, %s", snap.Rules[0].ID, snap.Rules[1].ID) } e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}) time.Sleep(50 * time.Millisecond) // 高优先级执行了一次,低优先级未执行(HandleEvent 只执行第一条匹配) if got := reg.acts["a"].Executed(); len(got) != 1 { t.Fatalf("executed = %v, want exactly 1", got) } } func TestCooldown(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "a": {id: "a"}, }} e := newTestEngine(t, reg) cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 200), }} e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}} e.HandleEvent(ev) e.HandleEvent(ev) // 冷却期内:应丢弃 time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 1 { t.Fatalf("executed = %v, want 1 (cooldown should drop second)", got) } time.Sleep(250 * time.Millisecond) e.HandleEvent(ev) time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 2 { t.Fatalf("executed = %v, want 2 after cooldown", got) } } func TestErrorIsolation(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "fail": {id: "fail", execute: func(context.Context) error { return errors.New("boom") }}, "ok": {id: "ok"}, }} e := newTestEngine(t, reg) cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "fail"}, {Type: "ok"}}, 0), }} e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}) time.Sleep(50 * time.Millisecond) got := reg.acts["ok"].Executed() if len(got) != 1 { t.Fatalf("ok action executed = %v, want 1 (isolation should continue)", got) } } func TestConcurrencyGuard(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "slow": {id: "slow", block: make(chan struct{})}, }} e := newTestEngine(t, reg) cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "slow"}}, 0), }} e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}} e.HandleEvent(ev) // 启动第一个(阻塞) e.HandleEvent(ev) // 同规则执行中:丢弃 time.Sleep(50 * time.Millisecond) close(reg.acts["slow"].block) // 放行 time.Sleep(50 * time.Millisecond) if got := reg.acts["slow"].Executed(); len(got) != 1 { t.Fatalf("executed = %v, want 1 (concurrent drop)", got) } } // TestGlobalEnabled 验证全局开关:关闭时事件不触发任何规则。 func TestGlobalEnabled(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "a": {id: "a"}, }} e := newTestEngine(t, reg) cfg := &config.Config{ Global: config.GlobalConfig{Enabled: false}, Rules: []config.Rule{ *testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0), }, } snap := BuildSnapshot(cfg, reg.newAction) if snap.GlobalEnabled { t.Fatal("GlobalEnabled should be false") } e.SetSnapshot(snap) e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}) time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 0 { t.Fatalf("executed = %v, want 0 when globally disabled", got) } // 开启后应触发 cfg.Global.Enabled = true e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}) time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 1 { t.Fatalf("executed = %v, want 1 when enabled", got) } } // TestFullscreenSuppression 验证全屏抑制:默认规则忽略、allow 规则豁免、退出全屏恢复。 func TestFullscreenSuppression(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "a": {id: "a"}, "b": {id: "b"}, }} e := newTestEngine(t, reg) fs := true e.SetFullscreenProvider(func() bool { return fs }) // 两条同触发器规则:默认(ignore) + allow cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("default-rule", 200, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0), *testRule("allow-rule", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "b"}}, 0), }} cfg.Rules[1].Fullscreen = "allow" e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}} // 全屏:默认规则被忽略,allow 规则触发 fs = true e.HandleEvent(ev) time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 0 { t.Fatalf("default rule executed in fullscreen: %v", got) } if got := reg.acts["b"].Executed(); len(got) != 1 { t.Fatalf("allow rule executed = %v, want 1", got) } // 退出全屏:默认规则恢复 fs = false e.HandleEvent(ev) time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 1 { t.Fatalf("default rule executed after fullscreen = %v, want 1", got) } } // TestFullscreenProviderNil 验证未注入提供者时不抑制(默认行为兼容)。 func TestFullscreenProviderNil(t *testing.T) { reg := &fakeRegistry{acts: map[string]*fakeAction{ "a": {id: "a"}, }} e := newTestEngine(t, reg) // 不注入 provider cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{ *testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0), }} e.SetSnapshot(BuildSnapshot(cfg, reg.newAction)) e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}) time.Sleep(50 * time.Millisecond) if got := reg.acts["a"].Executed(); len(got) != 1 { t.Fatalf("executed = %v, want 1 (no provider = no suppression)", got) } }