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