~bzr-pqm/bzr/bzr.dev

2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
1
# Copyright (C) 2005, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
750 by Martin Pool
- stubbed-out tests for python plugins
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
750 by Martin Pool
- stubbed-out tests for python plugins
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
12
#
750 by Martin Pool
- stubbed-out tests for python plugins
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
750 by Martin Pool
- stubbed-out tests for python plugins
16
17
"""Tests for plugins"""
18
1185.16.83 by mbp at sourcefrog
- notes on testability of plugins
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
2967.4.5 by Daniel Watkins
Added test for badly-named plugins.
23
import logging
1185.16.83 by mbp at sourcefrog
- notes on testability of plugins
24
import os
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
25
from StringIO import StringIO
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
26
import sys
2215.4.1 by Alexander Belchenko
Bugfix #68124: Allow plugins import from zip archives.
27
import zipfile
750 by Martin Pool
- stubbed-out tests for python plugins
28
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
29
from bzrlib import (
30
    osutils,
31
    plugin,
32
    tests,
33
    )
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
34
import bzrlib.plugin
35
import bzrlib.plugins
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
36
import bzrlib.commands
37
import bzrlib.help
3302.8.11 by Vincent Ladeuil
Simplify plugin.load_tests.
38
from bzrlib.tests import (
39
    TestCase,
40
    TestCaseInTempDir,
41
    TestUtil,
42
    )
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
43
from bzrlib.osutils import pathjoin, abspath, normpath
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
44
1185.16.83 by mbp at sourcefrog
- notes on testability of plugins
45
1185.16.84 by mbp at sourcefrog
- fix indents
46
PLUGIN_TEXT = """\
47
import bzrlib.commands
48
class cmd_myplug(bzrlib.commands.Command):
49
    '''Just a simple test plugin.'''
50
    aliases = ['mplg']
51
    def run(self):
52
        print 'Hello from my plugin'
53
"""
1492 by Robert Collins
Support decoration of commands.
54
55
# TODO: Write a test for plugin decoration of commands.
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
56
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
57
class TestLoadingPlugins(TestCaseInTempDir):
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
58
59
    activeattributes = {}
60
61
    def test_plugins_with_the_same_name_are_not_loaded(self):
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
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.
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
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.
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
71
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
72
            [tempattribute] = []
73
        self.failUnless(tempattribute in self.activeattributes)
74
        # create two plugin directories
75
        os.mkdir('first')
76
        os.mkdir('second')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
77
        # write a plugin that will record when its loaded in the
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
78
        # tempattribute list.
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
79
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
80
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
81
82
        outfile = open(os.path.join('first', 'plugin.py'), 'w')
83
        try:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
84
            outfile.write(template % (tempattribute, 'first'))
85
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
86
        finally:
87
            outfile.close()
88
89
        outfile = open(os.path.join('second', 'plugin.py'), 'w')
90
        try:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
91
            outfile.write(template % (tempattribute, 'second'))
92
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
93
        finally:
94
            outfile.close()
95
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
96
        try:
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
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]
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
102
            if 'bzrlib.plugins.plugin' in sys.modules:
103
                del sys.modules['bzrlib.plugins.plugin']
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
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):
109
        # This test tests that having two plugins in different
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
113
        # for accessing in activeattributes. - we cannot give import parameters.
114
        tempattribute = "different-dirs"
115
        self.failIf(tempattribute in self.activeattributes)
116
        # set a place for the plugins to record their loading, and at the same
117
        # time validate that the location the plugins should record to is
118
        # valid and correct.
119
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
120
            [tempattribute] = []
121
        self.failUnless(tempattribute in self.activeattributes)
122
        # create two plugin directories
123
        os.mkdir('first')
124
        os.mkdir('second')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
125
        # write plugins that will record when they are loaded in the
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
126
        # tempattribute list.
127
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
128
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
129
130
        outfile = open(os.path.join('first', 'pluginone.py'), 'w')
131
        try:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
