~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/selftest/plugins.py

  • Committer: Robert Collins
  • Date: 2005-09-28 05:25:54 UTC
  • mfrom: (1185.1.42)
  • mto: (1092.2.18)
  • mto: This revision was merged to the branch mainline in revision 1397.
  • Revision ID: robertc@robertcollins.net-20050928052554-beb985505f77ea6a
update symlink branch to integration

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
45
 
class cmd_myplug(bzrlib.commands.Command):
46
 
    '''Just a simple test plugin.'''
47
 
    aliases = ['mplg']
48
 
    def run(self):
49
 
        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 test_plugin_with_bad_name_does_not_load(self):
197
 
        # Create badly-named plugin
198
 
        file('bzr-bad plugin-name..py', 'w').close()
199
 
 
200
 
        # Capture output
201
 
        stream = StringIO()
202
 
        handler = logging.StreamHandler(stream)
203
 
        log = logging.getLogger('bzr')
204
 
        log.addHandler(handler)
205
 
 
206
 
        bzrlib.plugin.load_from_dir('.')
207
 
 
208
 
        # Stop capturing output
209
 
        handler.flush()
210
 
        handler.close()
211
 
        log.removeHandler(handler)
212
 
 
213
 
        self.assertContainsRe(stream.getvalue(),
214
 
            r"Unable to load 'bzr-bad plugin-name\.' in '\.' as a plugin "
215
 
            "because the file path isn't a valid module name; try renaming "
216
 
            "it to 'bad_plugin_name_'\.")
217
 
 
218
 
        stream.close()
219
 
 
220
 
 
221
 
class TestPlugins(TestCaseInTempDir):
222
 
 
223
 
    def setup_plugin(self, source=""):
224
 
        # This test tests a new plugin appears in bzrlib.plugin.plugins().
225
 
        # check the plugin is not loaded already
226
 
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
227
 
        # write a plugin that _cannot_ fail to load.
228
 
        file('plugin.py', 'w').write(source + '\n')
229
 
        self.addCleanup(self.teardown_plugin)
230
 
        bzrlib.plugin.load_from_path(['.'])
231
 
    
232
 
    def teardown_plugin(self):
233
 
        # remove the plugin 'plugin'
234
 
        if 'bzrlib.plugins.plugin' in sys.modules:
235
 
            del sys.modules['bzrlib.plugins.plugin']
236
 
        if getattr(bzrlib.plugins, 'plugin', None):
237
 
            del bzrlib.plugins.plugin
238
 
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
239
 
 
240
 
    def test_plugin_appears_in_plugins(self):
241
 
        self.setup_plugin()
242
 
        self.failUnless('plugin' in bzrlib.plugin.plugins())
243
 
        self.failUnless(getattr(bzrlib.plugins, 'plugin', None))
244
 
        plugins = bzrlib.plugin.plugins()
245
 
        plugin = plugins['plugin']
246
 
        self.assertIsInstance(plugin, bzrlib.plugin.PlugIn)
247
 
        self.assertEqual(bzrlib.plugins.plugin, plugin.module)
248
 
 
249
 
    def test_trivial_plugin_get_path(self):
250
 
        self.setup_plugin()
251
 
        plugins = bzrlib.plugin.plugins()
252
 
        plugin = plugins['plugin']
253
 
        plugin_path = self.test_dir + '/plugin.py'
254
 
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
255
 
 
256
 
    def test_plugin_get_path_py_not_pyc(self):
257
 
        self.setup_plugin()         # after first import there will be plugin.pyc
258
 
        self.teardown_plugin()
259
 
        bzrlib.plugin.load_from_path(['.']) # import plugin.pyc
260
 
        plugins = bzrlib.plugin.plugins()
261
 
        plugin = plugins['plugin']
262
 
        plugin_path = self.test_dir + '/plugin.py'
263
 
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
264
 
 
265
 
    def test_plugin_get_path_pyc_only(self):
266
 
        self.setup_plugin()         # after first import there will be plugin.pyc
267
 
        self.teardown_plugin()
268
 
        os.unlink(self.test_dir + '/plugin.py')
269
 
        bzrlib.plugin.load_from_path(['.']) # import plugin.pyc
