/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5452.4.3 by John Arbash Meinel
Merge bzr.dev to resolve bzr-2.3.txt (aka NEWS)
1
# Copyright (C) 2006, 2008, 2009, 2010 Canonical Ltd
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
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
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
16
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
17
"""Tests for the Registry classes"""
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
18
19
import os
20
import sys
21
22
from bzrlib import (
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
23
    branch,
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
24
    errors,
4691.1.1 by Vincent Ladeuil
Respect items() protocol for registry objects.
25
    osutils,
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
26
    registry,
4691.1.1 by Vincent Ladeuil
Respect items() protocol for registry objects.
27
    tests,
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
28
    )
4691.1.1 by Vincent Ladeuil
Respect items() protocol for registry objects.
29
30
31
class TestRegistry(tests.TestCase):
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
32
33
    def register_stuff(self, a_registry):
34
        a_registry.register('one', 1)
35
        a_registry.register('two', 2)
36
        a_registry.register('four', 4)
37
        a_registry.register('five', 5)
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
38
39
    def test_registry(self):
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
40
        a_registry = registry.Registry()
41
        self.register_stuff(a_registry)
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
42
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
43
        self.failUnless(a_registry.default_key is None)
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
44
3376.2.11 by Martin Pool
Compare to None using is/is not not ==
45
        # test get() (self.default_key is None)
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
46
        self.assertRaises(KeyError, a_registry.get)
47
        self.assertRaises(KeyError, a_registry.get, None)
48
        self.assertEqual(2, a_registry.get('two'))
49
        self.assertRaises(KeyError, a_registry.get, 'three')
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
50
51
        # test _set_default_key
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
52
        a_registry.default_key = 'five'
53
        self.failUnless(a_registry.default_key == 'five')
54
        self.assertEqual(5, a_registry.get())
55
        self.assertEqual(5, a_registry.get(None))
56
        # If they ask for a specific entry, they should get KeyError
57
        # not the default value. They can always pass None if they prefer
58
        self.assertRaises(KeyError, a_registry.get, 'six')
59
        self.assertRaises(KeyError, a_registry._set_default_key, 'six')
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
60
61
        # test keys()
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
62
        self.assertEqual(['five', 'four', 'one', 'two'], a_registry.keys())
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
63
1911.4.11 by John Arbash Meinel
Remove extra dict-like members, simplfying the api
64
    def test_registry_funcs(self):
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
65
        a_registry = registry.Registry()
66
        self.register_stuff(a_registry)
67
68
        self.failUnless('one' in a_registry)
1911.4.11 by John Arbash Meinel
Remove extra dict-like members, simplfying the api
69
        a_registry.remove('one')
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
70
        self.failIf('one' in a_registry)
71
        self.assertRaises(KeyError, a_registry.get, 'one')
72
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
73
        a_registry.register('one', 'one')
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
74
75
        self.assertEqual(['five', 'four', 'one', 'two'],
1911.4.11 by John Arbash Meinel
Remove extra dict-like members, simplfying the api
76
                         sorted(a_registry.keys()))
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
77
        self.assertEqual([('five', 5), ('four', 4),
78
                          ('one', 'one'), ('two', 2)],
79
                         sorted(a_registry.iteritems()))
80
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
81
    def test_register_override(self):
82
        a_registry = registry.Registry()
83
        a_registry.register('one', 'one')
84
        self.assertRaises(KeyError, a_registry.register, 'one', 'two')
85
        self.assertRaises(KeyError, a_registry.register, 'one', 'two',
86
                                    override_existing=False)
87
88
        a_registry.register('one', 'two', override_existing=True)
89
        self.assertEqual('two', a_registry.get('one'))
90
91
        self.assertRaises(KeyError, a_registry.register_lazy,
92
                          'one', 'three', 'four')
93
94
        a_registry.register_lazy('one', 'module', 'member',
95
                                 override_existing=True)