132
            outfile.write(template % (tempattribute, 'first'))
133
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
134
        finally:
135
            outfile.close()
136
137
        outfile = open(os.path.join('second', 'plugintwo.py'), 'w')
138
        try:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
139
            outfile.write(template % (tempattribute, 'second'))
140
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
141
        finally:
142
            outfile.close()
143
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
144
        oldpath = bzrlib.plugins.__path__
145
        try:
146
            bzrlib.plugins.__path__ = ['first', 'second']
147
            exec "import bzrlib.plugins.pluginone"
148
            self.assertEqual(['first'], self.activeattributes[tempattribute])
149
            exec "import bzrlib.plugins.plugintwo"
150
            self.assertEqual(['first', 'second'],
151
                self.activeattributes[tempattribute])
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
152
        finally:
153
            # remove the plugin 'plugin'
154
            del self.activeattributes[tempattribute]
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
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))
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
161
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
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.
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
165
        # check the plugin is not loaded already
166
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
167
        tempattribute = "trailing-slash"
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
168
        self.failIf(tempattribute in self.activeattributes)
2652.2.3 by Blake Winton
Understand the code and comments of the test, instead of just cargo-culting them.
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
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
171
        # valid and correct.
172
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
173
            [tempattribute] = []
174
        self.failUnless(tempattribute in self.activeattributes)
2652.2.3 by Blake Winton
Understand the code and comments of the test, instead of just cargo-culting them.
175
        # create a directory for the plugin
176
        os.mkdir('plugin_test')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
177
        # write a plugin that will record when its loaded in the
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
178
        # tempattribute list.
179
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
180
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
181
182
        outfile = open(os.path.join('plugin_test', 'ts_plugin.py'), 'w')
183
        try:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
184
            outfile.write(template % (tempattribute, 'plugin'))
2911.6.4 by Blake Winton
Fix test failures
185
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
186
        finally:
187
            outfile.close()
188
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
189
        try:
2652.2.3 by Blake Winton
Understand the code and comments of the test, instead of just cargo-culting them.
190
            bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
191
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
192
        finally:
193
            # remove the plugin 'plugin'
194
            del self.activeattributes[tempattribute]
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
195
            if getattr(bzrlib.plugins, 'ts_plugin', None):
196
                del bzrlib.plugins.ts_plugin
197
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
198
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
199
    def load_and_capture(self, name):
200
        """Load plugins from '.' capturing the output.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
201
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
202
        :param name: The name of the plugin.
203
        :return: A string with the log from the plugin loading call.
204
        """
2967.4.5 by Daniel Watkins
Added test for badly-named plugins.
205
        # Capture output
206
        stream = StringIO()
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
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()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
227
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
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,
3290.1.1 by James Westby
Strip "bzr_" from the start of the suggested plugin name.
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_'\.")
2967.4.5 by Daniel Watkins
Added test for badly-named plugins.
252
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
253
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
254
class TestPlugins(TestCaseInTempDir):
255
256
    def setup_plugin(self, source=""):
257
        # This test tests a new plugin appears in bzrlib.plugin.plugins().
258
        # check the plugin is not loaded already
259
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
260
        # write a plugin that _cannot_ fail to load.
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
261
        file('plugin.py', 'w').write(source + '\n')
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
262
        self.addCleanup(self.teardown_plugin)
263
        bzrlib.plugin.load_from_path(['.'])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
264
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
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
271
        self.failIf(getattr(bzrlib.plugins, 'plugin', None))
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'
2823.1.10 by Vincent Ladeuil
merge bzr.dev
287
        self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
288
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
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
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
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
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
322
    def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
323
        self.setup_plugin()
3302.8.11 by Vincent Ladeuil
Simplify plugin.load_tests.
324
        loader = TestUtil.TestLoader()
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
325
        plugin = bzrlib.plugin.plugins()['plugin']
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
326
        self.assertEqual(None, plugin.load_plugin_tests(loader))
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
327
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
328
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
329
        source = """
330
def load_tests(standard_tests, module, loader):
331
    return 'foo'"""
