/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_plugins.py

  • Committer: Jelmer Vernooij
  • Date: 2010-03-22 10:11:00 UTC
  • mto: This revision was merged to the branch mainline in revision 5105.
  • Revision ID: jelmer@samba.org-20100322101100-5omqm0h278vmvv1e
make sure working tree stays around after rmbranch has run.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2010 Canonical Ltd
 
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for plugins"""
 
18
 
 
19
# XXX: There are no plugin tests at the moment because the plugin module
 
20
# affects the global state of the process.  See bzrlib/plugins.py for more
 
21
# comments.
 
22
 
 
23
from cStringIO import StringIO
 
24
import logging
 
25
import os
 
26
import sys
 
27
 
 
28
import bzrlib
 
29
from bzrlib import (
 
30
    osutils,
 
31
    plugin,
 
32
    tests,
 
33
    )
 
34
 
 
35
 
 
36
# TODO: Write a test for plugin decoration of commands.
 
37
 
 
38
class TestLoadingPlugins(tests.TestCaseInTempDir):
 
39
 
 
40
    activeattributes = {}
 
41
 
 
42
    def test_plugins_with_the_same_name_are_not_loaded(self):
 
43
        # This test tests that having two plugins in different directories does
 
44
        # not result in both being loaded when they have the same name.  get a
 
45
        # file name we can use which is also a valid attribute for accessing in
 
46
        # activeattributes. - we cannot give import parameters.
 
47
        tempattribute = "0"
 
48
        self.failIf(tempattribute in self.activeattributes)
 
49
        # set a place for the plugins to record their loading, and at the same
 
50
        # time validate that the location the plugins should record to is
 
51
        # valid and correct.
 
52
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
53
            [tempattribute] = []
 
54
        self.failUnless(tempattribute in self.activeattributes)
 
55
        # create two plugin directories
 
56
        os.mkdir('first')
 
57
        os.mkdir('second')
 
58
        # write a plugin that will record when its loaded in the
 
59
        # tempattribute list.
 
60
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
 
61
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
 
62
 
 
63
        outfile = open(os.path.join('first', 'plugin.py'), 'w')
 
64
        try:
 
65
            outfile.write(template % (tempattribute, 'first'))
 
66
            outfile.write('\n')
 
67
        finally:
 
68
            outfile.close()
 
69
 
 
70
        outfile = open(os.path.join('second', 'plugin.py'), 'w')
 
71
        try:
 
72
            outfile.write(template % (tempattribute, 'second'))
 
73
            outfile.write('\n')
 
74
        finally:
 
75
            outfile.close()
 
76
 
 
77
        try:
 
78
            bzrlib.plugin.load_from_path(['first', 'second'])
 
79
            self.assertEqual(['first'], self.activeattributes[tempattribute])
 
80
        finally:
 
81
            # remove the plugin 'plugin'
 
82
            del self.activeattributes[tempattribute]
 
83
            if 'bzrlib.plugins.plugin' in sys.modules:
 
84
                del sys.modules['bzrlib.plugins.plugin']
 
85
            if getattr(bzrlib.plugins, 'plugin', None):
 
86
                del bzrlib.plugins.plugin
 
87
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
 
88
 
 
89
    def test_plugins_from_different_dirs_can_demand_load(self):
 
90
        # This test tests that having two plugins in different
 
91
        # directories with different names allows them both to be loaded, when
 
92
        # we do a direct import statement.
 
93
        # Determine a file name we can use which is also a valid attribute
 
94
        # for accessing in activeattributes. - we cannot give import parameters.
 
95
        tempattribute = "different-dirs"
 
96
        self.failIf(tempattribute in self.activeattributes)
 
97
        # set a place for the plugins to record their loading, and at the same
 
98
        # time validate that the location the plugins should record to is
 
99
        # valid and correct.
 
100
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
101
            [tempattribute] = []
 
102
        self.failUnless(tempattribute in self.activeattributes)
 
103
        # create two plugin directories
 
104
        os.mkdir('first')
 
105
        os.mkdir('second')
 
106
        # write plugins that will record when they are loaded in the
 
107
        # tempattribute list.
 
108
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
 
109
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
 
110
 
 
111
        outfile = open(os.path.join('first', 'pluginone.py'), 'w')
 
112
        try:
 
113
            outfile.write(template % (tempattribute, 'first'))
 
114
            outfile.write('\n')
 
115
        finally:
 
116
            outfile.close()
 
117
 
 
118
        outfile = open(os.path.join('second', 'plugintwo.py'), 'w')
 
119
        try:
 
120
            outfile.write(template % (tempattribute, 'second'))
 
121
            outfile.write('\n')
 
122
        finally:
 
123
            outfile.close()
 
124
 
 
125
        oldpath = bzrlib.plugins.__path__
 
126
        try:
 
127
            bzrlib.plugins.__path__ = ['first', 'second']
 
128
            exec "import bzrlib.plugins.pluginone"
 
129
            self.assertEqual(['first'], self.activeattributes[tempattribute])
 
130
            exec "import bzrlib.plugins.plugintwo"
 
131
            self.assertEqual(['first', 'second'],
 
132
                self.activeattributes[tempattribute])
 
133
        finally:
 
134
            # remove the plugin 'plugin'
 
135
            del self.activeattributes[tempattribute]
 
136
            if getattr(bzrlib.plugins, 'pluginone', None):
 
137
                del bzrlib.plugins.pluginone
 
138
            if getattr(bzrlib.plugins, 'plugintwo', None):
 
139
                del bzrlib.plugins.plugintwo
 
140
        self.failIf(getattr(bzrlib.plugins, 'pluginone', None))
 
141
        self.failIf(getattr(bzrlib.plugins, 'plugintwo', None))
 
142
 
 
143
    def test_plugins_can_load_from_directory_with_trailing_slash(self):
 
144
        # This test tests that a plugin can load from a directory when the
 
145
        # directory in the path has a trailing slash.
 
146
        # check the plugin is not loaded already
 
147
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
 
148
        tempattribute = "trailing-slash"
 
149
        self.failIf(tempattribute in self.activeattributes)
 
150
        # set a place for the plugin to record its loading, and at the same
 
151
        # time validate that the location the plugin should record to is
 
152
        # valid and correct.
 
153
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
154
            [tempattribute] = []
 
155
        self.failUnless(tempattribute in self.activeattributes)
 
156
        # create a directory for the plugin
 
157
        os.mkdir('plugin_test')
 
158
        # write a plugin that will record when its loaded in the
 
159
        # tempattribute list.
 
160
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
 
161
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
 
162
 
 
163
        outfile = open(os.path.join('plugin_test', 'ts_plugin.py'), 'w')
 
164
        try:
 
165
            outfile.write(template % (tempattribute, 'plugin'))
 
166
            outfile.write('\n')
 
167
        finally:
 
168
            outfile.close()
 
169
 
 
170
        try:
 
171
            bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
 
172
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
 
173
        finally:
 
174
            # remove the plugin 'plugin'
 
175
            del self.activeattributes[tempattribute]
 
176
            if getattr(bzrlib.plugins, 'ts_plugin', None):
 
177
                del bzrlib.plugins.ts_plugin
 
178
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
 
179
 
 
180
    def load_and_capture(self, name):
 
181
        """Load plugins from '.' capturing the output.
 
