2021-03-12 07:56:11 +00:00
|
|
|
import re
|
2013-07-01 12:22:27 +00:00
|
|
|
import unittest
|
|
|
|
|
2021-03-12 07:56:11 +00:00
|
|
|
from django.test import SimpleTestCase
|
2012-01-03 22:49:13 +00:00
|
|
|
from django.utils import regex_helper
|
|
|
|
|
|
|
|
|
|
|
|
class NormalizeTests(unittest.TestCase):
|
|
|
|
def test_empty(self):
|
|
|
|
pattern = r""
|
2022-02-03 19:24:19 +00:00
|
|
|
expected = [("", [])]
|
2012-01-03 22:49:13 +00:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_escape(self):
|
|
|
|
pattern = r"\\\^\$\.\|\?\*\+\(\)\["
|
2022-02-03 19:24:19 +00:00
|
|
|
expected = [("\\^$.|?*+()[", [])]
|
2012-01-03 22:49:13 +00:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_group_positional(self):
|
|
|
|
pattern = r"(.*)-(.+)"
|
2022-02-03 19:24:19 +00:00
|
|
|
expected = [("%(_0)s-%(_1)s", ["_0", "_1"])]
|
2012-01-03 22:49:13 +00:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_group_noncapturing(self):
|
|
|
|
pattern = r"(?:non-capturing)"
|
2022-02-03 19:24:19 +00:00
|
|
|
expected = [("non-capturing", [])]
|
2012-01-03 22:49:13 +00:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_group_named(self):
|
|
|
|
pattern = r"(?P<first_group_name>.*)-(?P<second_group_name>.*)"
|
2022-02-03 19:24:19 +00:00
|
|
|
expected = [
|
|
|
|
(
|
|
|
|
"%(first_group_name)s-%(second_group_name)s",
|
|
|
|
["first_group_name", "second_group_name"],
|
|
|
|
)
|
|
|
|
]
|
2012-01-03 22:49:13 +00:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_group_backreference(self):
|
|
|
|
pattern = r"(?P<first_group_name>.*)-(?P=first_group_name)"
|
2022-02-03 19:24:19 +00:00
|
|
|
expected = [("%(first_group_name)s-%(first_group_name)s", ["first_group_name"])]
|
2012-01-03 22:49:13 +00:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
2021-03-12 07:56:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LazyReCompileTests(SimpleTestCase):
|
|
|
|
def test_flags_with_pre_compiled_regex(self):
|
2022-02-03 19:24:19 +00:00
|
|
|
test_pattern = re.compile("test")
|
2021-03-12 07:56:11 +00:00
|
|
|
lazy_test_pattern = regex_helper._lazy_re_compile(test_pattern, re.I)
|
2022-02-03 19:24:19 +00:00
|
|
|
msg = "flags must be empty if regex is passed pre-compiled"
|
2021-03-12 07:56:11 +00:00
|
|
|
with self.assertRaisesMessage(AssertionError, msg):
|
2022-02-03 19:24:19 +00:00
|
|
|
lazy_test_pattern.match("TEST")
|