| 6 | ) |
| 7 | |
| 8 | func TestHookAddHandlerAndAdd(t *testing.T) { |
| 9 | calls := "" |
| 10 | |
| 11 | h := Hook[*Event]{} |
| 12 | |
| 13 | h.BindFunc(func(e *Event) error { calls += "1"; return e.Next() }) |
| 14 | h.BindFunc(func(e *Event) error { calls += "2"; return e.Next() }) |
| 15 | h3Id := h.BindFunc(func(e *Event) error { calls += "3"; return e.Next() }) |
| 16 | h.Bind(&Handler[*Event]{ |
| 17 | Id: h3Id, // should replace 3 |
| 18 | Func: func(e *Event) error { calls += "3'"; return e.Next() }, |
| 19 | }) |
| 20 | h.Bind(&Handler[*Event]{ |
| 21 | Func: func(e *Event) error { calls += "4"; return e.Next() }, |
| 22 | Priority: -2, |
| 23 | }) |
| 24 | h.Bind(&Handler[*Event]{ |
| 25 | Func: func(e *Event) error { calls += "5"; return e.Next() }, |
| 26 | Priority: -1, |
| 27 | }) |
| 28 | h.Bind(&Handler[*Event]{ |
| 29 | Func: func(e *Event) error { calls += "6"; return e.Next() }, |
| 30 | }) |
| 31 | h.Bind(&Handler[*Event]{ |
| 32 | Func: func(e *Event) error { calls += "7"; e.Next(); return errors.New("test") }, // error shouldn't stop the chain |
| 33 | }) |
| 34 | |
| 35 | h.Trigger( |
| 36 | &Event{}, |
| 37 | func(e *Event) error { calls += "8"; return e.Next() }, |
| 38 | func(e *Event) error { calls += "9"; return nil }, // skip next |
| 39 | func(e *Event) error { calls += "10"; return e.Next() }, |
| 40 | ) |
| 41 | |
| 42 | if total := len(h.handlers); total != 7 { |
| 43 | t.Fatalf("Expected %d handlers, found %d", 7, total) |
| 44 | } |
| 45 | |
| 46 | expectedCalls := "45123'6789" |
| 47 | |
| 48 | if calls != expectedCalls { |
| 49 | t.Fatalf("Expected calls sequence %q, got %q", expectedCalls, calls) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func TestHookLength(t *testing.T) { |
| 54 | h := Hook[*Event]{} |