182
 
 
183
        :param name: The name of the plugin.
 
184
        :return: A string with the log from the plugin loading call.
 
185
        """
 
186
        # Capture output
 
187
        stream = StringIO()
 
188
        try:
 
189
            handler = logging.StreamHandler(stream)
 
190
            log = logging.getLogger('bzr')
 
191
            log.addHandler(handler)
 
192
            try:
 
193
                try:
 
194
                    bzrlib.plugin.load_from_path(['.'])
 
195
                finally:
 
196
                    if 'bzrlib.plugins.%s' % name in sys.modules:
 
197
                        del sys.modules['bzrlib.plugins.%s' % name]
 
198
                    if getattr(bzrlib.plugins, name, None):
 
199
                        delattr(bzrlib.plugins, name)
 
200
            finally:
 
201
                # Stop capturing output
 
202
                handler.flush()
 
203
                handler.close()
 
204
                log.removeHandler(handler)
 
205
            return stream.getvalue()
 
206
        finally:
 
207
            stream.close()
 
208
 
 
209
    def test_plugin_with_bad_api_version_reports(self):
 
210
        # This plugin asks for bzrlib api version 1.0.0, which is not supported
 
211
        # anymore.
 
212
        name = 'wants100.py'
 
213
        f = file(name, 'w')
 
214
        try:
 
215
            f.write("import bzrlib.api\n"
 
216
                "bzrlib.api.require_any_api(bzrlib, [(1, 0, 0)])\n")
 
217
        finally:
 
218
            f.close()
 
219
 
 
220
        log = self.load_and_capture(name)
 
221
        self.assertContainsRe(log,
 
222
            r"It requested API version")
 
223
 
 
224
    def test_plugin_with_bad_name_does_not_load(self):
 
225
        # The file name here invalid for a python module.
 
226
        name = 'bzr-bad plugin-name..py'
 
227
        file(name, 'w').close()
 
228
        log = self.load_and_capture(name)
 
229
        self.assertContainsRe(log,
 
230
            r"Unable to load 'bzr-bad plugin-name\.' in '\.' as a plugin "
 
231
            "because the file path isn't a valid module name; try renaming "
 
232
            "it to 'bad_plugin_name_'\.")
 
233
 
 
234
 
 
235
class TestPlugins(tests.TestCaseInTempDir):
 
236
 
 
237
    def setup_plugin(self, source=""):
 
238
        # This test tests a new plugin appears in bzrlib.plugin.plugins().
 
239
        # check the plugin is not loaded already
 
240
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
 
241
        # write a plugin that _cannot_ fail to load.
 
242
        file('plugin.py', 'w').write(source + '\n')
 
243
        self.addCleanup(self.teardown_plugin)
 
244
        bzrlib.plugin.load_from_path(['.'])
 
245
 
 
246
    def teardown_plugin(self):
 
247
        # remove the plugin 'plugin'
 
248
        if 'bzrlib.plugins.plugin' in sys.modules:
 
249
            del sys.modules['bzrlib.plugins.plugin']
 
250
        if getattr(bzrlib.plugins, 'plugin', None):
 
251
            del bzrlib.plugins.plugin
 
252
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
 
253
 
 
254
    def test_plugin_appears_in_plugins(self):
 
255
        self.setup_plugin()
 
256
        self.failUnless('plugin' in bzrlib.plugin.plugins())
 
257
        self.failUnless(getattr(bzrlib.plugins, 'plugin', None))
 
258
        plugins = bzrlib.plugin.plugins()
 
259
        plugin = plugins['plugin']
 
260
        self.assertIsInstance(plugin, bzrlib.plugin.PlugIn)
 
261
        self.assertEqual(bzrlib.plugins.plugin, plugin.module)
 
262
 
 
263
    def test_trivial_plugin_get_path(self):
 
264
        self.setup_plugin()
 
265
        plugins = bzrlib.plugin.plugins()
 
266
        plugin = plugins['plugin']
 
267
        plugin_path = self.test_dir + '/plugin.py'
 
268
        self.assertIsSameRealPath(plugin_path, osutils.normpath(plugin.path()))
 
269
 
 
270
    def test_plugin_get_path_py_not_pyc(self):
 
271
        # first import creates plugin.pyc
 
272
        self.setup_plugin()
 
273
        self.teardown_plugin()
 
274
        bzrlib.plugin.load_from_path(['.']) # import plugin.pyc
 
275
        plugins = bzrlib.plugin.plugins()
 
276
        plugin = plugins['plugin']
 
277
        plugin_path = self.test_dir + '/plugin.py'
 
278
        self.assertIsSameRealPath(plugin_path, osutils.normpath(plugin.path()))
 
279
 
 
280
    def test_plugin_get_path_pyc_only(self):
 
281
        # first import creates plugin.pyc (or plugin.pyo depending on __debug__)
 
282
        self.setup_plugin()
 
283
        self.teardown_plugin()
 
284
        os.unlink(self.test_dir + '/plugin.py')
 
285
        bzrlib.plugin.load_from_path(['.']) # import plugin.pyc (or .pyo)
 
286
        plugins = bzrlib.plugin.plugins()
 
287
        plugin = plugins['plugin']
 
288
        if __debug__:
 
289
            plugin_path = self.test_dir + '/plugin.pyc'
 
290
        else:
 
291
            plugin_path = self.test_dir + '/plugin.pyo'
 
292
        self.assertIsSameRealPath(plugin_path, osutils.normpath(plugin.path()))
 
293
 
 
294
    def test_no_test_suite_gives_None_for_test_suite(self):
 
295
        self.setup_plugin()
 
296
        plugin = bzrlib.plugin.plugins()['plugin']
 
297
        self.assertEqual(None, plugin.test_suite())
 
298
 
 
299
    def test_test_suite_gives_test_suite_result(self):
 
300
        source = """def test_suite(): return 'foo'"""
 
301
        self.setup_plugin(source)
 
302
        plugin = bzrlib.plugin.plugins()['plugin']
 
303
        self.assertEqual('foo', plugin.test_suite())
 
304
 
 
305
    def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
 
306
        self.setup_plugin()
 
307
        loader = tests.TestUtil.TestLoader()
 
308
        plugin = bzrlib.plugin.plugins()['plugin']
 
309
        self.assertEqual(None, plugin.load_plugin_tests(loader))
 
310
 
 
311
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
 
312
        source = """
 