332
        self.setup_plugin(source)
3302.8.11 by Vincent Ladeuil
Simplify plugin.load_tests.
333
        loader = TestUtil.TestLoader()
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
334
        plugin = bzrlib.plugin.plugins()['plugin']
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
335
        self.assertEqual('foo', plugin.load_plugin_tests(loader))
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
336
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
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
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
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):
3777.6.5 by Marius Kruger
add 2 more tests for plugin version numbers
375
        self.setup_plugin("version_info = (1, 2)")
376
        plugin = bzrlib.plugin.plugins()['plugin']
377
        self.assertEqual("1.2", plugin.__version__)
378
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
379
    def test_1_2_3__version__with_version_info(self):
3777.6.5 by Marius Kruger
add 2 more tests for plugin version numbers
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):
3777.6.4 by Marius Kruger
fix tests
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__)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
393
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
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']
4634.50.6 by John Arbash Meinel
Handle a plugin fallback versioning issue.
397
        self.assertEqual("1.2.3dev4", plugin.__version__)
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
398
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
399
    def test_final__version__with_version_info(self):
3777.6.4 by Marius Kruger
fix tests
400
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
401
        plugin = bzrlib.plugin.plugins()['plugin']
402
        self.assertEqual("1.2.3", plugin.__version__)
403
4634.50.6 by John Arbash Meinel
Handle a plugin fallback versioning issue.
404
    def test_final_fallback__version__with_version_info(self):
405
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
406
        plugin = bzrlib.plugin.plugins()['plugin']
407
        self.assertEqual("1.2.3.final.2", plugin.__version__)
408
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
409
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
410
class TestPluginHelp(TestCaseInTempDir):
411
412
    def split_help_commands(self):
413
        help = {}
414
        current = None
3908.1.1 by Andrew Bennetts
Try harder to avoid loading plugins during the test suite.
415
        out, err = self.run_bzr('--no-plugins help commands')
416
        for line in out.splitlines():
2034.1.2 by Aaron Bentley
Fix testcase
417
            if not line.startswith(' '):
418
                current = line.split()[0]
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
419
            help[current] = help.get(current, '') + line
420
421
        return help
422
423
    def test_plugin_help_builtins_unaffected(self):
424
        # Check we don't get false positives
425
        help_commands = self.split_help_commands()
426
        for cmd_name in bzrlib.commands.builtin_command_names():
427
            if cmd_name in bzrlib.commands.plugin_command_names():
428
                continue
429
            try:
2432.1.12 by Robert Collins
Relocate command help onto Command.
430
                help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
431
            except NotImplementedError:
432
                # some commands have no help
433
                pass
434
            else:
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
435
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
436
2432.1.12 by Robert Collins
Relocate command help onto Command.
437
            if cmd_name in help_commands.keys():
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
438
                # some commands are hidden
439
                help = help_commands[cmd_name]
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
440
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
441
442
    def test_plugin_help_shows_plugin(self):
443
        # Create a test plugin
444
        os.mkdir('plugin_test')
445
        f = open(pathjoin('plugin_test', 'myplug.py'), 'w')
446
        f.write(PLUGIN_TEXT)
447
        f.close()
448
449
        try:
450
            # Check its help
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
451
            bzrlib.plugin.load_from_path(['plugin_test'])
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
452
            bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
2530.3.4 by Martin Pool
Deprecate run_bzr_captured in favour of just run_bzr
453
            help = self.run_bzr('help myplug')[0]
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
454
            self.assertContainsRe(help, 'plugin "myplug"')
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
455
            help = self.split_help_commands()['myplug']
2034.1.4 by Aaron Bentley
Change angle brackets to square brackets
456
            self.assertContainsRe(help, '\[myplug\]')
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
457
        finally:
2204.3.2 by Alexander Belchenko
cherrypicking: test_plugin_help_shows_plugin: fix cleanup after test
458
            # unregister command
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
459
            if 'myplug' in bzrlib.commands.plugin_cmds:
460
                bzrlib.commands.plugin_cmds.remove('myplug')
2204.3.2 by Alexander Belchenko
cherrypicking: test_plugin_help_shows_plugin: fix cleanup after test
461
            # remove the plugin 'myplug'
462
            if getattr(bzrlib.plugins, 'myplug', None):
463
                delattr(bzrlib.plugins, 'myplug')
2215.4.1 by Alexander Belchenko
Bugfix #68124: Allow plugins import from zip archives.
464
465
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
466
class TestHelpIndex(tests.TestCase):
467
    """Tests for the PluginsHelpIndex class."""
468
469
    def test_default_constructable(self):
470
        index = plugin.PluginsHelpIndex()
471
472
    def test_get_topics_None(self):
473
        """Searching for None returns an empty list."""
474
        index = plugin.PluginsHelpIndex()
475
        self.assertEqual([], index.get_topics(None))
476
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
477
    def test_get_topics_for_plugin(self):
478
        """Searching for plugin name gets its docstring."""
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
479
        index = plugin.PluginsHelpIndex()
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
480
        # make a new plugin here for this test, even if we're run with
481
        # --no-plugins
482
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
483
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
484
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
485
        try:
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
486
            topics = index.get_topics('demo_module')
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
487
            self.assertEqual(1, len(topics))
488
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
489
            self.assertEqual(demo_module, topics[0].module)
490
        finally:
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
491
            del sys.modules['bzrlib.plugins.demo_module']
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
492
493
    def test_get_topics_no_topic(self):
494
        """Searching for something that is not a plugin returns []."""
495
        # test this by using a name that cannot be a plugin - its not
496
        # a valid python identifier.
497
        index = plugin.PluginsHelpIndex()
498
        self.assertEqual([], index.get_topics('nothing by this name'))
499
500
    def test_prefix(self):
501
        """PluginsHelpIndex has a prefix of 'plugins/'."""
502
        index = plugin.PluginsHelpIndex()
503
        self.assertEqual('plugins/', index.prefix)
504
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
505
    def test_get_plugin_topic_with_prefix(self):
506
        """Searching for plugins/demo_module returns help."""
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
507
        index = plugin.PluginsHelpIndex()
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
508
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
509
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
510
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
511
        try:
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
512
            topics = index.get_topics('plugins/demo_module')
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
513
            self.assertEqual(1, len(topics))
514
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
515
            self.assertEqual(demo_module, topics[0].module)
516
        finally:
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
517
            del sys.modules['bzrlib.plugins.demo_module']
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
518
519
520
class FakeModule(object):
521
    """A fake module to test with."""
522
523
    def __init__(self, doc, name):
524
        self.__doc__ = doc
525
        self.__name__ = name
526
527
528
class TestModuleHelpTopic(tests.TestCase):
529
    """Tests for the ModuleHelpTopic class."""
530
531
    def test_contruct(self):
532
        """Construction takes the module to document."""
533
        mod = FakeModule('foo', 'foo')
534
        topic = plugin.ModuleHelpTopic(mod)
535
        self.assertEqual(mod, topic.module)
536
537
    def test_get_help_text_None(self):
538
        """A ModuleHelpTopic returns the docstring for get_help_text."""
539
        mod = FakeModule(None, 'demo')
540
        topic = plugin.ModuleHelpTopic(mod)
541
        self.assertEqual("Plugin 'demo' has no docstring.\n",
542
            topic.get_help_text())
543
544
    def test_get_help_text_no_carriage_return(self):
545
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
546
        mod = FakeModule('one line of help', 'demo')
547
        topic = plugin.ModuleHelpTopic(mod)
548
        self.assertEqual("one line of help\n",
549
            topic.get_help_text())
550
551
    def test_get_help_text_carriage_return(self):
552
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
553
        mod = FakeModule('two lines of help\nand more\n', 'demo')