96
97
    def test_registry_help(self):
98
        a_registry = registry.Registry()
99
        a_registry.register('one', 1, help='help text for one')
100
        # We should not have to import the module to return the help
101
        # information
102
        a_registry.register_lazy('two', 'nonexistent_module', 'member',
103
                                 help='help text for two')
104
105
        # We should be able to handle a callable to get information
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
106
        help_calls = []
1911.4.9 by John Arbash Meinel
A help callable should take the registry as the first parameter
107
        def generic_help(reg, key):
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
108
            help_calls.append(key)
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
109
            return 'generic help for %s' % (key,)
110
        a_registry.register('three', 3, help=generic_help)
111
        a_registry.register_lazy('four', 'nonexistent_module', 'member2',
112
                                 help=generic_help)
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
113
        a_registry.register('five', 5)
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
114
1911.4.10 by John Arbash Meinel
A test which uses the callback to return information from the object.
115
        def help_from_object(reg, key):
116
            obj = reg.get(key)
117
            return obj.help()
118
119
        class SimpleObj(object):
120
            def help(self):
121
                return 'this is my help'
122
        a_registry.register('six', SimpleObj(), help=help_from_object)
123
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
124
        self.assertEqual('help text for one', a_registry.get_help('one'))
125
        self.assertEqual('help text for two', a_registry.get_help('two'))
126
        self.assertEqual('generic help for three',
127
                         a_registry.get_help('three'))
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
128
        self.assertEqual(['three'], help_calls)
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
129
        self.assertEqual('generic help for four',
130
                         a_registry.get_help('four'))
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
131
        self.assertEqual(['three', 'four'], help_calls)
132
        self.assertEqual(None, a_registry.get_help('five'))
1911.4.10 by John Arbash Meinel
A test which uses the callback to return information from the object.
133
        self.assertEqual('this is my help', a_registry.get_help('six'))
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
134
135
        self.assertRaises(KeyError, a_registry.get_help, None)
1911.4.10 by John Arbash Meinel
A test which uses the callback to return information from the object.
136
        self.assertRaises(KeyError, a_registry.get_help, 'seven')
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
137
138
        a_registry.default_key = 'one'
139
        self.assertEqual('help text for one', a_registry.get_help(None))
1911.4.10 by John Arbash Meinel
A test which uses the callback to return information from the object.
140
        self.assertRaises(KeyError, a_registry.get_help, 'seven')
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
141
142
        self.assertEqual([('five', None),
143
                          ('four', 'generic help for four'),
144
                          ('one', 'help text for one'),
1911.4.10 by John Arbash Meinel
A test which uses the callback to return information from the object.
145
                          ('six', 'this is my help'),
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
146
                          ('three', 'generic help for three'),
147
                          ('two', 'help text for two'),
1911.4.11 by John Arbash Meinel
Remove extra dict-like members, simplfying the api
148
                         ], sorted((key, a_registry.get_help(key))
149
                                    for key in a_registry.keys()))
150
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
151
        # We don't know what order it was called in, but we should get
152
        # 2 more calls to three and four
153
        self.assertEqual(['four', 'four', 'three', 'three'],
154
                         sorted(help_calls))
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
155
156
    def test_registry_info(self):
157
        a_registry = registry.Registry()
158
        a_registry.register('one', 1, info='string info')
159
        # We should not have to import the module to return the info
160
        a_registry.register_lazy('two', 'nonexistent_module', 'member',
161
                                 info=2)
162
163
        # We should be able to handle a callable to get information
164
        a_registry.register('three', 3, info=['a', 'list'])
165
        obj = object()
166
        a_registry.register_lazy('four', 'nonexistent_module', 'member2',
167
                                 info=obj)
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
168
        a_registry.register('five', 5)
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
169
170
        self.assertEqual('string info', a_registry.get_info('one'))
171
        self.assertEqual(2, a_registry.get_info('two'))