313
def load_tests(standard_tests, module, loader):
 
314
    return 'foo'"""
 
315
        self.setup_plugin(source)
 
316
        loader = tests.TestUtil.TestLoader()
 
317
        plugin = bzrlib.plugin.plugins()['plugin']
 
318
        self.assertEqual('foo', plugin.load_plugin_tests(loader))
 
319
 
 
320
    def test_no_version_info(self):
 
321
        self.setup_plugin()
 
322
        plugin = bzrlib.plugin.plugins()['plugin']
 
323
        self.assertEqual(None, plugin.version_info())
 
324
 
 
325
    def test_with_version_info(self):
 
326
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
 
327
        plugin = bzrlib.plugin.plugins()['plugin']
 
328
        self.assertEqual((1, 2, 3, 'dev', 4), plugin.version_info())
 
329
 
 
330
    def test_short_version_info_gets_padded(self):
 
331
        # the gtk plugin has version_info = (1,2,3) rather than the 5-tuple.
 
332
        # so we adapt it
 
333
        self.setup_plugin("version_info = (1, 2, 3)")
 
334
        plugin = bzrlib.plugin.plugins()['plugin']
 
335
        self.assertEqual((1, 2, 3, 'final', 0), plugin.version_info())
 
336
 
 
337
    def test_no_version_info___version__(self):
 
338
        self.setup_plugin()
 
339
        plugin = bzrlib.plugin.plugins()['plugin']
 
340
        self.assertEqual("unknown", plugin.__version__)
 
341
 
 
342
    def test_str__version__with_version_info(self):
 
343
        self.setup_plugin("version_info = '1.2.3'")
 
344
        plugin = bzrlib.plugin.plugins()['plugin']
 
345
        self.assertEqual("1.2.3", plugin.__version__)
 
346
 
 
347
    def test_noniterable__version__with_version_info(self):
 
348
        self.setup_plugin("version_info = (1)")
 
349
        plugin = bzrlib.plugin.plugins()['plugin']
 
350
        self.assertEqual("1", plugin.__version__)
 
351
 
 
352
    def test_1__version__with_version_info(self):
 
353
        self.setup_plugin("version_info = (1,)")
 
354
        plugin = bzrlib.plugin.plugins()['plugin']
 
355
        self.assertEqual("1", plugin.__version__)
 
356
 
 
357
    def test_1_2__version__with_version_info(self):
 
358
        self.setup_plugin("version_info = (1, 2)")
 
359
        plugin = bzrlib.plugin.plugins()['plugin']
 
360
        self.assertEqual("1.2", plugin.__version__)
 
361
 
 
362
    def test_1_2_3__version__with_version_info(self):
 
363
        self.setup_plugin("version_info = (1, 2, 3)")
 
364
        plugin = bzrlib.plugin.plugins()['plugin']
 
365
        self.assertEqual("1.2.3", plugin.__version__)
 
366
 
 
367
    def test_candidate__version__with_version_info(self):
 
368
        self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
 
369
        plugin = bzrlib.plugin.plugins()['plugin']
 
370
        self.assertEqual("1.2.3rc1", plugin.__version__)
 
371
 
 
372
    def test_dev__version__with_version_info(self):
 
373
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 0)")
 
374
        plugin = bzrlib.plugin.plugins()['plugin']
 
375
        self.assertEqual("1.2.3dev", plugin.__version__)
 
376
 
 
377
    def test_dev_fallback__version__with_version_info(self):
 
378
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
 
379
        plugin = bzrlib.plugin.plugins()['plugin']
 
380
        self.assertEqual("1.2.3dev4", plugin.__version__)
 
381
 
 
382
    def test_final__version__with_version_info(self):
 
383
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
 
384
        plugin = bzrlib.plugin.plugins()['plugin']
 
385
        self.assertEqual("1.2.3", plugin.__version__)
 
386
 
 
387
    def test_final_fallback__version__with_version_info(self):
 
388
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
 
389
        plugin = bzrlib.plugin.plugins()['plugin']
 
390
        self.assertEqual("1.2.3.final.2", plugin.__version__)
 
391
 
 
392
 
 
393
class TestPluginHelp(tests.TestCaseInTempDir):
 
394
 
 
395
    def split_help_commands(self):
 
396
        help = {}
 
397
        current = None
 
398
        out, err = self.run_bzr('--no-plugins help commands')
 
399
        for line in out.splitlines():
 
400
            if not line.startswith(' '):
 
401
                current = line.split()[0]
 
402
            help[current] = help.get(current, '') + line
 
403
 
 
404
        return help
 
405
 
 
406
    def test_plugin_help_builtins_unaffected(self):
 
407
        # Check we don't get false positives
 
408
        help_commands = self.split_help_commands()
 
409
        for cmd_name in bzrlib.commands.builtin_command_names():
 
410
            if cmd_name in bzrlib.commands.plugin_command_names():
 
411
                continue
 
412
            try:
 
413
                help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
 
414
            except NotImplementedError:
 
415
                # some commands have no help
 
416
                pass
 
417
            else:
 
418
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
 
419
 
 
420
            if cmd_name in help_commands.keys():
 
421
                # some commands are hidden
 
422
                help = help_commands[cmd_name]
 
423
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
 
424
 
 
425
    def test_plugin_help_shows_plugin(self):
 
426
        # Create a test plugin
 
427
        os.mkdir('plugin_test')
 
428
        f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
 
429
        f.write("""\
 