554
        topic = plugin.ModuleHelpTopic(mod)
555
        self.assertEqual("two lines of help\nand more\n",
556
            topic.get_help_text())
557
558
    def test_get_help_text_with_additional_see_also(self):
559
        mod = FakeModule('two lines of help\nand more', 'demo')
560
        topic = plugin.ModuleHelpTopic(mod)
561
        self.assertEqual("two lines of help\nand more\nSee also: bar, foo\n",
562
            topic.get_help_text(['foo', 'bar']))
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
563
564
    def test_get_help_topic(self):
565
        """The help topic for a plugin is its module name."""
2432.1.30 by Robert Collins
Fix the ModuleHelpTopic get_help_topic to be tested with closer to real world data and strip the bzrlib.plugins. prefix from the name.
566
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
567
        topic = plugin.ModuleHelpTopic(mod)
568
        self.assertEqual('demo', topic.get_help_topic())
2432.1.30 by Robert Collins
Fix the ModuleHelpTopic get_help_topic to be tested with closer to real world data and strip the bzrlib.plugins. prefix from the name.
569
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
570
        topic = plugin.ModuleHelpTopic(mod)
571
        self.assertEqual('foo_bar', topic.get_help_topic())
3835.2.7 by Aaron Bentley
Add tests for plugins
572
573
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
574
class TestLoadFromPath(tests.TestCaseInTempDir):
575
576
    def setUp(self):
577
        super(TestLoadFromPath, self).setUp()
578
        # Change bzrlib.plugin to think no plugins have been loaded yet.
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
579
        self.overrideAttr(bzrlib.plugins, '__path__', [])
580
        self.overrideAttr(plugin, '_loaded', False)
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
581
582
        # Monkey-patch load_from_path to stop it from actually loading anything.
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
583
        self.overrideAttr(plugin, 'load_from_path', lambda dirs: None)
3835.2.7 by Aaron Bentley
Add tests for plugins
584
585
    def test_set_plugins_path_with_args(self):
586
        plugin.set_plugins_path(['a', 'b'])
587
        self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
588
589
    def test_set_plugins_path_defaults(self):
590
        plugin.set_plugins_path()
591
        self.assertEqual(plugin.get_standard_plugins_path(),
592
                         bzrlib.plugins.__path__)
593
594
    def test_get_standard_plugins_path(self):
595
        path = plugin.get_standard_plugins_path()
596
        for directory in path:
4412.2.1 by Vincent Ladeuil
Fix some OSX test regressions (well actual test bugs indeed).
597
            self.assertNotContainsRe(directory, r'\\/$')
3835.2.7 by Aaron Bentley
Add tests for plugins
598
        try:
599
            from distutils.sysconfig import get_python_lib
600
        except ImportError:
601
            pass
602
        else:
603
            if sys.platform != 'win32':
604
                python_lib = get_python_lib()
605
                for directory in path:
606
                    if directory.startswith(python_lib):
607
                        break
608
                else:
609
                    self.fail('No path to global plugins')
610
611
    def test_get_standard_plugins_path_env(self):
612
        os.environ['BZR_PLUGIN_PATH'] = 'foo/'
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
613
        path = plugin.get_standard_plugins_path()
614
        for directory in path:
615
            self.assertNotContainsRe(directory, r'\\/$')
3835.2.7 by Aaron Bentley
Add tests for plugins
616
617
    def test_load_plugins(self):
618
        plugin.load_plugins(['.'])
619
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
620
        # subsequent loads are no-ops
621
        plugin.load_plugins(['foo'])
622
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
623
624
    def test_load_plugins_default(self):
625
        plugin.load_plugins()
626
        path = plugin.get_standard_plugins_path()
627
        self.assertEqual(path, bzrlib.plugins.__path__)
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
628
629
630
class TestEnvPluginPath(tests.TestCaseInTempDir):
631
632
    def setUp(self):
633
        super(TestEnvPluginPath, self).setUp()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