270
 
        plugins = bzrlib.plugin.plugins()
271
 
        plugin = plugins['plugin']
272
 
        if __debug__:
273
 
            plugin_path = self.test_dir + '/plugin.pyc'
274
 
        else:
275
 
            plugin_path = self.test_dir + '/plugin.pyo'
276
 
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
277
 
 
278
 
    def test_no_test_suite_gives_None_for_test_suite(self):
279
 
        self.setup_plugin()
280
 
        plugin = bzrlib.plugin.plugins()['plugin']
281
 
        self.assertEqual(None, plugin.test_suite())
282
 
 
283
 
    def test_test_suite_gives_test_suite_result(self):
284
 
        source = """def test_suite(): return 'foo'"""
285
 
        self.setup_plugin(source)
286
 
        plugin = bzrlib.plugin.plugins()['plugin']
287
 
        self.assertEqual('foo', plugin.test_suite())
288
 
 
289
 
    def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
290
 
        self.setup_plugin()
291
 
        loader = TestUtil.TestLoader()
292
 
        plugin = bzrlib.plugin.plugins()['plugin']
293
 
        self.assertEqual(None, plugin.load_plugin_tests(loader))
294
 
 
295
 
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
296
 
        source = """
297
 
def load_tests(standard_tests, module, loader):
298
 
    return 'foo'"""
299
 
        self.setup_plugin(source)
300
 
        loader = TestUtil.TestLoader()
301
 
        plugin = bzrlib.plugin.plugins()['plugin']
302
 
        self.assertEqual('foo', plugin.load_plugin_tests(loader))
303
 
 
304
 
    def test_no_version_info(self):
305
 
        self.setup_plugin()
306
 
        plugin = bzrlib.plugin.plugins()['plugin']
307
 
        self.assertEqual(None, plugin.version_info())
308
 
 
309
 
    def test_with_version_info(self):
310
 
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
311
 
        plugin = bzrlib.plugin.plugins()['plugin']
312
 
        self.assertEqual((1, 2, 3, 'dev', 4), plugin.version_info())
313
 
 
314
 
    def test_short_version_info_gets_padded(self):
315
 
        # the gtk plugin has version_info = (1,2,3) rather than the 5-tuple.
316
 
        # so we adapt it
317
 
        self.setup_plugin("version_info = (1, 2, 3)")
318
 
        plugin = bzrlib.plugin.plugins()['plugin']
319
 
        self.assertEqual((1, 2, 3, 'final', 0), plugin.version_info())
320
 
 
321
 
    def test_no_version_info___version__(self):
322
 
        self.setup_plugin()
323
 
        plugin = bzrlib.plugin.plugins()['plugin']
324
 
        self.assertEqual("unknown", plugin.__version__)
325
 
 
326
 
    def test___version__with_version_info(self):
327
 
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
328
 
        plugin = bzrlib.plugin.plugins()['plugin']
329
 
        self.assertEqual("1.2.3dev4", plugin.__version__)
330
 
 
331
 
    def test_final__version__with_version_info(self):
332
 
        self.setup_plugin("version_info = (1, 2, 3, 'final', 4)")
333
 
        plugin = bzrlib.plugin.plugins()['plugin']
334
 
        self.assertEqual("1.2.3", plugin.__version__)
335
 
 
336
 
 
337
 
class TestPluginHelp(TestCaseInTempDir):
338
 
 
339
 
    def split_help_commands(self):
340
 
        help = {}
341
 
        current = None
342
 
        for line in self.run_bzr('help commands')[0].splitlines():
343
 
            if not line.startswith(' '):
344
 
                current = line.split()[0]
345
 
            help[current] = help.get(current, '') + line
346
 
 
347
 
        return help
348
 
 
349
 
    def test_plugin_help_builtins_unaffected(self):
350
 
        # Check we don't get false positives
351
 
        help_commands = self.split_help_commands()
352
 
        for cmd_name in bzrlib.commands.builtin_command_names():
353
 
            if cmd_name in bzrlib.commands.plugin_command_names():
354
 
                continue
355
 
            try:
356
 
                help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
357
 
            except NotImplementedError:
358
 
                # some commands have no help
359
 
                pass
