test_glob_to_regex.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. from tests.unittest import TestCase
  16. class GlobToRegexTestCase(TestCase):
  17. def test_literal_match(self):
  18. """patterns without wildcards should match"""
  19. pat = glob_to_regex("foobaz")
  20. self.assertTrue(
  21. pat.match("FoobaZ"), "patterns should match and be case-insensitive"
  22. )
  23. self.assertFalse(
  24. pat.match("x foobaz"), "pattern should not match at word boundaries"
  25. )
  26. def test_wildcard_match(self):
  27. pat = glob_to_regex("f?o*baz")
  28. self.assertTrue(
  29. pat.match("FoobarbaZ"),
  30. "* should match string and pattern should be case-insensitive",
  31. )
  32. self.assertTrue(pat.match("foobaz"), "* should match 0 characters")
  33. self.assertFalse(pat.match("fooxaz"), "the character after * must match")
  34. self.assertFalse(pat.match("fobbaz"), "? should not match 0 characters")
  35. self.assertFalse(pat.match("fiiobaz"), "? should not match 2 characters")
  36. def test_multi_wildcard(self):
  37. """patterns with multiple wildcards in a row should match"""
  38. pat = glob_to_regex("**baz")
  39. self.assertTrue(pat.match("agsgsbaz"), "** should match any string")
  40. self.assertTrue(pat.match("baz"), "** should match the empty string")
  41. self.assertEqual(pat.pattern, r"\A.{0,}baz\Z")
  42. pat = glob_to_regex("*?baz")
  43. self.assertTrue(pat.match("agsgsbaz"), "*? should match any string")
  44. self.assertTrue(pat.match("abaz"), "*? should match a single char")
  45. self.assertFalse(pat.match("baz"), "*? should not match the empty string")
  46. self.assertEqual(pat.pattern, r"\A.{1,}baz\Z")
  47. pat = glob_to_regex("a?*?*?baz")
  48. self.assertTrue(pat.match("a g baz"), "?*?*? should match 3 chars")
  49. self.assertFalse(pat.match("a..baz"), "?*?*? should not match 2 chars")
  50. self.assertTrue(pat.match("a.gg.baz"), "?*?*? should match 4 chars")
  51. self.assertEqual(pat.pattern, r"\Aa.{3,}baz\Z")