~bzr-pqm/bzr/bzr.dev

2052.3.4 by John Arbash Meinel
[merge] bzr.dev
1
# Copyright (C) 2006 Canonical Ltd
2063.4.1 by John Arbash Meinel
bzrlib.lazy_regex.lazy_compile creates a proxy object around re.compile()
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2063.4.1 by John Arbash Meinel
bzrlib.lazy_regex.lazy_compile creates a proxy object around re.compile()
16
17
"""Test that lazy regexes are not compiled right away"""
18
19
import re
20
5326.2.2 by Parth Malwankar
added tests for InvalidPattern errors
21
from bzrlib import errors
2063.4.1 by John Arbash Meinel
bzrlib.lazy_regex.lazy_compile creates a proxy object around re.compile()
22
from bzrlib import (
23
    lazy_regex,
24
    tests,
25
    )
26
27
28
class InstrumentedLazyRegex(lazy_regex.LazyRegex):
29
    """Keep track of actions on the lazy regex"""
30
31
    _actions = []
32
33
    @classmethod
34
    def use_actions(cls, actions):
35
        cls._actions = actions
36
37
    def __getattr__(self, attr):
38
        self._actions.append(('__getattr__', attr))
39
        return super(InstrumentedLazyRegex, self).__getattr__(attr)
40
41
    def _real_re_compile(self, *args, **kwargs):
42
        self._actions.append(('_real_re_compile',
43
                                               args, kwargs))
44
        return super(InstrumentedLazyRegex, self)._real_re_compile(*args, **kwargs)
45
46
47
class TestLazyRegex(tests.TestCase):
48
49
    def test_lazy_compile(self):
50
        """Make sure that LazyRegex objects compile at the right time"""
51
        actions = []
52
        InstrumentedLazyRegex.use_actions(actions)
53
54
        pattern = InstrumentedLazyRegex(args=('foo',))
55
        actions.append(('created regex', 'foo'))
56
        # This match call should compile the regex and go through __getattr__
57
        pattern.match('foo')
58
        # But a further call should not go through __getattr__ because it has
59
        # been bound locally.
60
        pattern.match('foo')
61
62
        self.assertEqual([('created regex', 'foo'),
63
                          ('__getattr__', 'match'),
64
                          ('_real_re_compile', ('foo',), {}),
65
                         ], actions)
66
5326.2.4 by Parth Malwankar
updated InvalidPattern test cases to use assertRaises
67
    def test_bad_pattern(self):
68
        """Ensure lazy regex handles bad patterns cleanly."""
69
        p = lazy_regex.lazy_compile('RE:[')
70
        # As p.match is lazy, we make it into a lambda so its handled
71
        # by assertRaises correctly.
72
        e = self.assertRaises(errors.InvalidPattern, lambda: p.match('foo'))
5339.1.1 by Parth Malwankar
fixes errors.InvalidPattern to work on Python2.5
73
        self.assertEqual(e.msg, '"RE:[" unexpected end of regular expression')
5326.2.4 by Parth Malwankar
updated InvalidPattern test cases to use assertRaises
74
2063.4.1 by John Arbash Meinel
bzrlib.lazy_regex.lazy_compile creates a proxy object around re.compile()
75
76
class TestLazyCompile(tests.TestCase):
77
78
    def test_simple_acts_like_regex(self):
79
        """Test that the returned object has basic regex like functionality"""
80
        pattern = lazy_regex.lazy_compile('foo')
81
        self.assertIsInstance(pattern, lazy_regex.LazyRegex)
82
        self.assertTrue(pattern.match('foo'))
83
        self.assertIs(None, pattern.match('bar'))
84
85
    def test_extra_args(self):
86
        """Test that extra arguments are also properly passed"""
87
        pattern = lazy_regex.lazy_compile('foo', re.I)
88
        self.assertIsInstance(pattern, lazy_regex.LazyRegex)
89
        self.assertTrue(pattern.match('foo'))
90
        self.assertTrue(pattern.match('Foo'))
91
2063.4.2 by John Arbash Meinel
Add install and unistall functions, and tests
92
    def test_findall(self):
93
        pattern = lazy_regex.lazy_compile('fo*')
94
        self.assertEqual(['f', 'fo', 'foo', 'fooo'],
95
                         pattern.findall('f fo foo fooo'))
96
97
    def test_finditer(self):
98
        pattern = lazy_regex.lazy_compile('fo*')
99
        matches = [(m.start(), m.end(), m.group())
100
                   for m in pattern.finditer('foo bar fop')]
101
        self.assertEqual([(0, 3, 'foo'), (8, 10, 'fo')], matches)
102
103
    def test_match(self):
104
        pattern = lazy_regex.lazy_compile('fo*')
105
        self.assertIs(None, pattern.match('baz foo'))
106
        self.assertEqual('fooo', pattern.match('fooo').group())
107
108
    def test_search(self):
109
        pattern = lazy_regex.lazy_compile('fo*')
110
        self.assertEqual('foo', pattern.search('baz foo').group())
111
        self.assertEqual('fooo', pattern.search('fooo').group())
112
113
    def test_split(self):
114
        pattern = lazy_regex.lazy_compile('[,;]*')
115
        self.assertEqual(['x', 'y', 'z'], pattern.split('x,y;z'))
116
117
118
class TestInstallLazyCompile(tests.TestCase):
119
120
    def setUp(self):
121
        super(TestInstallLazyCompile, self).setUp()
122
        self.addCleanup(lazy_regex.reset_compile)
123
124
    def test_install(self):
125
        lazy_regex.install_lazy_compile()
126
        pattern = re.compile('foo')
127
        self.assertIsInstance(pattern, lazy_regex.LazyRegex)
128
129
    def test_reset(self):
130
        lazy_regex.install_lazy_compile()
131
        lazy_regex.reset_compile()
132
        pattern = re.compile('foo')
133
        self.failIf(isinstance(pattern, lazy_regex.LazyRegex),
134
                    'lazy_regex.reset_compile() did not restore the original'
135
                    ' compile() function %s' % (type(pattern),))
136
        # but the returned object should still support regex operations
137
        m = pattern.match('foo')
138
        self.assertEqual('foo', m.group())