/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/selftest/plugins.py

  • Committer: Martin Pool
  • Date: 2005-08-04 22:04:40 UTC
  • Revision ID: mbp@sourcefrog.net-20050804220440-99562df8151d1ac5
- add pending merge from aaron

Show diffs side-by-side

added added

removed removed

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