|
| 1 | +package topics |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + . "github.com/smartystreets/goconvey/convey" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestTopicsMatch(t *testing.T) { |
| 10 | + Convey("Match should match mqtt topics correctly", t, func() { |
| 11 | + tests := []struct { |
| 12 | + pattern string |
| 13 | + topic string |
| 14 | + expected bool |
| 15 | + }{ |
| 16 | + // Exact matches |
| 17 | + {"a/b/c", "a/b/c", true}, |
| 18 | + {"a/b", "a/b", true}, |
| 19 | + {"a", "a", true}, |
| 20 | + |
| 21 | + {"a/b", "a/x", false}, |
| 22 | + {"a/b", "x/b", false}, |
| 23 | + |
| 24 | + // Single-level wildcard + |
| 25 | + {"a/+/c", "a/b/c", true}, |
| 26 | + {"a/+/c", "a/x/c", true}, |
| 27 | + {"+/+/+", "a/b/c", true}, |
| 28 | + {"+/b/+", "a/b/c", true}, |
| 29 | + {"a/b/+", "a/b/c", true}, |
| 30 | + {"+", "a", true}, |
| 31 | + |
| 32 | + {"a/+/c", "a/x/x", false}, |
| 33 | + |
| 34 | + // Wrong segment count with + |
| 35 | + {"a/+/c", "a/c", false}, |
| 36 | + {"a/+/c", "a/b/c/d", false}, |
| 37 | + {"+/+", "a", false}, |
| 38 | + {"+/+", "a/b/c", false}, |
| 39 | + |
| 40 | + // Multi-level wildcard # |
| 41 | + {"a/b/#", "a/b", true}, |
| 42 | + {"a/b/#", "a/b/c", true}, |
| 43 | + {"a/b/#", "a/b/c/d/e", true}, |
| 44 | + {"#", "a", true}, |
| 45 | + {"#", "a/b/c", true}, |
| 46 | + {"#", "/", true}, |
| 47 | + {"#", "//", true}, |
| 48 | + |
| 49 | + {"a/b/#", "a", false}, |
| 50 | + {"a/b/#", "a/x/c", false}, |
| 51 | + |
| 52 | + // # cannot match middle segments |
| 53 | + {"a/#/c", "a/b/c", false}, |
| 54 | + |
| 55 | + // Pattern longer than topic |
| 56 | + {"a/b/c/d", "a/b/c", false}, |
| 57 | + {"a/b/+", "a/b", false}, |
| 58 | + |
| 59 | + // Topic longer than pattern |
| 60 | + {"a/b", "a/b/c", false}, |
| 61 | + {"a/b/c", "a/b/c/d", false}, |
| 62 | + {"a/b/+", "a/b/c/d", false}, |
| 63 | + |
| 64 | + // Empty topic and pattern |
| 65 | + {"", "", true}, |
| 66 | + {"#", "", true}, |
| 67 | + {"+", "", true}, |
| 68 | + |
| 69 | + {"", "a", false}, |
| 70 | + |
| 71 | + // Trailing slashes |
| 72 | + {"a/b/", "a/b/", true}, |
| 73 | + |
| 74 | + {"a/b", "a/b/", false}, |
| 75 | + {"a/b/", "a/b", false}, |
| 76 | + |
| 77 | + // Topic with empty segments |
| 78 | + {"a//c", "a//c", true}, |
| 79 | + {"a/+/c", "a//c", true}, |
| 80 | + } |
| 81 | + |
| 82 | + for i, test := range tests { |
| 83 | + Convey(fmt.Sprintf("#%d: Match(%s, %s)", i, test.pattern, test.topic), func() { |
| 84 | + result := Match(test.pattern, test.topic) |
| 85 | + |
| 86 | + if result != test.expected { |
| 87 | + fmt.Printf("\nFAILED test #%d: pattern=%q topic=%q → got=%v, expected=%v\n", i, test.topic, test.pattern, result, test.expected) |
| 88 | + } |
| 89 | + |
| 90 | + So(result, ShouldEqual, test.expected) |
| 91 | + }) |
| 92 | + } |
| 93 | + }) |
| 94 | +} |
0 commit comments