~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_plugins.py

  • Committer: John Arbash Meinel
  • Date: 2009-10-02 20:32:50 UTC
  • mto: (4679.6.1 2.1-export-c-api)
  • mto: This revision was merged to the branch mainline in revision 4735.
  • Revision ID: john@arbash-meinel.com-20091002203250-q6iv6o2mwjqp4g53
Add __iter__ support.

Show diffs side-by-side

added added

removed removed

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