430
from bzrlib import commands
 
431
class cmd_myplug(commands.Command):
 
432
    '''Just a simple test plugin.'''
 
433
    aliases = ['mplg']
 
434
    def run(self):
 
435
        print 'Hello from my plugin'
 
436
 
 
437
"""
 
438
)
 
439
        f.close()
 
440
 
 
441
        try:
 
442
            # Check its help
 
443
            bzrlib.plugin.load_from_path(['plugin_test'])
 
444
            bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
 
445
            help = self.run_bzr('help myplug')[0]
 
446
            self.assertContainsRe(help, 'plugin "myplug"')
 
447
            help = self.split_help_commands()['myplug']
 
448
            self.assertContainsRe(help, '\[myplug\]')
 
449
        finally:
 
450
            # unregister command
 
451
            if 'myplug' in bzrlib.commands.plugin_cmds:
 
452
                bzrlib.commands.plugin_cmds.remove('myplug')
 
453
            # remove the plugin 'myplug'
 
454
            if getattr(bzrlib.plugins, 'myplug', None):
 
455
                delattr(bzrlib.plugins, 'myplug')
 
456
 
 
457
 
 
458
class TestHelpIndex(tests.TestCase):
 
459
    """Tests for the PluginsHelpIndex class."""
 
460
 
 
461
    def test_default_constructable(self):
 
462
        index = plugin.PluginsHelpIndex()
 
463
 
 
464
    def test_get_topics_None(self):
 
465
        """Searching for None returns an empty list."""
 
466
        index = plugin.PluginsHelpIndex()
 
467
        self.assertEqual([], index.get_topics(None))
 
468
 
 
469
    def test_get_topics_for_plugin(self):
 
470
        """Searching for plugin name gets its docstring."""
 
471
        index = plugin.PluginsHelpIndex()
 
472
        # make a new plugin here for this test, even if we're run with
 
473
        # --no-plugins
 
474
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
 
475
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
 
476
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
 
477
        try:
 
478
            topics = index.get_topics('demo_module')
 
479
            self.assertEqual(1, len(topics))
 
480
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
 
481
            self.assertEqual(demo_module, topics[0].module)
 
482
        finally:
 
483
            del sys.modules['bzrlib.plugins.demo_module']
 
484
 
 
485
    def test_get_topics_no_topic(self):
 
486
        """Searching for something that is not a plugin returns []."""
 
487
        # test this by using a name that cannot be a plugin - its not
 
488
        # a valid python identifier.
 
489
        index = plugin.PluginsHelpIndex()
 
490
        self.assertEqual([], index.get_topics('nothing by this name'))
 
491
 
 
492
    def test_prefix(self):
 
493
        """PluginsHelpIndex has a prefix of 'plugins/'."""
 
494
        index = plugin.PluginsHelpIndex()
 
495
        self.assertEqual('plugins/', index.prefix)
 
496
 
 
497
    def test_get_plugin_topic_with_prefix(self):
 
498
        """Searching for plugins/demo_module returns help."""
 
499
        index = plugin.PluginsHelpIndex()
 
500
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
 
501
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
 
502
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
 
503
        try:
 
504
            topics = index.get_topics('plugins/demo_module')
 
505
            self.assertEqual(1, len(topics))
 
506
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
 
507
            self.assertEqual(demo_module, topics[0].module)
 
508
        finally:
 
509
            del sys.modules['bzrlib.plugins.demo_module']
 
510
 
 
511
 
 
512
class FakeModule(object):
 
513
    """A fake module to test with."""
 
514
 
 
515
    def __init__(self, doc, name):
 
516
        self.__doc__ = doc
 
517
        self.__name__ = name
 
518
 
 
519
 
 
520
class TestModuleHelpTopic(tests.TestCase):
 
521
    """Tests for the ModuleHelpTopic class."""
 
522
 
 
523
    def test_contruct(self):
 
524
        """Construction takes the module to document."""
 
525
        mod = FakeModule('foo', 'foo')
 
526
        topic = plugin.ModuleHelpTopic(mod)
 
527
        self.assertEqual(mod, topic.module)
 
528
 
 
529
    def test_get_help_text_None(self):
 
530
        """A ModuleHelpTopic returns the docstring for get_help_text."""
 
531
        mod = FakeModule(None, 'demo')
 
532
        topic = plugin.ModuleHelpTopic(mod)
 
533
        self.assertEqual("Plugin 'demo' has no docstring.\n",
 
534
            topic.get_help_text())
 
535
 
 
536
    def test_get_help_text_no_carriage_return(self):
 
537
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
 
538
        mod = FakeModule('one line of help', 'demo')
 
539
        topic = plugin.ModuleHelpTopic(mod)
 
540
        self.assertEqual("one line of help\n",
 
541
            topic.get_help_text())
 
542
 
 
543
    def test_get_help_text_carriage_return(self):
 
544
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
 
545
        mod = FakeModule('two lines of help\nand more\n', 'demo')
 
546
        topic = plugin.ModuleHelpTopic(mod)
 
547
        self.assertEqual("two lines of help\nand more\n",
 
548
            topic.get_help_text())
 
549
 
 
550
    def test_get_help_text_with_additional_see_also(self):
 
551
        mod = FakeModule('two lines of help\nand more', 'demo')
 
552
        topic = plugin.ModuleHelpTopic(mod)
 
553
        self.assertEqual("two lines of help\nand more\nSee also: bar, foo\n",
 
554
            topic.get_help_text(['foo', 'bar']))
 
555
 
 
556
    def test_get_help_topic(self):
 
557
        """The help topic for a plugin is its module name."""
 
558
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
 
559
        topic = plugin.ModuleHelpTopic(mod)
 
560
        self.assertEqual('demo', topic.get_help_topic())
 
561
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
 
562
        topic = plugin.ModuleHelpTopic(mod)
 
563
        self.assertEqual('foo_bar', topic.get_help_topic())
 
564
 
 
565
 
 
566
class TestLoadFromPath(tests.TestCaseInTempDir):
 
567
 
 
568
    def setUp(self):
 
569
        super(TestLoadFromPath, self).setUp()
 
570
        # Change bzrlib.plugin to think no plugins have been loaded yet.
 
571
        self.overrideAttr(bzrlib.plugins, '__path__', [])
 
572
        self.overrideAttr(plugin, '_loaded', False)
 
573
 
 
574
        # Monkey-patch load_from_path to stop it from actually loading anything.
 
575
        self.overrideAttr(plugin, 'load_from_path', lambda dirs: None)
 
576
 
 
577
    def test_set_plugins_path_with_args(self):
 
578
        plugin.set_plugins_path(['a', 'b'])
 
579
        self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
 
580
 
 
581
    def test_set_plugins_path_defaults(self):
 
582
        plugin.set_plugins_path()
 
583
        self.assertEqual(plugin.get_standard_plugins_path(),
 
584
                         bzrlib.plugins.__path__)
 
585
 
 
586
    def test_get_standard_plugins_path(self):
 
587
        path = plugin.get_standard_plugins_path()
 
588
        for directory in path:
 
589
            self.assertNotContainsRe(directory, r'\\/$')
 
590
        try:
 
591
            from distutils.sysconfig import get_python_lib
 
592
        except ImportError:
 
593
            pass
 
594
        else:
 
595
            if sys.platform != 'win32':
 
596
                python_lib = get_python_lib()
 
597
                for directory in path:
 
598
                    if directory.startswith(python_lib):
 
599
                        break
 
600
                else:
 
601
                    self.fail('No path to global plugins')
 
602
 
 
603
    def test_get_standard_plugins_path_env(self):
 
604
        os.environ['BZR_PLUGIN_PATH'] = 'foo/'
 
605
        path = plugin.get_standard_plugins_path()
 
606
        for directory in path:
 
607
            self.assertNotContainsRe(directory, r'\\/$')
 
608
 
 
609
    def test_load_plugins(self):
 
610
        plugin.load_plugins(['.'])
 
611
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
612
        # subsequent loads are no-ops
 
613
        plugin.load_plugins(['foo'])
 
614
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
615
 
 
616
    def test_load_plugins_default(self):
 
617
        plugin.load_plugins()
 
618
        path = plugin.get_standard_plugins_path()
 
619
        self.assertEqual(path, bzrlib.plugins.__path__)
 
620
 
 
621
 
 
622
class TestEnvPluginPath(tests.TestCase):
 
623
 
 
624
    def setUp(self):
 
625
        super(TestEnvPluginPath, self).setUp()
 
626
        self.overrideAttr(plugin, 'DEFAULT_PLUGIN_PATH', None)
 
627
 
 
628
        self.user = plugin.get_user_plugin_path()
 
629
        self.site = plugin.get_site_plugin_path()
 
630
        self.core = plugin.get_core_plugin_path()
 
631
 
 
632
    def _list2paths(self, *args):
 
633
        paths = []
 
634
        for p in args:
 
635
            plugin._append_new_path(paths, p)
 
636
        return paths
 
637
 
 
638
    def _set_path(self, *args):
 
639
        path = os.pathsep.join(self._list2paths(*args))
 
640
        osutils.set_or_unset_env('BZR_PLUGIN_PATH', path)
 
641
 
 
642
    def check_path(self, expected_dirs, setting_dirs):
 
643
        if setting_dirs:
 
644
            self._set_path(*setting_dirs)
 
645
        actual = plugin.get_standard_plugins_path()
 
646
        self.assertEquals(self._list2paths(*expected_dirs), actual)
 
647
 
 
648
    def test_default(self):
 
649
        self.check_path([self.user, self.core, self.site],
 
650
                        None)
 
651
 
 
652
    def test_adhoc_policy(self):
 
653
        self.check_path([self.user, self.core, self.site],
 
654
                        ['+user', '+core', '+site'])
 
655
 
 
656
    def test_fallback_policy(self):
 
657
        self.check_path([self.core, self.site, self.user],
 
658
                        ['+core', '+site', '+user'])
 
659
 
 
660
    def test_override_policy(self):
 
661
        self.check_path([self.user, self.site, self.core],
 
662
                        ['+user', '+site', '+core'])
 
663
 
 
664
    def test_disable_user(self):
 
665
        self.check_path([self.core, self.site], ['-user'])
 
666
 
 
667
    def test_disable_user_twice(self):
 
668
        # Ensures multiple removals don't left cruft
 
669
        self.check_path([self.core, self.site], ['-user', '-user'])
 
670
 
 
671
    def test_duplicates_are_removed(self):
 
672
        self.check_path([self.user, self.core, self.site],
 
673
                        ['+user', '+user'])
 
674
        # And only the first reference is kept (since the later references will
 
675
        # only produce '<plugin> already loaded' mutters)
 
676
        self.check_path([self.user, self.core, self.site],
 
677
                        ['+user', '+user', '+core',
 
678
                         '+user', '+site', '+site',
 
679
                         '+core'])
 
680
 
 
681
    def test_disable_overrides_disable(self):
 
682
        self.check_path([self.core, self.site], ['-user', '+user'])
 
683
 
 
684
    def test_disable_core(self):
 
685
        self.check_path([self.site], ['-core'])
 
686
        self.check_path([self.user, self.site], ['+user', '-core'])
 
687
 
 
688
    def test_disable_site(self):
 
689
        self.check_path([self.core], ['-site'])
 
690
        self.check_path([self.user, self.core], ['-site', '+user'])
 
691
 
 
692
    def test_override_site(self):
 
693
        self.check_path(['mysite', self.user, self.core],
 
694
                        ['mysite', '-site', '+user'])
 
695
        self.check_path(['mysite', self.core],
 
696
                        ['mysite', '-site'])
 
697
 
 
698
    def test_override_core(self):
 
699
        self.check_path(['mycore', self.user, self.site],
 
700
                        ['mycore', '-core', '+user', '+site'])
 
701
        self.check_path(['mycore', self.site],
 
702
                        ['mycore', '-core'])
 
703
 
 
704
    def test_my_plugin_only(self):
 
705
        self.check_path(['myplugin'], ['myplugin', '-user', '-core', '-site'])
 
706
 
 
707
    def test_my_plugin_first(self):
 
708
        self.check_path(['myplugin', self.core, self.site, self.user],
 
709
                        ['myplugin', '+core', '+site', '+user'])
 
710
 
 
711
    def test_bogus_references(self):
 
712
        self.check_path(['+foo', '-bar', self.core, self.site],
 
713
                        ['+foo', '-bar'])