|
| 1 | +# Copyright 2021 The Matrix.org Foundation C.I.C. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from synapse.util import glob_to_regex |
| 15 | + |
| 16 | +from tests.unittest import TestCase |
| 17 | + |
| 18 | + |
| 19 | +class GlobToRegexTestCase(TestCase): |
| 20 | + def test_literal_match(self): |
| 21 | + """patterns without wildcards should match""" |
| 22 | + pat = glob_to_regex("foobaz") |
| 23 | + self.assertTrue( |
| 24 | + pat.match("FoobaZ"), "patterns should match and be case-insensitive" |
| 25 | + ) |
| 26 | + self.assertFalse( |
| 27 | + pat.match("x foobaz"), "pattern should not match at word boundaries" |
| 28 | + ) |
| 29 | + |
| 30 | + def test_wildcard_match(self): |
| 31 | + pat = glob_to_regex("f?o*baz") |
| 32 | + |
| 33 | + self.assertTrue( |
| 34 | + pat.match("FoobarbaZ"), |
| 35 | + "* should match string and pattern should be case-insensitive", |
| 36 | + ) |
| 37 | + self.assertTrue(pat.match("foobaz"), "* should match 0 characters") |
| 38 | + self.assertFalse(pat.match("fooxaz"), "the character after * must match") |
| 39 | + self.assertFalse(pat.match("fobbaz"), "? should not match 0 characters") |
| 40 | + self.assertFalse(pat.match("fiiobaz"), "? should not match 2 characters") |
| 41 | + |
| 42 | + def test_multi_wildcard(self): |
| 43 | + """patterns with multiple wildcards in a row should match""" |
| 44 | + pat = glob_to_regex("**baz") |
| 45 | + self.assertTrue(pat.match("agsgsbaz"), "** should match any string") |
| 46 | + self.assertTrue(pat.match("baz"), "** should match the empty string") |
| 47 | + self.assertEqual(pat.pattern, r"\A.{0,}baz\Z") |
| 48 | + |
| 49 | + pat = glob_to_regex("*?baz") |
| 50 | + self.assertTrue(pat.match("agsgsbaz"), "*? should match any string") |
| 51 | + self.assertTrue(pat.match("abaz"), "*? should match a single char") |
| 52 | + self.assertFalse(pat.match("baz"), "*? should not match the empty string") |
| 53 | + self.assertEqual(pat.pattern, r"\A.{1,}baz\Z") |
| 54 | + |
| 55 | + pat = glob_to_regex("a?*?*?baz") |
| 56 | + self.assertTrue(pat.match("a g baz"), "?*?*? should match 3 chars") |
| 57 | + self.assertFalse(pat.match("a..baz"), "?*?*? should not match 2 chars") |
| 58 | + self.assertTrue(pat.match("a.gg.baz"), "?*?*? should match 4 chars") |
| 59 | + self.assertEqual(pat.pattern, r"\Aa.{3,}baz\Z") |
0 commit comments