634
        self.overrideAttr(plugin, 'DEFAULT_PLUGIN_PATH', None)
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
635
636
        self.user = plugin.get_user_plugin_path()
637
        self.site = plugin.get_site_plugin_path()
638
        self.core = plugin.get_core_plugin_path()
639
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
640
    def _list2paths(self, *args):
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
641
        paths = []
642
        for p in args:
643
            plugin._append_new_path(paths, p)
644
        return paths
645
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
646
    def _set_path(self, *args):
647
        path = os.pathsep.join(self._list2paths(*args))
648
        osutils.set_or_unset_env('BZR_PLUGIN_PATH', path)
649
650
    def check_path(self, expected_dirs, setting_dirs):
651
        if setting_dirs:
652
            self._set_path(*setting_dirs)
653
        actual = plugin.get_standard_plugins_path()
654
        self.assertEquals(self._list2paths(*expected_dirs), actual)
655
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
656
    def test_default(self):
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
657
        self.check_path([self.user, self.core, self.site],
658
                        None)
659
660
    def test_adhoc_policy(self):
661
        self.check_path([self.user, self.core, self.site],
662
                        ['+user', '+core', '+site'])
663
664
    def test_fallback_policy(self):
665
        self.check_path([self.core, self.site, self.user],
666
                        ['+core', '+site', '+user'])
667
668
    def test_override_policy(self):
669
        self.check_path([self.user, self.site, self.core],
670
                        ['+user', '+site', '+core'])
671
672
    def test_disable_user(self):
673
        self.check_path([self.core, self.site], ['-user'])
674
675
    def test_disable_user_twice(self):
676
        # Ensures multiple removals don't left cruft
677
        self.check_path([self.core, self.site], ['-user', '-user'])
678
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
679
    def test_duplicates_are_removed(self):
680
        self.check_path([self.user, self.core, self.site],
681
                        ['+user', '+user'])
682
        # And only the first reference is kept (since the later references will
683
        # onnly produce <plugin> already loaded mutters)
684
        self.check_path([self.user, self.core, self.site],
685
                        ['+user', '+user', '+core',
686
                         '+user', '+site', '+site',
687
                         '+core'])
688
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
689
    def test_disable_overrides_disable(self):
690
        self.check_path([self.core, self.site], ['-user', '+user'])
691
692
    def test_disable_core(self):
4628.2.3 by Vincent Ladeuil
Update doc and add NEWS entry.
693
        self.check_path([self.site], ['-core'])
694
        self.check_path([self.user, self.site], ['+user', '-core'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
695
696
    def test_disable_site(self):
4628.2.3 by Vincent Ladeuil
Update doc and add NEWS entry.
697
        self.check_path([self.core], ['-site'])
698
        self.check_path([self.user, self.core], ['-site', '+user'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
699
700
    def test_override_site(self):
4628.2.3 by Vincent Ladeuil
Update doc and add NEWS entry.
701
        self.check_path(['mysite', self.user, self.core],
702
                        ['mysite', '-site', '+user'])
703
        self.check_path(['mysite', self.core],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
704
                        ['mysite', '-site'])
705
706
    def test_override_core(self):
4628.2.3 by Vincent Ladeuil
Update doc and add NEWS entry.
707
        self.check_path(['mycore', self.user, self.site],
708
                        ['mycore', '-core', '+user', '+site'])
709
        self.check_path(['mycore', self.site],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
710
                        ['mycore', '-core'])
711
712
    def test_my_plugin_only(self):
713
        self.check_path(['myplugin'], ['myplugin', '-user', '-core', '-site'])
714
715
    def test_my_plugin_first(self):
716
        self.check_path(['myplugin', self.core, self.site, self.user],
717
                        ['myplugin', '+core', '+site', '+user'])
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
718
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
719
    def test_bogus_references(self):
720
        self.check_path(['+foo', '-bar', self.core, self.site],
721
                        ['+foo', '-bar'])