172
        self.assertEqual(['a', 'list'], a_registry.get_info('three'))
173
        self.assertIs(obj, a_registry.get_info('four'))
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
174
        self.assertIs(None, a_registry.get_info('five'))
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
175
176
        self.assertRaises(KeyError, a_registry.get_info, None)
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
177
        self.assertRaises(KeyError, a_registry.get_info, 'six')
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
178
179
        a_registry.default_key = 'one'
180
        self.assertEqual('string info', a_registry.get_info(None))
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
181
        self.assertRaises(KeyError, a_registry.get_info, 'six')
1911.4.7 by John Arbash Meinel
Add help and info parameters, and tests for them
182
1911.4.8 by John Arbash Meinel
Add Registry.iterhelp and Registry.iterinfo
183
        self.assertEqual([('five', None),
184
                          ('four', obj),
185
                          ('one', 'string info'),
186
                          ('three', ['a', 'list']),
187
                          ('two', 2),
1911.4.11 by John Arbash Meinel
Remove extra dict-like members, simplfying the api
188
                         ], sorted((key, a_registry.get_info(key))
189
                                    for key in a_registry.keys()))
190
3251.3.2 by Aaron Bentley
Add testing of Registry.get_prefix
191
    def test_get_prefix(self):
192
        my_registry = registry.Registry()
193
        http_object = object()
194
        sftp_object = object()
195
        my_registry.register('http:', http_object)
196
        my_registry.register('sftp:', sftp_object)
197
        found_object, suffix = my_registry.get_prefix('http://foo/bar')
198
        self.assertEqual('//foo/bar', suffix)
199
        self.assertIs(http_object, found_object)
200
        self.assertIsNot(sftp_object, found_object)
201
        found_object, suffix = my_registry.get_prefix('sftp://baz/qux')
202
        self.assertEqual('//baz/qux', suffix)
203
        self.assertIs(sftp_object, found_object)
204
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
205
4691.1.1 by Vincent Ladeuil
Respect items() protocol for registry objects.
206
class TestRegistryIter(tests.TestCase):
207
    """Test registry iteration behaviors.
208
209
    There are dark corner cases here when the registered objects trigger
210
    addition in the iterated registry.
211
    """
212
213
    def setUp(self):
214
        super(TestRegistryIter, self).setUp()
215
216
        # We create a registry with "official" objects and "hidden"
217
        # objects. The later represent the side effects that led to bug #277048
218
        # and #430510
219
        self.registry =  registry.Registry()
220
221
        def register_more():
222
            self.registry.register('hidden', None)
223
224
        self.registry.register('passive', None)
225
        self.registry.register('active', register_more)
226
        self.registry.register('passive-too', None)
227
228
        class InvasiveGetter(registry._ObjectGetter):
229
230
            def get_obj(inner_self):
231
                # Surprise ! Getting a registered object (think lazy loaded
232
                # module) register yet another object !
233
                self.registry.register('more hidden', None)
234
                return inner_self._obj
235
236
        self.registry.register('hacky', None)
237
        # We peek under the covers because the alternative is to use lazy
238
        # registration and create a module that can reference our test registry
239
        # it's too much work for such a corner case -- vila 090916
240
        self.registry._dict['hacky'] = InvasiveGetter(None)
241
242
    def _iter_them(self, iter_func_name):
243
        iter_func = getattr(self.registry, iter_func_name, None)
244
        self.assertIsNot(None, iter_func)
245
        count = 0
246
        for name, func in iter_func():
247
            count += 1
248
            self.assertFalse(name in ('hidden', 'more hidden'))
249
            if func is not None:
250
                # Using an object register another one as a side effect
251
                func()
252
        self.assertEqual(4, count)
253
254
    def test_iteritems(self):
255
        # the dict is modified during the iteration
256
        self.assertRaises(RuntimeError, self._iter_them, 'iteritems')
