| 1 | package session |
| 2 | |
| 3 | import ( |
| 4 | "testing" |
| 5 | ) |
| 6 | |
| 7 | func sameStrings(a []string, b []string) bool { |
| 8 | if len(a) != len(b) { |
| 9 | return false |
| 10 | } |
| 11 | for i, v := range a { |
| 12 | if v != b[i] { |
| 13 | return false |
| 14 | } |
| 15 | } |
| 16 | return true |
| 17 | } |
| 18 | |
| 19 | func assertPanic(t *testing.T, msg string, f func()) { |
| 20 | defer func() { |
| 21 | if r := recover(); r == nil { |
| 22 | t.Fatal(msg) |
| 23 | } |
| 24 | }() |
| 25 | f() |
| 26 | } |
| 27 | |
| 28 | func TestSessionCommandHandler(t *testing.T) { |
| 29 | var units = []struct { |
| 30 | expr string |
| 31 | panic bool |
| 32 | parsed []string |
| 33 | }{ |
| 34 | {"notvali(d", true, nil}, |
| 35 | {`simple\s+(\d+)`, false, []string{"123"}}, |
| 36 | } |
| 37 | |
| 38 | for _, u := range units { |
| 39 | if u.panic { |
| 40 | assertPanic(t, "", func() { |
| 41 | _ = NewCommandHandler("", u.expr, "", nil) |
| 42 | t.Fatal("panic expected") |
| 43 | }) |
| 44 | } else { |
| 45 | c := NewCommandHandler("", u.expr, "", nil) |
| 46 | shouldNotParse := "simple123" |
| 47 | shouldParse := "simple 123" |
| 48 | |
| 49 | if parsed, _ := c.Parse(shouldNotParse); parsed { |
| 50 | t.Fatalf("should not parse '%s'", shouldNotParse) |
| 51 | } else if parsed, parts := c.Parse(shouldParse); !parsed { |
| 52 | t.Fatalf("should parse '%s'", shouldParse) |
| 53 | } else if !sameStrings(parts, u.parsed) { |
| 54 | t.Fatalf("expected '%v', got '%v'", u.parsed, parts) |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } |