2021-03-12 08:56:11 +01:00
|
|
|
import re
|
2013-07-01 14:22:27 +02:00
|
|
|
import unittest
|
|
|
|
|
2021-03-12 08:56:11 +01:00
|
|
|
from django.test import SimpleTestCase
|
2012-01-03 23:49:13 +01:00
|
|
|
from django.utils import regex_helper
|
|
|
|
|
|
|
|
|
|
|
|
class NormalizeTests(unittest.TestCase):
|
|
|
|
def test_empty(self):
|
|
|
|
pattern = r""
|
2012-06-07 18:08:47 +02:00
|
|
|
expected = [('', [])]
|
2012-01-03 23:49:13 +01:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_escape(self):
|
|
|
|
pattern = r"\\\^\$\.\|\?\*\+\(\)\["
|
2012-06-07 18:08:47 +02:00
|
|
|
expected = [('\\^$.|?*+()[', [])]
|
2012-01-03 23:49:13 +01:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_group_positional(self):
|
|
|
|
pattern = r"(.*)-(.+)"
|
2012-06-07 18:08:47 +02:00
|
|
|
expected = [('%(_0)s-%(_1)s', ['_0', '_1'])]
|
2012-01-03 23:49:13 +01:00
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
|
|
|
|
|
|
|
def test_group_noncapturing(self):
|
|
|
|
pattern = r"(?:non-capturing)"
|
2012-06-07 18:08:47 +02:00
|
|
|
expected = [('non-capturing', [])]
|
2012-01-03 23:49:13 +01: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-07 18:08:47 +02:00
|
|
|
expected = [('%(first_group_name)s-%(second_group_name)s',
|
2012-01-03 23:49:13 +01: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-07 18:08:47 +02:00
|
|
|
expected = [('%(first_group_name)s-%(first_group_name)s',
|
2012-01-03 23:49:13 +01:00
|
|
|
['first_group_name'])]
|
|
|
|
result = regex_helper.normalize(pattern)
|
|
|
|
self.assertEqual(result, expected)
|
2021-03-12 08:56:11 +01: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')
|