From 3173e66166fee58f05c576891ca0c30dfd1e5331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=B9=BF?= Date: Thu, 19 Sep 2024 16:19:02 +0800 Subject: [PATCH] add testcase --- main.go | 2 ++ main_test.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 main_test.go diff --git a/main.go b/main.go index ea2a26d..21455c0 100644 --- a/main.go +++ b/main.go @@ -27,6 +27,8 @@ func (e *EventEmitter) Once(event string, callback func(args ...interface{})) { defer e.lock.Unlock() if _, ok := e.onceCallbacks[event]; !ok { + e.onceCallbacks[event] = []func(args ...interface{}){callback} + } else { e.onceCallbacks[event] = append(e.onceCallbacks[event], callback) } } diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..bf45291 --- /dev/null +++ b/main_test.go @@ -0,0 +1,60 @@ +package goemitter + +import ( + "testing" + "time" +) + +func TestEventEmitter_Emit(t *testing.T) { + emitter := &EventEmitter{ + callbacks: make(map[string][]func(args ...interface{})), + onceCallbacks: make(map[string][]func(args ...interface{})), + } + + // 注册一个普通回调函数 + emitter.callbacks["testEvent"] = append(emitter.callbacks["testEvent"], func(data ...interface{}) { + t.Log("普通回调函数被调用") + }) + + // 注册一个一次性回调函数 + emitter.onceCallbacks["testEvent"] = append(emitter.onceCallbacks["testEvent"], func(data ...interface{}) { + t.Log("一次性回调函数被调用") + }) + + // 触发事件 + emitter.Emit("testEvent", "testData") + + // 等待一段时间,确保异步执行的回调函数完成 + time.Sleep(1 * time.Second) + if len(emitter.onceCallbacks["testEvent"]) != 0 { + t.Error("一次性回调函数没有被清除") + } +} + +func TestEventEmitter_Once(t *testing.T) { + emitter := &EventEmitter{ + onceCallbacks: make(map[string][]func(args ...interface{})), + } + + // 测试添加新事件和回调函数 + emitter.Once("event1", func(args ...interface{}) {}) + if len(emitter.onceCallbacks["event1"]) != 1 { + t.Error("一次性回调函数添加失败") + } + + // 测试添加已存在事件的回调函数 + emitter.Once("event1", func(args ...interface{}) {}) + if len(emitter.onceCallbacks["event1"]) != 2 { + t.Error("一次性回调函数再次添加失败") + } + + // 测试不存在的事件 + emitter.Once("event2", func(args ...interface{}) {}) + emitter.Emit("event1", "testData") + + // 等待一段时间,确保异步执行的回调函数完成 + time.Sleep(1 * time.Second) + if len(emitter.onceCallbacks["event1"]) != 0 { + t.Error("一次性回调函数没有被清除") + } +}