~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_plugins.py

Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
# affects the global state of the process.  See bzrlib/plugins.py for more
21
21
# comments.
22
22
 
23
 
from cStringIO import StringIO
24
23
import logging
25
24
import os
 
25
from StringIO import StringIO
26
26
import sys
 
27
import zipfile
27
28
 
28
 
import bzrlib
29
 
from bzrlib import (
30
 
    errors,
31
 
    osutils,
32
 
    plugin,
33
 
    plugins,
34
 
    tests,
35
 
    trace,
 
29
from bzrlib import plugin, tests
 
30
import bzrlib.plugin
 
31
import bzrlib.plugins
 
32
import bzrlib.commands
 
33
import bzrlib.help
 
34
from bzrlib.tests import (
 
35
    TestCase,
 
36
    TestCaseInTempDir,
 
37
    TestUtil,
36
38
    )
37
 
 
 
39
from bzrlib.osutils import pathjoin, abspath, normpath
 
40
 
 
41
 
 
42
PLUGIN_TEXT = """\
 
43
import bzrlib.commands
 
44
class cmd_myplug(bzrlib.commands.Command):
 
45
    '''Just a simple test plugin.'''
 
46
    aliases = ['mplg']
 
47
    def run(self):
 
48
        print 'Hello from my plugin'
 
49
"""
38
50
 
39
51
# TODO: Write a test for plugin decoration of commands.
40
52
 
41
 
class BaseTestPlugins(tests.TestCaseInTempDir):
42
 
 
43
 
    def create_plugin(self, name, source=None, dir='.', file_name=None):
44
 
        if source is None:
45
 
            source = '''\
46
 
"""This is the doc for %s"""
47
 
''' % (name)
48
 
        if file_name is None:
49
 
            file_name = name + '.py'
50
 
        # 'source' must not fail to load
51
 
        path = osutils.pathjoin(dir, file_name)
52
 
        f = open(path, 'w')
53
 
        self.addCleanup(os.unlink, path)
54
 
        try:
55
 
            f.write(source + '\n')
56
 
        finally:
57
 
            f.close()
58
 
 
59
 
    def create_plugin_package(self, name, dir=None, source=None):
60
 
        if dir is None:
61
 
            dir = name
62
 
        if source is None:
63
 
            source = '''\
64
 
"""This is the doc for %s"""
65
 
dir_source = '%s'
66
 
''' % (name, dir)
67
 
        os.makedirs(dir)
68
 
        def cleanup():
69
 
            # Workaround lazy import random? madness
70
 
            osutils.rmtree(dir)
71
 
        self.addCleanup(cleanup)
72
 
        self.create_plugin(name, source, dir,
73
 
                           file_name='__init__.py')
74
 
 
75
 
    def _unregister_plugin(self, name):
76
 
        """Remove the plugin from sys.modules and the bzrlib namespace."""
77
 
        py_name = 'bzrlib.plugins.%s' % name
78
 
        if py_name in sys.modules:
79
 
            del sys.modules[py_name]
80
 
        if getattr(bzrlib.plugins, name, None) is not None:
81
 
            delattr(bzrlib.plugins, name)
82
 
 
83
 
    def _unregister_plugin_submodule(self, plugin_name, submodule_name):
84
 
        """Remove the submodule from sys.modules and the bzrlib namespace."""
85
 
        py_name = 'bzrlib.plugins.%s.%s' % (plugin_name, submodule_name)
86
 
        if py_name in sys.modules:
87
 
            del sys.modules[py_name]
88
 
        plugin = getattr(bzrlib.plugins, plugin_name, None)
89
 
        if plugin is not None:
90
 
            if getattr(plugin, submodule_name, None) is not None:
91
 
                delattr(plugin, submodule_name)
92
 
 
93
 
    def assertPluginUnknown(self, name):
94
 
        self.assertFalse(getattr(bzrlib.plugins, name, None) is not None)
95
 
        self.assertFalse('bzrlib.plugins.%s' % name in sys.modules)
96
 
 
97
 
    def assertPluginKnown(self, name):
98
 
        self.assertTrue(getattr(bzrlib.plugins, name, None) is not None)
99
 
        self.assertTrue('bzrlib.plugins.%s' % name in sys.modules)
100
 
 
101
 
 
102
 
class TestLoadingPlugins(BaseTestPlugins):
 
53
class TestLoadingPlugins(TestCaseInTempDir):
103
54
 
104
55
    activeattributes = {}
105
56
 
109
60
        # file name we can use which is also a valid attribute for accessing in
110
61
        # activeattributes. - we cannot give import parameters.
111
62
        tempattribute = "0"
112
 
        self.assertFalse(tempattribute in self.activeattributes)
 
63
        self.failIf(tempattribute in self.activeattributes)
113
64
        # set a place for the plugins to record their loading, and at the same
114
65
        # time validate that the location the plugins should record to is
115
66
        # valid and correct.
116
 
        self.__class__.activeattributes [tempattribute] = []
117
 
        self.assertTrue(tempattribute in self.activeattributes)
 
67
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
68
            [tempattribute] = []
 
69
        self.failUnless(tempattribute in self.activeattributes)
118
70
        # create two plugin directories
119
71
        os.mkdir('first')
120
72
        os.mkdir('second')
143
95
        finally:
144
96
            # remove the plugin 'plugin'
145
97
            del self.activeattributes[tempattribute]
146
 
            self._unregister_plugin('plugin')
147
 
        self.assertPluginUnknown('plugin')
 
98
            if 'bzrlib.plugins.plugin' in sys.modules:
 
99
                del sys.modules['bzrlib.plugins.plugin']
 
100
            if getattr(bzrlib.plugins, 'plugin', None):
 
101
                del bzrlib.plugins.plugin
 
102
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
148
103
 
149
104
    def test_plugins_from_different_dirs_can_demand_load(self):
150
 
        self.assertFalse('bzrlib.plugins.pluginone' in sys.modules)
151
 
        self.assertFalse('bzrlib.plugins.plugintwo' in sys.modules)
152
105
        # This test tests that having two plugins in different
153
106
        # directories with different names allows them both to be loaded, when
154
107
        # we do a direct import statement.
155
108
        # Determine a file name we can use which is also a valid attribute
156
109
        # for accessing in activeattributes. - we cannot give import parameters.
157
110
        tempattribute = "different-dirs"
158
 
        self.assertFalse(tempattribute in self.activeattributes)
 
111
        self.failIf(tempattribute in self.activeattributes)
159
112
        # set a place for the plugins to record their loading, and at the same
160
113
        # time validate that the location the plugins should record to is
161
114
        # valid and correct.
162
115
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
163
116
            [tempattribute] = []
164
 
        self.assertTrue(tempattribute in self.activeattributes)
 
117
        self.failUnless(tempattribute in self.activeattributes)
165
118
        # create two plugin directories
166
119
        os.mkdir('first')
167
120
        os.mkdir('second')
186
139
 
187
140
        oldpath = bzrlib.plugins.__path__
188
141
        try:
189
 
            self.assertFalse('bzrlib.plugins.pluginone' in sys.modules)
190
 
            self.assertFalse('bzrlib.plugins.plugintwo' in sys.modules)
191
142
            bzrlib.plugins.__path__ = ['first', 'second']
192
143
            exec "import bzrlib.plugins.pluginone"
193
144
            self.assertEqual(['first'], self.activeattributes[tempattribute])
197
148
        finally:
198
149
            # remove the plugin 'plugin'
199
150
            del self.activeattributes[tempattribute]
200
 
            self._unregister_plugin('pluginone')
201
 
            self._unregister_plugin('plugintwo')
202
 
        self.assertPluginUnknown('pluginone')
203
 
        self.assertPluginUnknown('plugintwo')
 
151
            if getattr(bzrlib.plugins, 'pluginone', None):
 
152
                del bzrlib.plugins.pluginone
 
153
            if getattr(bzrlib.plugins, 'plugintwo', None):
 
154
                del bzrlib.plugins.plugintwo
 
155
        self.failIf(getattr(bzrlib.plugins, 'pluginone', None))
 
156
        self.failIf(getattr(bzrlib.plugins, 'plugintwo', None))
204
157
 
205
158
    def test_plugins_can_load_from_directory_with_trailing_slash(self):
206
159
        # This test tests that a plugin can load from a directory when the
207
160
        # directory in the path has a trailing slash.
208
161
        # check the plugin is not loaded already
209
 
        self.assertPluginUnknown('ts_plugin')
 
162
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
210
163
        tempattribute = "trailing-slash"
211
 
        self.assertFalse(tempattribute in self.activeattributes)
 
164
        self.failIf(tempattribute in self.activeattributes)
212
165
        # set a place for the plugin to record its loading, and at the same
213
166
        # time validate that the location the plugin should record to is
214
167
        # valid and correct.
215
168
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
216
169
            [tempattribute] = []
217
 
        self.assertTrue(tempattribute in self.activeattributes)
 
170
        self.failUnless(tempattribute in self.activeattributes)
218
171
        # create a directory for the plugin
219
172
        os.mkdir('plugin_test')
220
173
        # write a plugin that will record when its loaded in the
233
186
            bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
234
187
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
235
188
        finally:
 
189
            # remove the plugin 'plugin'
236
190
            del self.activeattributes[tempattribute]
237
 
            self._unregister_plugin('ts_plugin')
238
 
        self.assertPluginUnknown('ts_plugin')
 
191
            if getattr(bzrlib.plugins, 'ts_plugin', None):
 
192
                del bzrlib.plugins.ts_plugin
 
193
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
239
194
 
240
195
    def load_and_capture(self, name):
241
196
        """Load plugins from '.' capturing the output.
267
222
            stream.close()
268
223
 
269
224
    def test_plugin_with_bad_api_version_reports(self):
270
 
        """Try loading a plugin that requests an unsupported api.
271
 
        
272
 
        Observe that it records the problem but doesn't complain on stderr.
273
 
 
274
 
        See https://bugs.launchpad.net/bzr/+bug/704195
275
 
        """
276
 
        self.overrideAttr(plugin, 'plugin_warnings', {})
 
225
        # This plugin asks for bzrlib api version 1.0.0, which is not supported
 
226
        # anymore.
277
227
        name = 'wants100.py'
278
228
        f = file(name, 'w')
279
229
        try:
281
231
                "bzrlib.api.require_any_api(bzrlib, [(1, 0, 0)])\n")
282
232
        finally:
283
233
            f.close()
 
234
 
284
235
        log = self.load_and_capture(name)
285
 
        self.assertNotContainsRe(log,
286
 
            r"It requested API version")
287
 
        self.assertEquals(
288
 
            ['wants100'],
289
 
            plugin.plugin_warnings.keys())
290
 
        self.assertContainsRe(
291
 
            plugin.plugin_warnings['wants100'][0],
 
236
        self.assertContainsRe(log,
292
237
            r"It requested API version")
293
238
 
294
239
    def test_plugin_with_bad_name_does_not_load(self):
302
247
            "it to 'bad_plugin_name_'\.")
303
248
 
304
249
 
305
 
class TestPlugins(BaseTestPlugins):
 
250
class TestPlugins(TestCaseInTempDir):
306
251
 
307
252
    def setup_plugin(self, source=""):
308
253
        # This test tests a new plugin appears in bzrlib.plugin.plugins().
309
254
        # check the plugin is not loaded already
310
 
        self.assertPluginUnknown('plugin')
 
255
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
311
256
        # write a plugin that _cannot_ fail to load.
312
257
        file('plugin.py', 'w').write(source + '\n')
313
258
        self.addCleanup(self.teardown_plugin)
314
 
        plugin.load_from_path(['.'])
 
259
        bzrlib.plugin.load_from_path(['.'])
315
260
 
316
261
    def teardown_plugin(self):
317
 
        self._unregister_plugin('plugin')
318
 
        self.assertPluginUnknown('plugin')
 
262
        # remove the plugin 'plugin'
 
263
        if 'bzrlib.plugins.plugin' in sys.modules:
 
264
            del sys.modules['bzrlib.plugins.plugin']
 
265
        if getattr(bzrlib.plugins, 'plugin', None):
 
266
            del bzrlib.plugins.plugin
 
267
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
319
268
 
320
269
    def test_plugin_appears_in_plugins(self):
321
270
        self.setup_plugin()
322
 
        self.assertPluginKnown('plugin')
323
 
        p = plugin.plugins()['plugin']
324
 
        self.assertIsInstance(p, bzrlib.plugin.PlugIn)
325
 
        self.assertEqual(p.module, plugins.plugin)
 
271
        self.failUnless('plugin' in bzrlib.plugin.plugins())
 
272
        self.failUnless(getattr(bzrlib.plugins, 'plugin', None))
 
273
        plugins = bzrlib.plugin.plugins()
 
274
        plugin = plugins['plugin']
 
275
        self.assertIsInstance(plugin, bzrlib.plugin.PlugIn)
 
276
        self.assertEqual(bzrlib.plugins.plugin, plugin.module)
326
277
 
327
278
    def test_trivial_plugin_get_path(self):
328
279
        self.setup_plugin()
329
 
        p = plugin.plugins()['plugin']
 
280
        plugins = bzrlib.plugin.plugins()
 
281
        plugin = plugins['plugin']
330
282
        plugin_path = self.test_dir + '/plugin.py'
331
 
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
 
283
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
332
284
 
333
285
    def test_plugin_get_path_py_not_pyc(self):
334
 
        # first import creates plugin.pyc
335
 
        self.setup_plugin()
 
286
        self.setup_plugin()         # after first import there will be plugin.pyc
336
287
        self.teardown_plugin()
337
 
        plugin.load_from_path(['.']) # import plugin.pyc
338
 
        p = plugin.plugins()['plugin']
 
288
        bzrlib.plugin.load_from_path(['.']) # import plugin.pyc
 
289
        plugins = bzrlib.plugin.plugins()
 
290
        plugin = plugins['plugin']
339
291
        plugin_path = self.test_dir + '/plugin.py'
340
 
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
 
292
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
341
293
 
342
294
    def test_plugin_get_path_pyc_only(self):
343
 
        # first import creates plugin.pyc (or plugin.pyo depending on __debug__)
344
 
        self.setup_plugin()
 
295
        self.setup_plugin()         # after first import there will be plugin.pyc
345
296
        self.teardown_plugin()
346
297
        os.unlink(self.test_dir + '/plugin.py')
347
 
        plugin.load_from_path(['.']) # import plugin.pyc (or .pyo)
348
 
        p = plugin.plugins()['plugin']
 
298
        bzrlib.plugin.load_from_path(['.']) # import plugin.pyc
 
299
        plugins = bzrlib.plugin.plugins()
 
300
        plugin = plugins['plugin']
349
301
        if __debug__:
350
302
            plugin_path = self.test_dir + '/plugin.pyc'
351
303
        else:
352
304
            plugin_path = self.test_dir + '/plugin.pyo'
353
 
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
 
305
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
354
306
 
355
307
    def test_no_test_suite_gives_None_for_test_suite(self):
356
308
        self.setup_plugin()
357
 
        p = plugin.plugins()['plugin']
358
 
        self.assertEqual(None, p.test_suite())
 
309
        plugin = bzrlib.plugin.plugins()['plugin']
 
310
        self.assertEqual(None, plugin.test_suite())
359
311
 
360
312
    def test_test_suite_gives_test_suite_result(self):
361
313
        source = """def test_suite(): return 'foo'"""
362
314
        self.setup_plugin(source)
363
 
        p = plugin.plugins()['plugin']
364
 
        self.assertEqual('foo', p.test_suite())
 
315
        plugin = bzrlib.plugin.plugins()['plugin']
 
316
        self.assertEqual('foo', plugin.test_suite())
365
317
 
366
318
    def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
367
319
        self.setup_plugin()
368
 
        loader = tests.TestUtil.TestLoader()
369
 
        p = plugin.plugins()['plugin']
370
 
        self.assertEqual(None, p.load_plugin_tests(loader))
 
320
        loader = TestUtil.TestLoader()
 
321
        plugin = bzrlib.plugin.plugins()['plugin']
 
322
        self.assertEqual(None, plugin.load_plugin_tests(loader))
371
323
 
372
324
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
373
325
        source = """
374
326
def load_tests(standard_tests, module, loader):
375
327
    return 'foo'"""
376
328
        self.setup_plugin(source)
377
 
        loader = tests.TestUtil.TestLoader()
378
 
        p = plugin.plugins()['plugin']
379
 
        self.assertEqual('foo', p.load_plugin_tests(loader))
380
 
 
381
 
    def check_version_info(self, expected, source='', name='plugin'):
382
 
        self.setup_plugin(source)
383
 
        self.assertEqual(expected, plugin.plugins()[name].version_info())
 
329
        loader = TestUtil.TestLoader()
 
330
        plugin = bzrlib.plugin.plugins()['plugin']
 
331
        self.assertEqual('foo', plugin.load_plugin_tests(loader))
384
332
 
385
333
    def test_no_version_info(self):
386
 
        self.check_version_info(None)
 
334
        self.setup_plugin()
 
335
        plugin = bzrlib.plugin.plugins()['plugin']
 
336
        self.assertEqual(None, plugin.version_info())
387
337
 
388
338
    def test_with_version_info(self):
389
 
        self.check_version_info((1, 2, 3, 'dev', 4),
390
 
                                "version_info = (1, 2, 3, 'dev', 4)")
 
339
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
 
340
        plugin = bzrlib.plugin.plugins()['plugin']
 
341
        self.assertEqual((1, 2, 3, 'dev', 4), plugin.version_info())
391
342
 
392
343
    def test_short_version_info_gets_padded(self):
393
344
        # the gtk plugin has version_info = (1,2,3) rather than the 5-tuple.
394
345
        # so we adapt it
395
 
        self.check_version_info((1, 2, 3, 'final', 0),
396
 
                                "version_info = (1, 2, 3)")
397
 
 
398
 
    def check_version(self, expected, source=None, name='plugin'):
399
 
        self.setup_plugin(source)
400
 
        self.assertEqual(expected, plugins[name].__version__)
 
346
        self.setup_plugin("version_info = (1, 2, 3)")
 
347
        plugin = bzrlib.plugin.plugins()['plugin']
 
348
        self.assertEqual((1, 2, 3, 'final', 0), plugin.version_info())
401
349
 
402
350
    def test_no_version_info___version__(self):
403
351
        self.setup_plugin()
442
390
    def test_dev_fallback__version__with_version_info(self):
443
391
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
444
392
        plugin = bzrlib.plugin.plugins()['plugin']
445
 
        self.assertEqual("1.2.3dev4", plugin.__version__)
 
393
        self.assertEqual("1.2.3.dev.4", plugin.__version__)
446
394
 
447
395
    def test_final__version__with_version_info(self):
448
396
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
449
397
        plugin = bzrlib.plugin.plugins()['plugin']
450
398
        self.assertEqual("1.2.3", plugin.__version__)
451
399
 
452
 
    def test_final_fallback__version__with_version_info(self):
453
 
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
454
 
        plugin = bzrlib.plugin.plugins()['plugin']
455
 
        self.assertEqual("1.2.3.final.2", plugin.__version__)
456
 
 
457
 
 
458
 
class TestPluginHelp(tests.TestCaseInTempDir):
 
400
 
 
401
class TestPluginHelp(TestCaseInTempDir):
459
402
 
460
403
    def split_help_commands(self):
461
404
        help = {}
490
433
    def test_plugin_help_shows_plugin(self):
491
434
        # Create a test plugin
492
435
        os.mkdir('plugin_test')
493
 
        f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
494
 
        f.write("""\
495
 
from bzrlib import commands
496
 
class cmd_myplug(commands.Command):
497
 
    __doc__ = '''Just a simple test plugin.'''
498
 
    aliases = ['mplg']
499
 
    def run(self):
500
 
        print 'Hello from my plugin'
501
 
 
502
 
"""
503
 
)
 
436
        f = open(pathjoin('plugin_test', 'myplug.py'), 'w')
 
437
        f.write(PLUGIN_TEXT)
504
438
        f.close()
505
439
 
506
440
        try:
520
454
                delattr(bzrlib.plugins, 'myplug')
521
455
 
522
456
 
 
457
class TestSetPluginsPath(TestCase):
 
458
 
 
459
    def test_set_plugins_path(self):
 
460
        """set_plugins_path should set the module __path__ correctly."""
 
461
        old_path = bzrlib.plugins.__path__
 
462
        try:
 
463
            bzrlib.plugins.__path__ = []
 
464
            expected_path = bzrlib.plugin.set_plugins_path()
 
465
            self.assertEqual(expected_path, bzrlib.plugins.__path__)
 
466
        finally:
 
467
            bzrlib.plugins.__path__ = old_path
 
468
 
 
469
    def test_set_plugins_path_with_trailing_slashes(self):
 
470
        """set_plugins_path should set the module __path__ based on
 
471
        BZR_PLUGIN_PATH after removing all trailing slashes."""
 
472
        old_path = bzrlib.plugins.__path__
 
473
        old_env = os.environ.get('BZR_PLUGIN_PATH')
 
474
        try:
 
475
            bzrlib.plugins.__path__ = []
 
476
            os.environ['BZR_PLUGIN_PATH'] = "first\\//\\" + os.pathsep + \
 
477
                "second/\\/\\/"
 
478
            bzrlib.plugin.set_plugins_path()
 
479
            # We expect our nominated paths to have all path-seps removed,
 
480
            # and this is testing only that.
 
481
            expected_path = ['first', 'second']
 
482
            self.assertEqual(expected_path,
 
483
                bzrlib.plugins.__path__[:len(expected_path)])
 
484
        finally:
 
485
            bzrlib.plugins.__path__ = old_path
 
486
            if old_env is not None:
 
487
                os.environ['BZR_PLUGIN_PATH'] = old_env
 
488
            else:
 
489
                del os.environ['BZR_PLUGIN_PATH']
 
490
 
 
491
 
523
492
class TestHelpIndex(tests.TestCase):
524
493
    """Tests for the PluginsHelpIndex class."""
525
494
 
628
597
        self.assertEqual('foo_bar', topic.get_help_topic())
629
598
 
630
599
 
631
 
class TestLoadFromPath(tests.TestCaseInTempDir):
632
 
 
633
 
    def setUp(self):
634
 
        super(TestLoadFromPath, self).setUp()
635
 
        # Change bzrlib.plugin to think no plugins have been loaded yet.
636
 
        self.overrideAttr(bzrlib.plugins, '__path__', [])
637
 
        self.overrideAttr(plugin, '_loaded', False)
638
 
 
639
 
        # Monkey-patch load_from_path to stop it from actually loading anything.
640
 
        self.overrideAttr(plugin, 'load_from_path', lambda dirs: None)
 
600
def clear_plugins(test_case):
 
601
    # Save the attributes that we're about to monkey-patch.
 
602
    old_plugins_path = bzrlib.plugins.__path__
 
603
    old_loaded = plugin._loaded
 
604
    old_load_from_path = plugin.load_from_path
 
605
    # Change bzrlib.plugin to think no plugins have been loaded yet.
 
606
    bzrlib.plugins.__path__ = []
 
607
    plugin._loaded = False
 
608
    # Monkey-patch load_from_path to stop it from actually loading anything.
 
609
    def load_from_path(dirs):
 
610
        pass
 
611
    plugin.load_from_path = load_from_path
 
612
    def restore_plugins():
 
613
        bzrlib.plugins.__path__ = old_plugins_path
 
614
        plugin._loaded = old_loaded
 
615
        plugin.load_from_path = old_load_from_path
 
616
    test_case.addCleanup(restore_plugins)
 
617
 
 
618
 
 
619
class TestPluginPaths(tests.TestCase):
641
620
 
642
621
    def test_set_plugins_path_with_args(self):
 
622
        clear_plugins(self)
643
623
        plugin.set_plugins_path(['a', 'b'])
644
624
        self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
645
625
 
646
626
    def test_set_plugins_path_defaults(self):
 
627
        clear_plugins(self)
647
628
        plugin.set_plugins_path()
648
629
        self.assertEqual(plugin.get_standard_plugins_path(),
649
630
                         bzrlib.plugins.__path__)
650
631
 
651
632
    def test_get_standard_plugins_path(self):
652
633
        path = plugin.get_standard_plugins_path()
 
634
        self.assertEqual(plugin.get_default_plugin_path(), path[0])
653
635
        for directory in path:
654
 
            self.assertNotContainsRe(directory, r'\\/$')
 
636
            self.assertNotContainsRe(r'\\/$', directory)
655
637
        try:
656
638
            from distutils.sysconfig import get_python_lib
657
639
        except ImportError:
666
648
                    self.fail('No path to global plugins')
667
649
 
668
650
    def test_get_standard_plugins_path_env(self):
669
 
        self.overrideEnv('BZR_PLUGIN_PATH', 'foo/')
670
 
        path = plugin.get_standard_plugins_path()
671
 
        for directory in path:
672
 
            self.assertNotContainsRe(directory, r'\\/$')
 
651
        os.environ['BZR_PLUGIN_PATH'] = 'foo/'
 
652
        self.assertEqual('foo', plugin.get_standard_plugins_path()[0])
 
653
 
 
654
 
 
655
class TestLoadPlugins(tests.TestCaseInTempDir):
673
656
 
674
657
    def test_load_plugins(self):
 
658
        clear_plugins(self)
675
659
        plugin.load_plugins(['.'])
676
660
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
677
661
        # subsequent loads are no-ops
679
663
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
680
664
 
681
665
    def test_load_plugins_default(self):
 
666
        clear_plugins(self)
682
667
        plugin.load_plugins()
683
668
        path = plugin.get_standard_plugins_path()
684
669
        self.assertEqual(path, bzrlib.plugins.__path__)
685
 
 
686
 
 
687
 
class TestEnvPluginPath(tests.TestCase):
688
 
 
689
 
    def setUp(self):
690
 
        super(TestEnvPluginPath, self).setUp()
691
 
        self.overrideAttr(plugin, 'DEFAULT_PLUGIN_PATH', None)
692
 
 
693
 
        self.user = plugin.get_user_plugin_path()
694
 
        self.site = plugin.get_site_plugin_path()
695
 
        self.core = plugin.get_core_plugin_path()
696
 
 
697
 
    def _list2paths(self, *args):
698
 
        paths = []
699
 
        for p in args:
700
 
            plugin._append_new_path(paths, p)
701
 
        return paths
702
 
 
703
 
    def _set_path(self, *args):
704
 
        path = os.pathsep.join(self._list2paths(*args))
705
 
        self.overrideEnv('BZR_PLUGIN_PATH', path)
706
 
 
707
 
    def check_path(self, expected_dirs, setting_dirs):
708
 
        if setting_dirs:
709
 
            self._set_path(*setting_dirs)
710
 
        actual = plugin.get_standard_plugins_path()
711
 
        self.assertEquals(self._list2paths(*expected_dirs), actual)
712
 
 
713
 
    def test_default(self):
714
 
        self.check_path([self.user, self.core, self.site],
715
 
                        None)
716
 
 
717
 
    def test_adhoc_policy(self):
718
 
        self.check_path([self.user, self.core, self.site],
719
 
                        ['+user', '+core', '+site'])
720
 
 
721
 
    def test_fallback_policy(self):
722
 
        self.check_path([self.core, self.site, self.user],
723
 
                        ['+core', '+site', '+user'])
724
 
 
725
 
    def test_override_policy(self):
726
 
        self.check_path([self.user, self.site, self.core],
727
 
                        ['+user', '+site', '+core'])
728
 
 
729
 
    def test_disable_user(self):
730
 
        self.check_path([self.core, self.site], ['-user'])
731
 
 
732
 
    def test_disable_user_twice(self):
733
 
        # Ensures multiple removals don't left cruft
734
 
        self.check_path([self.core, self.site], ['-user', '-user'])
735
 
 
736
 
    def test_duplicates_are_removed(self):
737
 
        self.check_path([self.user, self.core, self.site],
738
 
                        ['+user', '+user'])
739
 
        # And only the first reference is kept (since the later references will
740
 
        # only produce '<plugin> already loaded' mutters)
741
 
        self.check_path([self.user, self.core, self.site],
742
 
                        ['+user', '+user', '+core',
743
 
                         '+user', '+site', '+site',
744
 
                         '+core'])
745
 
 
746
 
    def test_disable_overrides_enable(self):
747
 
        self.check_path([self.core, self.site], ['-user', '+user'])
748
 
 
749
 
    def test_disable_core(self):
750
 
        self.check_path([self.site], ['-core'])
751
 
        self.check_path([self.user, self.site], ['+user', '-core'])
752
 
 
753
 
    def test_disable_site(self):
754
 
        self.check_path([self.core], ['-site'])
755
 
        self.check_path([self.user, self.core], ['-site', '+user'])
756
 
 
757
 
    def test_override_site(self):
758
 
        self.check_path(['mysite', self.user, self.core],
759
 
                        ['mysite', '-site', '+user'])
760
 
        self.check_path(['mysite', self.core],
761
 
                        ['mysite', '-site'])
762
 
 
763
 
    def test_override_core(self):
764
 
        self.check_path(['mycore', self.user, self.site],
765
 
                        ['mycore', '-core', '+user', '+site'])
766
 
        self.check_path(['mycore', self.site],
767
 
                        ['mycore', '-core'])
768
 
 
769
 
    def test_my_plugin_only(self):
770
 
        self.check_path(['myplugin'], ['myplugin', '-user', '-core', '-site'])
771
 
 
772
 
    def test_my_plugin_first(self):
773
 
        self.check_path(['myplugin', self.core, self.site, self.user],
774
 
                        ['myplugin', '+core', '+site', '+user'])
775
 
 
776
 
    def test_bogus_references(self):
777
 
        self.check_path(['+foo', '-bar', self.core, self.site],
778
 
                        ['+foo', '-bar'])
779
 
 
780
 
 
781
 
class TestDisablePlugin(BaseTestPlugins):
782
 
 
783
 
    def setUp(self):
784
 
        super(TestDisablePlugin, self).setUp()
785
 
        self.create_plugin_package('test_foo')
786
 
        # Make sure we don't pollute the plugins namespace
787
 
        self.overrideAttr(plugins, '__path__')
788
 
        # Be paranoid in case a test fail
789
 
        self.addCleanup(self._unregister_plugin, 'test_foo')
790
 
 
791
 
    def test_cannot_import(self):
792
 
        self.overrideEnv('BZR_DISABLE_PLUGINS', 'test_foo')
793
 
        plugin.set_plugins_path(['.'])
794
 
        try:
795
 
            import bzrlib.plugins.test_foo
796
 
        except ImportError:
797
 
            pass
798
 
        self.assertPluginUnknown('test_foo')
799
 
 
800
 
    def test_regular_load(self):
801
 
        self.overrideAttr(plugin, '_loaded', False)
802
 
        plugin.load_plugins(['.'])
803
 
        self.assertPluginKnown('test_foo')
804
 
        self.assertDocstring("This is the doc for test_foo",
805
 
                             bzrlib.plugins.test_foo)
806
 
 
807
 
    def test_not_loaded(self):
808
 
        self.warnings = []
809
 
        def captured_warning(*args, **kwargs):
810
 
            self.warnings.append((args, kwargs))
811
 
        self.overrideAttr(trace, 'warning', captured_warning)
812
 
        # Reset the flag that protect against double loading
813
 
        self.overrideAttr(plugin, '_loaded', False)
814
 
        self.overrideEnv('BZR_DISABLE_PLUGINS', 'test_foo')
815
 
        plugin.load_plugins(['.'])
816
 
        self.assertPluginUnknown('test_foo')
817
 
        # Make sure we don't warn about the plugin ImportError since this has
818
 
        # been *requested* by the user.
819
 
        self.assertLength(0, self.warnings)
820
 
 
821
 
 
822
 
 
823
 
class TestLoadPluginAtSyntax(tests.TestCase):
824
 
 
825
 
    def _get_paths(self, paths):
826
 
        return plugin._get_specific_plugin_paths(paths)
827
 
 
828
 
    def test_empty(self):
829
 
        self.assertEquals([], self._get_paths(None))
830
 
        self.assertEquals([], self._get_paths(''))
831
 
 
832
 
    def test_one_path(self):
833
 
        self.assertEquals([('b', 'man')], self._get_paths('b@man'))
834
 
 
835
 
    def test_bogus_path(self):
836
 
        # We need a '@'
837
 
        self.assertRaises(errors.BzrCommandError, self._get_paths, 'batman')
838
 
        # Too much '@' isn't good either
839
 
        self.assertRaises(errors.BzrCommandError, self._get_paths,
840
 
                          'batman@mobile@cave')
841
 
        # An empty description probably indicates a problem
842
 
        self.assertRaises(errors.BzrCommandError, self._get_paths,
843
 
                          os.pathsep.join(['batman@cave', '', 'robin@mobile']))
844
 
 
845
 
 
846
 
class TestLoadPluginAt(BaseTestPlugins):
847
 
 
848
 
    def setUp(self):
849
 
        super(TestLoadPluginAt, self).setUp()
850
 
        # Make sure we don't pollute the plugins namespace
851
 
        self.overrideAttr(plugins, '__path__')
852
 
        # Reset the flag that protect against double loading
853
 
        self.overrideAttr(plugin, '_loaded', False)
854
 
        # Create the same plugin in two directories
855
 
        self.create_plugin_package('test_foo', dir='non-standard-dir')
856
 
        # The "normal" directory, we use 'standard' instead of 'plugins' to
857
 
        # avoid depending on the precise naming.
858
 
        self.create_plugin_package('test_foo', dir='standard/test_foo')
859
 
        # All the tests will load the 'test_foo' plugin from various locations
860
 
        self.addCleanup(self._unregister_plugin, 'test_foo')
861
 
        # Unfortunately there's global cached state for the specific
862
 
        # registered paths.
863
 
        self.addCleanup(plugin.PluginImporter.reset)
864
 
 
865
 
    def assertTestFooLoadedFrom(self, path):
866
 
        self.assertPluginKnown('test_foo')
867
 
        self.assertDocstring('This is the doc for test_foo',
868
 
                             bzrlib.plugins.test_foo)
869
 
        self.assertEqual(path, bzrlib.plugins.test_foo.dir_source)
870
 
 
871
 
    def test_regular_load(self):
872
 
        plugin.load_plugins(['standard'])
873
 
        self.assertTestFooLoadedFrom('standard/test_foo')
874
 
 
875
 
    def test_import(self):
876
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
877
 
        plugin.set_plugins_path(['standard'])
878
 
        try:
879
 
            import bzrlib.plugins.test_foo
880
 
        except ImportError:
881
 
            pass
882
 
        self.assertTestFooLoadedFrom('non-standard-dir')
883
 
 
884
 
    def test_loading(self):
885
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
886
 
        plugin.load_plugins(['standard'])
887
 
        self.assertTestFooLoadedFrom('non-standard-dir')
888
 
 
889
 
    def test_compiled_loaded(self):
890
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
891
 
        plugin.load_plugins(['standard'])
892
 
        self.assertTestFooLoadedFrom('non-standard-dir')
893
 
        self.assertIsSameRealPath('non-standard-dir/__init__.py',
894
 
                                  bzrlib.plugins.test_foo.__file__)
895
 
 
896
 
        # Try importing again now that the source has been compiled
897
 
        self._unregister_plugin('test_foo')
898
 
        plugin._loaded = False
899
 
        plugin.load_plugins(['standard'])
900
 
        self.assertTestFooLoadedFrom('non-standard-dir')
901
 
        if __debug__:
902
 
            suffix = 'pyc'
903
 
        else:
904
 
            suffix = 'pyo'
905
 
        self.assertIsSameRealPath('non-standard-dir/__init__.%s' % suffix,
906
 
                                  bzrlib.plugins.test_foo.__file__)
907
 
 
908
 
    def test_submodule_loading(self):
909
 
        # We create an additional directory under the one for test_foo
910
 
        self.create_plugin_package('test_bar', dir='non-standard-dir/test_bar')
911
 
        self.addCleanup(self._unregister_plugin_submodule,
912
 
                        'test_foo', 'test_bar')
913
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
914
 
        plugin.set_plugins_path(['standard'])
915
 
        import bzrlib.plugins.test_foo
916
 
        self.assertEqual('bzrlib.plugins.test_foo',
917
 
                         bzrlib.plugins.test_foo.__package__)
918
 
        import bzrlib.plugins.test_foo.test_bar
919
 
        self.assertIsSameRealPath('non-standard-dir/test_bar/__init__.py',
920
 
                                  bzrlib.plugins.test_foo.test_bar.__file__)
921
 
 
922
 
    def test_relative_submodule_loading(self):
923
 
        self.create_plugin_package('test_foo', dir='another-dir', source='''
924
 
import test_bar
925
 
''')
926
 
        # We create an additional directory under the one for test_foo
927
 
        self.create_plugin_package('test_bar', dir='another-dir/test_bar')
928
 
        self.addCleanup(self._unregister_plugin_submodule,
929
 
                        'test_foo', 'test_bar')
930
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@another-dir')
931
 
        plugin.set_plugins_path(['standard'])
932
 
        import bzrlib.plugins.test_foo
933
 
        self.assertEqual('bzrlib.plugins.test_foo',
934
 
                         bzrlib.plugins.test_foo.__package__)
935
 
        self.assertIsSameRealPath('another-dir/test_bar/__init__.py',
936
 
                                  bzrlib.plugins.test_foo.test_bar.__file__)
937
 
 
938
 
    def test_loading_from___init__only(self):
939
 
        # We rename the existing __init__.py file to ensure that we don't load
940
 
        # a random file
941
 
        init = 'non-standard-dir/__init__.py'
942
 
        random = 'non-standard-dir/setup.py'
943
 
        os.rename(init, random)
944
 
        self.addCleanup(os.rename, random, init)
945
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
946
 
        plugin.load_plugins(['standard'])
947
 
        self.assertPluginUnknown('test_foo')
948
 
 
949
 
    def test_loading_from_specific_file(self):
950
 
        plugin_dir = 'non-standard-dir'
951
 
        plugin_file_name = 'iamtestfoo.py'
952
 
        plugin_path = osutils.pathjoin(plugin_dir, plugin_file_name)
953
 
        source = '''\
954
 
"""This is the doc for %s"""
955
 
dir_source = '%s'
956
 
''' % ('test_foo', plugin_path)
957
 
        self.create_plugin('test_foo', source=source,
958
 
                           dir=plugin_dir, file_name=plugin_file_name)
959
 
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@%s' % plugin_path)
960
 
        plugin.load_plugins(['standard'])
961
 
        self.assertTestFooLoadedFrom(plugin_path)
962
 
 
963
 
 
964
 
class TestDescribePlugins(BaseTestPlugins):
965
 
 
966
 
    def test_describe_plugins(self):
967
 
        class DummyModule(object):
968
 
            __doc__ = 'Hi there'
969
 
        class DummyPlugin(object):
970
 
            __version__ = '0.1.0'
971
 
            module = DummyModule()
972
 
        def dummy_plugins():
973
 
            return { 'good': DummyPlugin() }
974
 
        self.overrideAttr(plugin, 'plugin_warnings',
975
 
            {'bad': ['Failed to load (just testing)']})
976
 
        self.overrideAttr(plugin, 'plugins', dummy_plugins)
977
 
        self.assertEquals("""\
978
 
bad (failed to load)
979
 
  ** Failed to load (just testing)
980
 
 
981
 
good 0.1.0
982
 
  Hi there
983
 
 
984
 
""", ''.join(plugin.describe_plugins()))