257
258
    def test_items(self):
259
        # we should be able to iterate even if one item modify the dict
260
        self._iter_them('items')
261
262
263
class TestRegistryWithDirs(tests.TestCaseInTempDir):
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
264
    """Registry tests that require temporary dirs"""
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
265
266
    def create_plugin_file(self, contents):
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
267
        """Create a file to be used as a plugin.
268
269
        This is created in a temporary directory, so that we
270
        are sure that it doesn't start in the plugin path.
271
        """
272
        os.mkdir('tmp')
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
273
        plugin_name = 'bzr_plugin_a_%s' % (osutils.rand_chars(4),)
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
274
        open('tmp/'+plugin_name+'.py', 'wb').write(contents)
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
275
        return plugin_name
276
277
    def create_simple_plugin(self):
278
        return self.create_plugin_file(
279
            'object1 = "foo"\n'
280
            '\n\n'
281
            'def function(a,b,c):\n'
282
            '    return a,b,c\n'
283
            '\n\n'
284
            'class MyClass(object):\n'
285
            '    def __init__(self, a):\n'
286
            '      self.a = a\n'
287
            '\n\n'
288
        )
289
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
290
    def test_lazy_import_registry_foo(self):
291
        a_registry = registry.Registry()
292
        a_registry.register_lazy('foo', 'bzrlib.branch', 'Branch')
293
        a_registry.register_lazy('bar', 'bzrlib.branch', 'Branch.hooks')
294
        self.assertEqual(branch.Branch, a_registry.get('foo'))
295
        self.assertEqual(branch.Branch.hooks, a_registry.get('bar'))
296
1912.5.2 by Adeodato Simó
Morph John's LazyFactory into a generalized Registry class, and
297
    def test_lazy_import_registry(self):
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
298
        plugin_name = self.create_simple_plugin()
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
299
        a_registry = registry.Registry()
300
        a_registry.register_lazy('obj', plugin_name, 'object1')
301
        a_registry.register_lazy('function', plugin_name, 'function')
302
        a_registry.register_lazy('klass', plugin_name, 'MyClass')
303
        a_registry.register_lazy('module', plugin_name, None)
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
304
305
        self.assertEqual(['function', 'klass', 'module', 'obj'],
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
306
                         sorted(a_registry.keys()))
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
307
        # The plugin should not be loaded until we grab the first object
308
        self.failIf(plugin_name in sys.modules)
309
310
        # By default the plugin won't be in the search path
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
311
        self.assertRaises(ImportError, a_registry.get, 'obj')
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
312
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
313
        plugin_path = os.getcwd() + '/tmp'
314
        sys.path.append(plugin_path)
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
315
        try:
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
316
            obj = a_registry.get('obj')
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
317
            self.assertEqual('foo', obj)
318
            self.failUnless(plugin_name in sys.modules)
319
320
            # Now grab another object
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
321
            func = a_registry.get('function')
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
322
            self.assertEqual(plugin_name, func.__module__)
323
            self.assertEqual('function', func.__name__)
324
            self.assertEqual((1, [], '3'), func(1, [], '3'))
325
326
            # And finally a class
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
327
            klass = a_registry.get('klass')
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
328
            self.assertEqual(plugin_name, klass.__module__)
329
            self.assertEqual('MyClass', klass.__name__)
330
331
            inst = klass(1)
332
            self.assertIsInstance(inst, klass)
333
            self.assertEqual(1, inst.a)
334
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
335
            module = a_registry.get('module')
1911.4.1 by John Arbash Meinel
Creating a factory that can load modules on demand.
336
            self.assertIs(obj, module.object1)
337
            self.assertIs(func, module.function)
338
            self.assertIs(klass, module.MyClass)
339
        finally:
1911.4.5 by John Arbash Meinel
Make a Registry look more like a dict, and allow anyone to register stuff lazily.
340
            sys.path.remove(plugin_path)
341