360
 
            else:
361
 
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
362
 
 
363
 
            if cmd_name in help_commands.keys():
364
 
                # some commands are hidden
365
 
                help = help_commands[cmd_name]
366
 
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
367
 
 
368
 
    def test_plugin_help_shows_plugin(self):
369
 
        # Create a test plugin
370
 
        os.mkdir('plugin_test')
371
 
        f = open(pathjoin('plugin_test', 'myplug.py'), 'w')
 
20
 
 
21
 
 
22
# **************************************************
 
23
# NOT RUN YET
 
24
# **************************************************
 
25
 
 
26
 
 
27
 
 
28
 
 
29
 
 
30
 
 
31
 
 
32
 
 
33
from bzrlib.selftest import TestCaseInTempDir
 
34
 
 
35
 
 
36
class PluginTest(TestCaseInTempDir):
 
37
    """Create an external plugin and test loading."""
 
38
    def test_plugin_loading(self):
 
39
        import os
 
40
        
 
41
        orig_help = self.backtick('bzr help commands') # No plugins yet
 
42
        os.mkdir('plugin_test')
 
43
        f = open(os.path.join('plugin_test', 'myplug.py'), 'wt')
372
44
        f.write(PLUGIN_TEXT)
373
45
        f.close()
374
46
 
375
 
        try:
376
 
            # Check its help
377
 
            bzrlib.plugin.load_from_path(['plugin_test'])
378
 
            bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
379
 
            help = self.run_bzr('help myplug')[0]
380
 
            self.assertContainsRe(help, 'plugin "myplug"')
381
 
            help = self.split_help_commands()['myplug']
382
 
            self.assertContainsRe(help, '\[myplug\]')
383
 
        finally:
384
 
            # unregister command
385
 
            if bzrlib.commands.plugin_cmds.get('myplug', None):
386
 
                del bzrlib.commands.plugin_cmds['myplug']
387
 
            # remove the plugin 'myplug'
388
 
            if getattr(bzrlib.plugins, 'myplug', None):
389
 
                delattr(bzrlib.plugins, 'myplug')
390
 
 
391
 
 
392
 
class TestPluginFromZip(TestCaseInTempDir):
393
 
 
394
 
    def make_zipped_plugin(self, zip_name, filename):
395
 
        z = zipfile.ZipFile(zip_name, 'w')
396
 
        z.writestr(filename, PLUGIN_TEXT)
397
 
        z.close()
398
 
 
399
 
    def check_plugin_load(self, zip_name, plugin_name):
400
 
        self.assertFalse(plugin_name in dir(bzrlib.plugins),
401
 
                         'Plugin already loaded')
402
 
        old_path = bzrlib.plugins.__path__
403
 
        try:
404
 
            # this is normally done by load_plugins -> set_plugins_path
405
 
            bzrlib.plugins.__path__ = [zip_name]
406
 
            self.applyDeprecated(one_three,
407
 
                bzrlib.plugin.load_from_zip, zip_name)
408
 
            self.assertTrue(plugin_name in dir(bzrlib.plugins),
409
 
                            'Plugin is not loaded')
410
 
        finally:
411
 
            # unregister plugin
412
 
            if getattr(bzrlib.plugins, plugin_name, None):
413
 
                delattr(bzrlib.plugins, plugin_name)
414
 
                del sys.modules['bzrlib.plugins.' + plugin_name]
415
 
            bzrlib.plugins.__path__ = old_path
416
 
 
417
 
    def test_load_module(self):
418
 
        self.make_zipped_plugin('./test.zip', 'ziplug.py')
419
 
        self.check_plugin_load('./test.zip', 'ziplug')
420
 
 
421
 
    def test_load_package(self):
422
 
        self.make_zipped_plugin('./test.zip', 'ziplug/__init__.py')
423
 
        self.check_plugin_load('./test.zip', 'ziplug')
424
 
 
425
 
 
426
 
class TestSetPluginsPath(TestCase):
427
 
    
428
 
    def test_set_plugins_path(self):
429
 
        """set_plugins_path should set the module __path__ correctly."""
430
 
        old_path = bzrlib.plugins.__path__
431
 
        try:
432
 
            bzrlib.plugins.__path__ = []
433
 
            expected_path = bzrlib.plugin.set_plugins_path()
434
 
            self.assertEqual(expected_path, bzrlib.plugins.__path__)
435
 
        finally:
436
 
            bzrlib.plugins.__path__ = old_path
437
 
 
438
 
    def test_set_plugins_path_with_trailing_slashes(self):
439
 
        """set_plugins_path should set the module __path__ based on
440
 
        BZR_PLUGIN_PATH."""
441
 
        old_path = bzrlib.plugins.__path__
442
 
        old_env = os.environ.get('BZR_PLUGIN_PATH')
443
 
        try:
444
 
            bzrlib.plugins.__path__ = []
445
 
            os.environ['BZR_PLUGIN_PATH'] = "first\\//\\" + os.pathsep + \
446
 
                "second/\\/\\/"
447
 
            bzrlib.plugin.set_plugins_path()
448
 
            expected_path = ['first', 'second',
449
 
                os.path.dirname(bzrlib.plugins.__file__)]
450
 
            self.assertEqual(expected_path,
451
 
                bzrlib.plugins.__path__[:len(expected_path)])
452
 
        finally:
453
 
            bzrlib.plugins.__path__ = old_path
454
 
            if old_env is not None:
455
 
                os.environ['BZR_PLUGIN_PATH'] = old_env
456
 
            else:
457
 
                del os.environ['BZR_PLUGIN_PATH']
458
 
 
459
 
 
460
 
class TestHelpIndex(tests.TestCase):
461
 
    """Tests for the PluginsHelpIndex class."""
462
 
 
463
 
    def test_default_constructable(self):
464
 
        index = plugin.PluginsHelpIndex()
465
 
 
466
 
    def test_get_topics_None(self):
467
 
        """Searching for None returns an empty list."""
468
 
        index = plugin.PluginsHelpIndex()
469
 
        self.assertEqual([], index.get_topics(None))
470
 
 
471
 
    def test_get_topics_for_plugin(self):
472
 
        """Searching for plugin name gets its docstring."""
473
 
        index = plugin.PluginsHelpIndex()
474
 
        # make a new plugin here for this test, even if we're run with
475
 
        # --no-plugins
476
 
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
477
 
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
478
 
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
479
 
        try:
480
 
            topics = index.get_topics('demo_module')
481
 
            self.assertEqual(1, len(topics))
482
 
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
483
 
            self.assertEqual(demo_module, topics[0].module)
484
 
        finally:
485
 
            del sys.modules['bzrlib.plugins.demo_module']
486
 
 
487
 
    def test_get_topics_no_topic(self):
488
 
        """Searching for something that is not a plugin returns []."""
489
 
        # test this by using a name that cannot be a plugin - its not
490
 
        # a valid python identifier.
491
 
        index = plugin.PluginsHelpIndex()
492
 
        self.assertEqual([], index.get_topics('nothing by this name'))
493
 
 
494
 
    def test_prefix(self):
495
 
        """PluginsHelpIndex has a prefix of 'plugins/'."""
496
 
        index = plugin.PluginsHelpIndex()
497
 
        self.assertEqual('plugins/', index.prefix)
498
 
 
499
 
    def test_get_plugin_topic_with_prefix(self):
500
 
        """Searching for plugins/demo_module returns help."""
501
 
        index = plugin.PluginsHelpIndex()
502
 
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
503
 
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
504
 
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
505
 
        try:
506
 
            topics = index.get_topics('plugins/demo_module')
507
 
            self.assertEqual(1, len(topics))
508
 
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
509
 
            self.assertEqual(demo_module, topics[0].module)
510
 
        finally:
511
 
            del sys.modules['bzrlib.plugins.demo_module']
512
 
 
513
 
 
514
 
class FakeModule(object):
515
 
    """A fake module to test with."""
516
 
 
517
 
    def __init__(self, doc, name):
518
 
        self.__doc__ = doc
519
 
        self.__name__ = name
520
 
 
521
 
 
522
 
class TestModuleHelpTopic(tests.TestCase):
523
 
    """Tests for the ModuleHelpTopic class."""
524
 
 
525
 
    def test_contruct(self):
526
 
        """Construction takes the module to document."""
527
 
        mod = FakeModule('foo', 'foo')
528
 
        topic = plugin.ModuleHelpTopic(mod)
529
 
        self.assertEqual(mod, topic.module)
530
 
 
531
 
    def test_get_help_text_None(self):
532
 
        """A ModuleHelpTopic returns the docstring for get_help_text."""
533
 
        mod = FakeModule(None, 'demo')
534
 
        topic = plugin.ModuleHelpTopic(mod)
535
 
        self.assertEqual("Plugin 'demo' has no docstring.\n",
536
 
            topic.get_help_text())
537
 
 
538
 
    def test_get_help_text_no_carriage_return(self):
539
 
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
540
 
        mod = FakeModule('one line of help', 'demo')
541
 
        topic = plugin.ModuleHelpTopic(mod)
542
 
        self.assertEqual("one line of help\n",
543
 
            topic.get_help_text())
544
 
 
545
 
    def test_get_help_text_carriage_return(self):
546
 
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
547
 
        mod = FakeModule('two lines of help\nand more\n', 'demo')
548
 
        topic = plugin.ModuleHelpTopic(mod)
549
 
        self.assertEqual("two lines of help\nand more\n",
550
 
            topic.get_help_text())
551
 
 
552
 
    def test_get_help_text_with_additional_see_also(self):
553
 
        mod = FakeModule('two lines of help\nand more', 'demo')
554
 
        topic = plugin.ModuleHelpTopic(mod)
555
 
        self.assertEqual("two lines of help\nand more\nSee also: bar, foo\n",
556
 
            topic.get_help_text(['foo', 'bar']))
557
 
 
558
 
    def test_get_help_topic(self):
559
 
        """The help topic for a plugin is its module name."""
560
 
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
561
 
        topic = plugin.ModuleHelpTopic(mod)
562
 
        self.assertEqual('demo', topic.get_help_topic())
563
 
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
564
 
        topic = plugin.ModuleHelpTopic(mod)
565
 
        self.assertEqual('foo_bar', topic.get_help_topic())
 
47
        newhelp = backtick('bzr help commands')
 
48
        assert newhelp.startswith('You have been overridden\n')
 
49
        # We added a line, but the rest should work
 
50
        assert newhelp[25:] == help
 
51
 
 
52
        assert backtick('bzr commit -m test') == "I'm sorry dave, you can't do that\n"
 
53
 
 
54
        shutil.rmtree('plugin_test')
 
55
 
 
56
 
 
57
 
 
58
 
 
59
#         PLUGIN_TEXT = \
 
60
#         """import bzrlib, bzrlib.commands
 
61
#         class cmd_myplug(bzrlib.commands.Command):
 
62
#             '''Just a simple test plugin.'''
 
63
#             aliases = ['mplg']
 
64
#             def run(self):
 
65
#                 print 'Hello from my plugin'
 
66
#         """
 
67
#         f.close()
 
68
 
 
69
#         os.environ['BZRPLUGINPATH'] = os.path.abspath('plugin_test')
 
70
#         help = backtick('bzr help commands')
 
71
#         assert help.find('myplug') != -1
 
72
#         assert help.find('Just a simple test plugin.') != -1
 
73
 
 
74
 
 
75
#         assert backtick('bzr myplug') == 'Hello from my plugin\n'
 
76
#         assert backtick('bzr mplg') == 'Hello from my plugin\n'
 
77
 
 
78
#         f = open(os.path.join('plugin_test', 'override.py'), 'wb')
 
79
#         f.write("""import bzrlib, bzrlib.commands
 
80
#     class cmd_commit(bzrlib.commands.cmd_commit):
 
81
#         '''Commit changes into a new revision.'''
 
82
#         def run(self, *args, **kwargs):
 
83
#             print "I'm sorry dave, you can't do that"
 
84
 
 
85
#     class cmd_help(bzrlib.commands.cmd_help):
 
86
#         '''Show help on a command or other topic.'''
 
87
#         def run(self, *args, **kwargs):
 
88
#             print "You have been overridden"
 
89
#             bzrlib.commands.cmd_help.run(self, *args, **kwargs)
 
90
 
 
91
#         """