/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/test_plugins.py

  • Committer: Jelmer Vernooij
  • Date: 2017-08-07 11:49:46 UTC
  • mto: (6747.3.4 avoid-set-revid-3)
  • mto: This revision was merged to the branch mainline in revision 6750.
  • Revision ID: jelmer@jelmer.uk-20170807114946-luclmxuawyzhpiot
Avoid setting revision_ids.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2012, 2016 Canonical Ltd, 2017 Breezy developers
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for plugins"""
 
18
 
 
19
import imp
 
20
import importlib
 
21
import logging
 
22
import os
 
23
import sys
 
24
 
 
25
import breezy
 
26
from .. import (
 
27
    errors,
 
28
    osutils,
 
29
    plugin,
 
30
    tests,
 
31
    trace,
 
32
    )
 
33
from ..sixish import (
 
34
    PY3,
 
35
    StringIO,
 
36
    viewkeys,
 
37
    )
 
38
 
 
39
 
 
40
# TODO: Write a test for plugin decoration of commands.
 
41
 
 
42
invalidate_caches = getattr(importlib, "invalidate_caches", lambda: None)
 
43
 
 
44
 
 
45
class BaseTestPlugins(tests.TestCaseInTempDir):
 
46
    """TestCase that isolates plugin imports and cleans up on completion."""
 
47
 
 
48
    def setUp(self):
 
49
        super(BaseTestPlugins, self).setUp()
 
50
        self.module_name = "breezy.testingplugins"
 
51
        self.module_prefix = self.module_name + "."
 
52
        self.module = imp.new_module(self.module_name)
 
53
 
 
54
        self.overrideAttr(plugin, "_MODULE_PREFIX", self.module_prefix)
 
55
        self.overrideAttr(breezy, "testingplugins", self.module)
 
56
 
 
57
        sys.modules[self.module_name] = self.module
 
58
        self.addCleanup(self._unregister_all)
 
59
        self.addCleanup(self._unregister_finder)
 
60
 
 
61
        invalidate_caches()
 
62
 
 
63
    def reset(self):
 
64
        """Remove all global testing state and clean up module."""
 
65
        # GZ 2017-06-02: Ideally don't do this, write new test or generate
 
66
        # bytecode by other mechanism.
 
67
        self.log("resetting plugin testing context")
 
68
        self._unregister_all()
 
69
        self._unregister_finder()
 
70
        sys.modules[self.module_name] = self.module
 
71
        for name in list(self.module.__dict__):
 
72
            if name[:2] != '__':
 
73
                delattr(self.module, name)
 
74
        invalidate_caches()
 
75
        self.plugins = None
 
76
 
 
77
    def update_module_paths(self, paths):
 
78
        paths = plugin.extend_path(paths, self.module_name)
 
79
        self.module.__path__ = paths
 
80
        self.log("using %r", paths)
 
81
        return paths
 
82
 
 
83
    def load_with_paths(self, paths):
 
84
        self.log("loading plugins!")
 
85
        plugin.load_plugins(self.update_module_paths(paths), state=self)
 
86
 
 
87
    def create_plugin(self, name, source=None, dir='.', file_name=None):
 
88
        if source is None:
 
89
            source = '''\
 
90
"""This is the doc for %s"""
 
91
''' % (name)
 
92
        if file_name is None:
 
93
            file_name = name + '.py'
 
94
        # 'source' must not fail to load
 
95
        path = osutils.pathjoin(dir, file_name)
 
96
        with open(path, 'w') as f:
 
97
            f.write(source + '\n')
 
98
 
 
99
    def create_plugin_package(self, name, dir=None, source=None):
 
100
        if dir is None:
 
101
            dir = name
 
102
        if source is None:
 
103
            source = '''\
 
104
"""This is the doc for %s"""
 
105
dir_source = '%s'
 
106
''' % (name, dir)
 
107
        os.makedirs(dir)
 
108
        self.create_plugin(name, source, dir,
 
109
                           file_name='__init__.py')
 
110
 
 
111
    def promote_cache(self, directory):
 
112
        """Move bytecode files out of __pycache__ in given directory."""
 
113
        cache_dir = os.path.join(directory, '__pycache__')
 
114
        if os.path.isdir(cache_dir):
 
115
            for name in os.listdir(cache_dir):
 
116
                magicless_name = '.'.join(name.split('.')[0::name.count('.')])
 
117
                rel = osutils.relpath(self.test_dir, cache_dir)
 
118
                self.log("moving %s in %s to %s", name, rel, magicless_name)
 
119
                os.rename(os.path.join(cache_dir, name),
 
120
                    os.path.join(directory, magicless_name))
 
121
 
 
122
    def _unregister_finder(self):
 
123
        """Removes any test copies of _PluginsAtFinder from sys.meta_path."""
 
124
        idx = len(sys.meta_path)
 
125
        while idx:
 
126
            idx -= 1
 
127
            finder = sys.meta_path[idx]
 
128
            if getattr(finder, "prefix", "") == self.module_prefix:
 
129
                self.log("removed %r from sys.meta_path", finder)
 
130
                sys.meta_path.pop(idx)
 
131
 
 
132
    def _unregister_all(self):
 
133
        """Remove all plugins in the test namespace from sys.modules."""
 
134
        for name in list(sys.modules):
 
135
            if name.startswith(self.module_prefix) or name == self.module_name:
 
136
                self.log("removed %s from sys.modules", name)
 
137
                del sys.modules[name]
 
138
 
 
139
    def assertPluginModules(self, plugin_dict):
 
140
        self.assertEqual(
 
141
            dict((k[len(self.module_prefix):], sys.modules[k])
 
142
                for k in sys.modules if k.startswith(self.module_prefix)),
 
143
            plugin_dict)
 
144
 
 
145
    def assertPluginUnknown(self, name):
 
146
        self.assertTrue(getattr(self.module, name, None) is None)
 
147
        self.assertFalse(self.module_prefix + name in sys.modules)
 
148
 
 
149
    def assertPluginKnown(self, name):
 
150
        self.assertTrue(getattr(self.module, name, None) is not None)
 
151
        self.assertTrue(self.module_prefix + name in sys.modules)
 
152
 
 
153
 
 
154
class TestLoadingPlugins(BaseTestPlugins):
 
155
 
 
156
    activeattributes = {}
 
157
 
 
158
    def test_plugins_with_the_same_name_are_not_loaded(self):
 
159
        # This test tests that having two plugins in different directories does
 
160
        # not result in both being loaded when they have the same name.  get a
 
161
        # file name we can use which is also a valid attribute for accessing in
 
162
        # activeattributes. - we cannot give import parameters.
 
163
        tempattribute = "0"
 
164
        self.assertFalse(tempattribute in self.activeattributes)
 
165
        # set a place for the plugins to record their loading, and at the same
 
166
        # time validate that the location the plugins should record to is
 
167
        # valid and correct.
 
168
        self.__class__.activeattributes [tempattribute] = []
 
169
        self.assertTrue(tempattribute in self.activeattributes)
 
170
        # create two plugin directories
 
171
        os.mkdir('first')
 
172
        os.mkdir('second')
 
173
        # write a plugin that will record when its loaded in the
 
174
        # tempattribute list.
 
175
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
 
176
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
 
177
 
 
178
        with open(os.path.join('first', 'plugin.py'), 'w') as outfile:
 
179
            outfile.write(template % (tempattribute, 'first'))
 
180
            outfile.write('\n')
 
181
 
 
182
        with open(os.path.join('second', 'plugin.py'), 'w') as outfile:
 
183
            outfile.write(template % (tempattribute, 'second'))
 
184
            outfile.write('\n')
 
185
 
 
186
        try:
 
187
            self.load_with_paths(['first', 'second'])
 
188
            self.assertEqual(['first'], self.activeattributes[tempattribute])
 
189
        finally:
 
190
            del self.activeattributes[tempattribute]
 
191
 
 
192
    def test_plugins_from_different_dirs_can_demand_load(self):
 
193
        self.assertFalse('breezy.plugins.pluginone' in sys.modules)
 
194
        self.assertFalse('breezy.plugins.plugintwo' in sys.modules)
 
195
        # This test tests that having two plugins in different
 
196
        # directories with different names allows them both to be loaded, when
 
197
        # we do a direct import statement.
 
198
        # Determine a file name we can use which is also a valid attribute
 
199
        # for accessing in activeattributes. - we cannot give import parameters.
 
200
        tempattribute = "different-dirs"
 
201
        self.assertFalse(tempattribute in self.activeattributes)
 
202
        # set a place for the plugins to record their loading, and at the same
 
203
        # time validate that the location the plugins should record to is
 
204
        # valid and correct.
 
205
        breezy.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
206
            [tempattribute] = []
 
207
        self.assertTrue(tempattribute in self.activeattributes)
 
208
        # create two plugin directories
 
209
        os.mkdir('first')
 
210
        os.mkdir('second')
 
211
        # write plugins that will record when they are loaded in the
 
212
        # tempattribute list.
 
213
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
 
214
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
 
215
 
 
216
        with open(os.path.join('first', 'pluginone.py'), 'w') as outfile:
 
217
            outfile.write(template % (tempattribute, 'first'))
 
218
            outfile.write('\n')
 
219
 
 
220
        with open(os.path.join('second', 'plugintwo.py'), 'w') as outfile:
 
221
            outfile.write(template % (tempattribute, 'second'))
 
222
            outfile.write('\n')
 
223
 
 
224
        try:
 
225
            self.assertPluginUnknown('pluginone')
 
226
            self.assertPluginUnknown('plugintwo')
 
227
            self.update_module_paths(['first', 'second'])
 
228
            exec("import %spluginone" % self.module_prefix)
 
229
            self.assertEqual(['first'], self.activeattributes[tempattribute])
 
230
            exec("import %splugintwo" % self.module_prefix)
 
231
            self.assertEqual(['first', 'second'],
 
232
                self.activeattributes[tempattribute])
 
233
        finally:
 
234
            del self.activeattributes[tempattribute]
 
235
 
 
236
    def test_plugins_can_load_from_directory_with_trailing_slash(self):
 
237
        # This test tests that a plugin can load from a directory when the
 
238
        # directory in the path has a trailing slash.
 
239
        # check the plugin is not loaded already
 
240
        self.assertPluginUnknown('ts_plugin')
 
241
        tempattribute = "trailing-slash"
 
242
        self.assertFalse(tempattribute in self.activeattributes)
 
243
        # set a place for the plugin to record its loading, and at the same
 
244
        # time validate that the location the plugin should record to is
 
245
        # valid and correct.
 
246
        breezy.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
247
            [tempattribute] = []
 
248
        self.assertTrue(tempattribute in self.activeattributes)
 
249
        # create a directory for the plugin
 
250
        os.mkdir('plugin_test')
 
251
        # write a plugin that will record when its loaded in the
 
252
        # tempattribute list.
 
253
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
 
254
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
 
255
 
 
256
        with open(os.path.join('plugin_test', 'ts_plugin.py'), 'w') as outfile:
 
257
            outfile.write(template % (tempattribute, 'plugin'))
 
258
            outfile.write('\n')
 
259
 
 
260
        try:
 
261
            self.load_with_paths(['plugin_test'+os.sep])
 
262
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
 
263
            self.assertPluginKnown('ts_plugin')
 
264
        finally:
 
265
            del self.activeattributes[tempattribute]
 
266
 
 
267
    def load_and_capture(self, name):
 
268
        """Load plugins from '.' capturing the output.
 
269
 
 
270
        :param name: The name of the plugin.
 
271
        :return: A string with the log from the plugin loading call.
 
272
        """
 
273
        # Capture output
 
274
        stream = StringIO()
 
275
        try:
 
276
            handler = logging.StreamHandler(stream)
 
277
            log = logging.getLogger('brz')
 
278
            log.addHandler(handler)
 
279
            try:
 
280
                self.load_with_paths(['.'])
 
281
            finally:
 
282
                # Stop capturing output
 
283
                handler.flush()
 
284
                handler.close()
 
285
                log.removeHandler(handler)
 
286
            return stream.getvalue()
 
287
        finally:
 
288
            stream.close()
 
289
 
 
290
    def test_plugin_with_bad_api_version_reports(self):
 
291
        """Try loading a plugin that requests an unsupported api.
 
292
 
 
293
        Observe that it records the problem but doesn't complain on stderr.
 
294
 
 
295
        See https://bugs.launchpad.net/bzr/+bug/704195
 
296
        """
 
297
        name = 'wants100.py'
 
298
        with open(name, 'w') as f:
 
299
            f.write("import breezy\n"
 
300
                "from breezy.errors import IncompatibleVersion\n"
 
301
                "raise IncompatibleVersion(breezy, [(1, 0, 0)], (0, 0, 5))\n")
 
302
        log = self.load_and_capture(name)
 
303
        self.assertNotContainsRe(log,
 
304
            r"It supports breezy version")
 
305
        self.assertEqual({'wants100'}, viewkeys(self.plugin_warnings))
 
306
        self.assertContainsRe(
 
307
            self.plugin_warnings['wants100'][0],
 
308
            r"It supports breezy version")
 
309
 
 
310
    def test_plugin_with_bad_name_does_not_load(self):
 
311
        # The file name here invalid for a python module.
 
312
        name = 'brz-bad plugin-name..py'
 
313
        open(name, 'w').close()
 
314
        log = self.load_and_capture(name)
 
315
        self.assertContainsRe(log,
 
316
            r"Unable to load 'brz-bad plugin-name\.' in '\.' as a plugin "
 
317
            "because the file path isn't a valid module name; try renaming "
 
318
            "it to 'bad_plugin_name_'\.")
 
319
 
 
320
 
 
321
class TestPlugins(BaseTestPlugins):
 
322
 
 
323
    def setup_plugin(self, source=""):
 
324
        # This test tests a new plugin appears in breezy.plugin.plugins().
 
325
        # check the plugin is not loaded already
 
326
        self.assertPluginUnknown('plugin')
 
327
        # write a plugin that _cannot_ fail to load.
 
328
        with open('plugin.py', 'w') as f: f.write(source + '\n')
 
329
        self.load_with_paths(['.'])
 
330
 
 
331
    def test_plugin_appears_in_plugins(self):
 
332
        self.setup_plugin()
 
333
        self.assertPluginKnown('plugin')
 
334
        p = self.plugins['plugin']
 
335
        self.assertIsInstance(p, breezy.plugin.PlugIn)
 
336
        self.assertIs(p.module, sys.modules[self.module_prefix + 'plugin'])
 
337
 
 
338
    def test_trivial_plugin_get_path(self):
 
339
        self.setup_plugin()
 
340
        p = self.plugins['plugin']
 
341
        plugin_path = self.test_dir + '/plugin.py'
 
342
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
 
343
 
 
344
    def test_plugin_get_path_py_not_pyc(self):
 
345
        # first import creates plugin.pyc
 
346
        self.setup_plugin()
 
347
        self.promote_cache(self.test_dir)
 
348
        self.reset()
 
349
        self.load_with_paths(['.']) # import plugin.pyc
 
350
        p = plugin.plugins()['plugin']
 
351
        plugin_path = self.test_dir + '/plugin.py'
 
352
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
 
353
 
 
354
    def test_plugin_get_path_pyc_only(self):
 
355
        # first import creates plugin.pyc (or plugin.pyo depending on __debug__)
 
356
        self.setup_plugin()
 
357
        os.unlink(self.test_dir + '/plugin.py')
 
358
        self.promote_cache(self.test_dir)
 
359
        self.reset()
 
360
        self.load_with_paths(['.']) # import plugin.pyc (or .pyo)
 
361
        p = plugin.plugins()['plugin']
 
362
        plugin_path = self.test_dir + '/plugin' + plugin.COMPILED_EXT
 
363
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
 
364
 
 
365
    def test_no_test_suite_gives_None_for_test_suite(self):
 
366
        self.setup_plugin()
 
367
        p = plugin.plugins()['plugin']
 
368
        self.assertEqual(None, p.test_suite())
 
369
 
 
370
    def test_test_suite_gives_test_suite_result(self):
 
371
        source = """def test_suite(): return 'foo'"""
 
372
        self.setup_plugin(source)
 
373
        p = plugin.plugins()['plugin']
 
374
        self.assertEqual('foo', p.test_suite())
 
375
 
 
376
    def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
 
377
        self.setup_plugin()
 
378
        loader = tests.TestUtil.TestLoader()
 
379
        p = plugin.plugins()['plugin']
 
380
        self.assertEqual(None, p.load_plugin_tests(loader))
 
381
 
 
382
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
 
383
        source = """
 
384
def load_tests(loader, standard_tests, pattern):
 
385
    return 'foo'"""
 
386
        self.setup_plugin(source)
 
387
        loader = tests.TestUtil.TestLoader()
 
388
        p = plugin.plugins()['plugin']
 
389
        self.assertEqual('foo', p.load_plugin_tests(loader))
 
390
 
 
391
    def check_version_info(self, expected, source='', name='plugin'):
 
392
        self.setup_plugin(source)
 
393
        self.assertEqual(expected, plugin.plugins()[name].version_info())
 
394
 
 
395
    def test_no_version_info(self):
 
396
        self.check_version_info(None)
 
397
 
 
398
    def test_with_version_info(self):
 
399
        self.check_version_info((1, 2, 3, 'dev', 4),
 
400
                                "version_info = (1, 2, 3, 'dev', 4)")
 
401
 
 
402
    def test_short_version_info_gets_padded(self):
 
403
        # the gtk plugin has version_info = (1,2,3) rather than the 5-tuple.
 
404
        # so we adapt it
 
405
        self.check_version_info((1, 2, 3, 'final', 0),
 
406
                                "version_info = (1, 2, 3)")
 
407
 
 
408
    def check_version(self, expected, source=None, name='plugin'):
 
409
        self.setup_plugin(source)
 
410
        self.assertEqual(expected, plugins[name].__version__)
 
411
 
 
412
    def test_no_version_info___version__(self):
 
413
        self.setup_plugin()
 
414
        plugin = breezy.plugin.plugins()['plugin']
 
415
        self.assertEqual("unknown", plugin.__version__)
 
416
 
 
417
    def test_str__version__with_version_info(self):
 
418
        self.setup_plugin("version_info = '1.2.3'")
 
419
        plugin = breezy.plugin.plugins()['plugin']
 
420
        self.assertEqual("1.2.3", plugin.__version__)
 
421
 
 
422
    def test_noniterable__version__with_version_info(self):
 
423
        self.setup_plugin("version_info = (1)")
 
424
        plugin = breezy.plugin.plugins()['plugin']
 
425
        self.assertEqual("1", plugin.__version__)
 
426
 
 
427
    def test_1__version__with_version_info(self):
 
428
        self.setup_plugin("version_info = (1,)")
 
429
        plugin = breezy.plugin.plugins()['plugin']
 
430
        self.assertEqual("1", plugin.__version__)
 
431
 
 
432
    def test_1_2__version__with_version_info(self):
 
433
        self.setup_plugin("version_info = (1, 2)")
 
434
        plugin = breezy.plugin.plugins()['plugin']
 
435
        self.assertEqual("1.2", plugin.__version__)
 
436
 
 
437
    def test_1_2_3__version__with_version_info(self):
 
438
        self.setup_plugin("version_info = (1, 2, 3)")
 
439
        plugin = breezy.plugin.plugins()['plugin']
 
440
        self.assertEqual("1.2.3", plugin.__version__)
 
441
 
 
442
    def test_candidate__version__with_version_info(self):
 
443
        self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
 
444
        plugin = breezy.plugin.plugins()['plugin']
 
445
        self.assertEqual("1.2.3rc1", plugin.__version__)
 
446
 
 
447
    def test_dev__version__with_version_info(self):
 
448
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 0)")
 
449
        plugin = breezy.plugin.plugins()['plugin']
 
450
        self.assertEqual("1.2.3dev", plugin.__version__)
 
451
 
 
452
    def test_dev_fallback__version__with_version_info(self):
 
453
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
 
454
        plugin = breezy.plugin.plugins()['plugin']
 
455
        self.assertEqual("1.2.3dev4", plugin.__version__)
 
456
 
 
457
    def test_final__version__with_version_info(self):
 
458
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
 
459
        plugin = breezy.plugin.plugins()['plugin']
 
460
        self.assertEqual("1.2.3", plugin.__version__)
 
461
 
 
462
    def test_final_fallback__version__with_version_info(self):
 
463
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
 
464
        plugin = breezy.plugin.plugins()['plugin']
 
465
        self.assertEqual("1.2.3.2", plugin.__version__)
 
466
 
 
467
 
 
468
# GZ 2017-06-02: Move this suite to blackbox, as it's what it actually is.
 
469
class TestPluginHelp(BaseTestPlugins):
 
470
 
 
471
    def split_help_commands(self):
 
472
        help = {}
 
473
        current = None
 
474
        out, err = self.run_bzr('--no-plugins help commands')
 
475
        for line in out.splitlines():
 
476
            if not line.startswith(' '):
 
477
                current = line.split()[0]
 
478
            help[current] = help.get(current, '') + line
 
479
 
 
480
        return help
 
481
 
 
482
    def test_plugin_help_builtins_unaffected(self):
 
483
        # Check we don't get false positives
 
484
        help_commands = self.split_help_commands()
 
485
        for cmd_name in breezy.commands.builtin_command_names():
 
486
            if cmd_name in breezy.commands.plugin_command_names():
 
487
                continue
 
488
            try:
 
489
                help = breezy.commands.get_cmd_object(cmd_name).get_help_text()
 
490
            except NotImplementedError:
 
491
                # some commands have no help
 
492
                pass
 
493
            else:
 
494
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
 
495
 
 
496
            if cmd_name in help_commands:
 
497
                # some commands are hidden
 
498
                help = help_commands[cmd_name]
 
499
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
 
500
 
 
501
    def test_plugin_help_shows_plugin(self):
 
502
        # Create a test plugin
 
503
        os.mkdir('plugin_test')
 
504
        source = (
 
505
            "from breezy import commands\n"
 
506
            "class cmd_myplug(commands.Command):\n"
 
507
            "    __doc__ = '''Just a simple test plugin.'''\n"
 
508
            "    aliases = ['mplg']\n"
 
509
            "    def run(self):\n"
 
510
            "        print ('Hello from my plugin')\n"
 
511
        )
 
512
        self.create_plugin('myplug', source, 'plugin_test')
 
513
 
 
514
        # Check its help
 
515
        self.load_with_paths(['plugin_test'])
 
516
        myplug = self.plugins['myplug'].module
 
517
        breezy.commands.register_command(myplug.cmd_myplug)
 
518
        self.addCleanup(breezy.commands.plugin_cmds.remove, 'myplug')
 
519
        help = self.run_bzr('help myplug')[0]
 
520
        self.assertContainsRe(help, 'plugin "myplug"')
 
521
        help = self.split_help_commands()['myplug']
 
522
        self.assertContainsRe(help, '\[myplug\]')
 
523
 
 
524
 
 
525
class TestHelpIndex(tests.TestCase):
 
526
    """Tests for the PluginsHelpIndex class."""
 
527
 
 
528
    def test_default_constructable(self):
 
529
        index = plugin.PluginsHelpIndex()
 
530
 
 
531
    def test_get_topics_None(self):
 
532
        """Searching for None returns an empty list."""
 
533
        index = plugin.PluginsHelpIndex()
 
534
        self.assertEqual([], index.get_topics(None))
 
535
 
 
536
    def test_get_topics_for_plugin(self):
 
537
        """Searching for plugin name gets its docstring."""
 
538
        index = plugin.PluginsHelpIndex()
 
539
        # make a new plugin here for this test, even if we're run with
 
540
        # --no-plugins
 
541
        self.assertFalse('breezy.plugins.demo_module' in sys.modules)
 
542
        demo_module = FakeModule('', 'breezy.plugins.demo_module')
 
543
        sys.modules['breezy.plugins.demo_module'] = demo_module
 
544
        try:
 
545
            topics = index.get_topics('demo_module')
 
546
            self.assertEqual(1, len(topics))
 
547
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
 
548
            self.assertEqual(demo_module, topics[0].module)
 
549
        finally:
 
550
            del sys.modules['breezy.plugins.demo_module']
 
551
 
 
552
    def test_get_topics_no_topic(self):
 
553
        """Searching for something that is not a plugin returns []."""
 
554
        # test this by using a name that cannot be a plugin - its not
 
555
        # a valid python identifier.
 
556
        index = plugin.PluginsHelpIndex()
 
557
        self.assertEqual([], index.get_topics('nothing by this name'))
 
558
 
 
559
    def test_prefix(self):
 
560
        """PluginsHelpIndex has a prefix of 'plugins/'."""
 
561
        index = plugin.PluginsHelpIndex()
 
562
        self.assertEqual('plugins/', index.prefix)
 
563
 
 
564
    def test_get_plugin_topic_with_prefix(self):
 
565
        """Searching for plugins/demo_module returns help."""
 
566
        index = plugin.PluginsHelpIndex()
 
567
        self.assertFalse('breezy.plugins.demo_module' in sys.modules)
 
568
        demo_module = FakeModule('', 'breezy.plugins.demo_module')
 
569
        sys.modules['breezy.plugins.demo_module'] = demo_module
 
570
        try:
 
571
            topics = index.get_topics('plugins/demo_module')
 
572
            self.assertEqual(1, len(topics))
 
573
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
 
574
            self.assertEqual(demo_module, topics[0].module)
 
575
        finally:
 
576
            del sys.modules['breezy.plugins.demo_module']
 
577
 
 
578
 
 
579
class FakeModule(object):
 
580
    """A fake module to test with."""
 
581
 
 
582
    def __init__(self, doc, name):
 
583
        self.__doc__ = doc
 
584
        self.__name__ = name
 
585
 
 
586
 
 
587
class TestModuleHelpTopic(tests.TestCase):
 
588
    """Tests for the ModuleHelpTopic class."""
 
589
 
 
590
    def test_contruct(self):
 
591
        """Construction takes the module to document."""
 
592
        mod = FakeModule('foo', 'foo')
 
593
        topic = plugin.ModuleHelpTopic(mod)
 
594
        self.assertEqual(mod, topic.module)
 
595
 
 
596
    def test_get_help_text_None(self):
 
597
        """A ModuleHelpTopic returns the docstring for get_help_text."""
 
598
        mod = FakeModule(None, 'demo')
 
599
        topic = plugin.ModuleHelpTopic(mod)
 
600
        self.assertEqual("Plugin 'demo' has no docstring.\n",
 
601
            topic.get_help_text())
 
602
 
 
603
    def test_get_help_text_no_carriage_return(self):
 
604
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
 
605
        mod = FakeModule('one line of help', 'demo')
 
606
        topic = plugin.ModuleHelpTopic(mod)
 
607
        self.assertEqual("one line of help\n",
 
608
            topic.get_help_text())
 
609
 
 
610
    def test_get_help_text_carriage_return(self):
 
611
        """ModuleHelpTopic.get_help_text adds a \n if needed."""
 
612
        mod = FakeModule('two lines of help\nand more\n', 'demo')
 
613
        topic = plugin.ModuleHelpTopic(mod)
 
614
        self.assertEqual("two lines of help\nand more\n",
 
615
            topic.get_help_text())
 
616
 
 
617
    def test_get_help_text_with_additional_see_also(self):
 
618
        mod = FakeModule('two lines of help\nand more', 'demo')
 
619
        topic = plugin.ModuleHelpTopic(mod)
 
620
        self.assertEqual("two lines of help\nand more\n\n:See also: bar, foo\n",
 
621
                         topic.get_help_text(['foo', 'bar']))
 
622
 
 
623
    def test_get_help_topic(self):
 
624
        """The help topic for a plugin is its module name."""
 
625
        mod = FakeModule('two lines of help\nand more', 'breezy.plugins.demo')
 
626
        topic = plugin.ModuleHelpTopic(mod)
 
627
        self.assertEqual('demo', topic.get_help_topic())
 
628
        mod = FakeModule('two lines of help\nand more',
 
629
                         'breezy.plugins.foo_bar')
 
630
        topic = plugin.ModuleHelpTopic(mod)
 
631
        self.assertEqual('foo_bar', topic.get_help_topic())
 
632
 
 
633
 
 
634
class TestEnvPluginPath(tests.TestCase):
 
635
 
 
636
    user = "USER"
 
637
    core = "CORE"
 
638
    site = "SITE"
 
639
 
 
640
    def check_path(self, expected_dirs, setting_dirs):
 
641
        if setting_dirs is None:
 
642
            del os.environ['BRZ_PLUGIN_PATH']
 
643
        else:
 
644
            os.environ['BRZ_PLUGIN_PATH'] = os.pathsep.join(setting_dirs)
 
645
        actual = [(p if t == 'path' else t.upper())
 
646
            for p, t in plugin._env_plugin_path()]
 
647
        self.assertEqual(expected_dirs, actual)
 
648
 
 
649
    def test_default(self):
 
650
        self.check_path([self.user, self.core, self.site],
 
651
                        None)
 
652
 
 
653
    def test_adhoc_policy(self):
 
654
        self.check_path([self.user, self.core, self.site],
 
655
                        ['+user', '+core', '+site'])
 
656
 
 
657
    def test_fallback_policy(self):
 
658
        self.check_path([self.core, self.site, self.user],
 
659
                        ['+core', '+site', '+user'])
 
660
 
 
661
    def test_override_policy(self):
 
662
        self.check_path([self.user, self.site, self.core],
 
663
                        ['+user', '+site', '+core'])
 
664
 
 
665
    def test_disable_user(self):
 
666
        self.check_path([self.core, self.site], ['-user'])
 
667
 
 
668
    def test_disable_user_twice(self):
 
669
        # Ensures multiple removals don't left cruft
 
670
        self.check_path([self.core, self.site], ['-user', '-user'])
 
671
 
 
672
    def test_duplicates_are_removed(self):
 
673
        self.check_path([self.user, self.core, self.site],
 
674
                        ['+user', '+user'])
 
675
        # And only the first reference is kept (since the later references will
 
676
        # only produce '<plugin> already loaded' mutters)
 
677
        self.check_path([self.user, self.core, self.site],
 
678
                        ['+user', '+user', '+core',
 
679
                         '+user', '+site', '+site',
 
680
                         '+core'])
 
681
 
 
682
    def test_disable_overrides_enable(self):
 
683
        self.check_path([self.core, self.site], ['-user', '+user'])
 
684
 
 
685
    def test_disable_core(self):
 
686
        self.check_path([self.site], ['-core'])
 
687
        self.check_path([self.user, self.site], ['+user', '-core'])
 
688
 
 
689
    def test_disable_site(self):
 
690
        self.check_path([self.core], ['-site'])
 
691
        self.check_path([self.user, self.core], ['-site', '+user'])
 
692
 
 
693
    def test_override_site(self):
 
694
        self.check_path(['mysite', self.user, self.core],
 
695
                        ['mysite', '-site', '+user'])
 
696
        self.check_path(['mysite', self.core],
 
697
                        ['mysite', '-site'])
 
698
 
 
699
    def test_override_core(self):
 
700
        self.check_path(['mycore', self.user, self.site],
 
701
                        ['mycore', '-core', '+user', '+site'])
 
702
        self.check_path(['mycore', self.site],
 
703
                        ['mycore', '-core'])
 
704
 
 
705
    def test_my_plugin_only(self):
 
706
        self.check_path(['myplugin'], ['myplugin', '-user', '-core', '-site'])
 
707
 
 
708
    def test_my_plugin_first(self):
 
709
        self.check_path(['myplugin', self.core, self.site, self.user],
 
710
                        ['myplugin', '+core', '+site', '+user'])
 
711
 
 
712
    def test_bogus_references(self):
 
713
        self.check_path(['+foo', '-bar', self.core, self.site],
 
714
                        ['+foo', '-bar'])
 
715
 
 
716
 
 
717
class TestDisablePlugin(BaseTestPlugins):
 
718
 
 
719
    def test_cannot_import(self):
 
720
        self.create_plugin_package('works')
 
721
        self.create_plugin_package('fails')
 
722
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'fails')
 
723
        self.update_module_paths(["."])
 
724
        import breezy.testingplugins.works as works
 
725
        try:
 
726
            import breezy.testingplugins.fails as fails
 
727
        except ImportError:
 
728
            pass
 
729
        else:
 
730
            self.fail("Loaded blocked plugin: " + repr(fails))
 
731
        self.assertPluginModules({'fails': None, 'works': works})
 
732
 
 
733
    def test_partial_imports(self):
 
734
        self.create_plugin('good')
 
735
        self.create_plugin('bad')
 
736
        self.create_plugin_package('ugly')
 
737
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'bad:ugly')
 
738
        self.load_with_paths(['.'])
 
739
        self.assertEqual({'good'}, viewkeys(self.plugins))
 
740
        self.assertPluginModules({
 
741
            'good': self.plugins['good'].module,
 
742
            'bad': None,
 
743
            'ugly': None,
 
744
        })
 
745
        # Ensure there are no warnings about plugins not being imported as
 
746
        # the user has explictly requested they be disabled.
 
747
        self.assertNotContainsRe(self.get_log(), r"Unable to load plugin")
 
748
 
 
749
 
 
750
class TestEnvDisablePlugins(tests.TestCase):
 
751
 
 
752
    def _get_names(self, env_value):
 
753
        os.environ['BRZ_DISABLE_PLUGINS'] = env_value
 
754
        return plugin._env_disable_plugins()
 
755
 
 
756
    def test_unset(self):
 
757
        self.assertEqual([], plugin._env_disable_plugins())
 
758
 
 
759
    def test_empty(self):
 
760
        self.assertEqual([], self._get_names(''))
 
761
 
 
762
    def test_single(self):
 
763
        self.assertEqual(['single'], self._get_names('single'))
 
764
 
 
765
    def test_multi(self):
 
766
        expected = ['one', 'two']
 
767
        self.assertEqual(expected, self._get_names(os.pathsep.join(expected)))
 
768
 
 
769
    def test_mixed(self):
 
770
        value = os.pathsep.join(['valid', 'in-valid'])
 
771
        self.assertEqual(['valid'], self._get_names(value))
 
772
        self.assertContainsRe(self.get_log(),
 
773
            r"Invalid name 'in-valid' in BRZ_DISABLE_PLUGINS=" + repr(value))
 
774
 
 
775
 
 
776
class TestEnvPluginsAt(tests.TestCase):
 
777
 
 
778
    def _get_paths(self, env_value):
 
779
        os.environ['BRZ_PLUGINS_AT'] = env_value
 
780
        return plugin._env_plugins_at()
 
781
 
 
782
    def test_empty(self):
 
783
        self.assertEqual([], plugin._env_plugins_at())
 
784
        self.assertEqual([], self._get_paths(''))
 
785
 
 
786
    def test_one_path(self):
 
787
        self.assertEqual([('b', 'man')], self._get_paths('b@man'))
 
788
 
 
789
    def test_multiple(self):
 
790
        self.assertEqual(
 
791
            [('tools', 'bzr-tools'), ('p', 'play.py')],
 
792
            self._get_paths(os.pathsep.join(('tools@bzr-tools', 'p@play.py'))))
 
793
 
 
794
    def test_many_at(self):
 
795
        self.assertEqual(
 
796
            [('church', 'StMichael@Plea@Norwich')],
 
797
            self._get_paths('church@StMichael@Plea@Norwich'))
 
798
 
 
799
    def test_only_py(self):
 
800
        self.assertEqual([('test', './test.py')], self._get_paths('./test.py'))
 
801
 
 
802
    def test_only_package(self):
 
803
        self.assertEqual([('py', '/opt/b/py')], self._get_paths('/opt/b/py'))
 
804
 
 
805
    def test_bad_name(self):
 
806
        self.assertEqual([], self._get_paths('/usr/local/bzr-git'))
 
807
        self.assertContainsRe(self.get_log(),
 
808
            r"Invalid name 'bzr-git' in BRZ_PLUGINS_AT='/usr/local/bzr-git'")
 
809
 
 
810
 
 
811
class TestLoadPluginAt(BaseTestPlugins):
 
812
 
 
813
    def setUp(self):
 
814
        super(TestLoadPluginAt, self).setUp()
 
815
        # Create the same plugin in two directories
 
816
        self.create_plugin_package('test_foo', dir='non-standard-dir')
 
817
        # The "normal" directory, we use 'standard' instead of 'plugins' to
 
818
        # avoid depending on the precise naming.
 
819
        self.create_plugin_package('test_foo', dir='standard/test_foo')
 
820
 
 
821
    def assertTestFooLoadedFrom(self, path):
 
822
        self.assertPluginKnown('test_foo')
 
823
        self.assertDocstring('This is the doc for test_foo',
 
824
                             self.module.test_foo)
 
825
        self.assertEqual(path, self.module.test_foo.dir_source)
 
826
 
 
827
    def test_regular_load(self):
 
828
        self.load_with_paths(['standard'])
 
829
        self.assertTestFooLoadedFrom('standard/test_foo')
 
830
 
 
831
    def test_import(self):
 
832
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
833
        self.update_module_paths(['standard'])
 
834
        import breezy.testingplugins.test_foo
 
835
        self.assertTestFooLoadedFrom('non-standard-dir')
 
836
 
 
837
    def test_loading(self):
 
838
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
839
        self.load_with_paths(['standard'])
 
840
        self.assertTestFooLoadedFrom('non-standard-dir')
 
841
 
 
842
    def test_loading_other_name(self):
 
843
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
844
        os.rename('standard/test_foo', 'standard/test_bar')
 
845
        self.load_with_paths(['standard'])
 
846
        self.assertTestFooLoadedFrom('non-standard-dir')
 
847
 
 
848
    def test_compiled_loaded(self):
 
849
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
850
        self.load_with_paths(['standard'])
 
851
        self.assertTestFooLoadedFrom('non-standard-dir')
 
852
        self.assertIsSameRealPath('non-standard-dir/__init__.py',
 
853
                                  self.module.test_foo.__file__)
 
854
 
 
855
        # Try importing again now that the source has been compiled
 
856
        os.remove('non-standard-dir/__init__.py')
 
857
        self.promote_cache('non-standard-dir')
 
858
        self.reset()
 
859
        self.load_with_paths(['standard'])
 
860
        self.assertTestFooLoadedFrom('non-standard-dir')
 
861
        suffix = plugin.COMPILED_EXT
 
862
        self.assertIsSameRealPath('non-standard-dir/__init__' + suffix,
 
863
                                  self.module.test_foo.__file__)
 
864
 
 
865
    def test_submodule_loading(self):
 
866
        # We create an additional directory under the one for test_foo
 
867
        self.create_plugin_package('test_bar', dir='non-standard-dir/test_bar')
 
868
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
869
        self.update_module_paths(['standard'])
 
870
        import breezy.testingplugins.test_foo
 
871
        self.assertEqual(self.module_prefix + 'test_foo',
 
872
                         self.module.test_foo.__package__)
 
873
        import breezy.testingplugins.test_foo.test_bar
 
874
        self.assertIsSameRealPath('non-standard-dir/test_bar/__init__.py',
 
875
                                  self.module.test_foo.test_bar.__file__)
 
876
 
 
877
    def test_relative_submodule_loading(self):
 
878
        self.create_plugin_package('test_foo', dir='another-dir', source='''
 
879
from . import test_bar
 
880
''')
 
881
        # We create an additional directory under the one for test_foo
 
882
        self.create_plugin_package('test_bar', dir='another-dir/test_bar')
 
883
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@another-dir')
 
884
        self.update_module_paths(['standard'])
 
885
        import breezy.testingplugins.test_foo
 
886
        self.assertEqual(self.module_prefix + 'test_foo',
 
887
                         self.module.test_foo.__package__)
 
888
        self.assertIsSameRealPath('another-dir/test_bar/__init__.py',
 
889
                                  self.module.test_foo.test_bar.__file__)
 
890
 
 
891
    def test_loading_from___init__only(self):
 
892
        # We rename the existing __init__.py file to ensure that we don't load
 
893
        # a random file
 
894
        init = 'non-standard-dir/__init__.py'
 
895
        random = 'non-standard-dir/setup.py'
 
896
        os.rename(init, random)
 
897
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
898
        self.load_with_paths(['standard'])
 
899
        self.assertPluginUnknown('test_foo')
 
900
 
 
901
    def test_loading_from_specific_file(self):
 
902
        plugin_dir = 'non-standard-dir'
 
903
        plugin_file_name = 'iamtestfoo.py'
 
904
        plugin_path = osutils.pathjoin(plugin_dir, plugin_file_name)
 
905
        source = '''\
 
906
"""This is the doc for %s"""
 
907
dir_source = '%s'
 
908
''' % ('test_foo', plugin_path)
 
909
        self.create_plugin('test_foo', source=source,
 
910
                           dir=plugin_dir, file_name=plugin_file_name)
 
911
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@%s' % plugin_path)
 
912
        self.load_with_paths(['standard'])
 
913
        self.assertTestFooLoadedFrom(plugin_path)
 
914
 
 
915
 
 
916
class TestDescribePlugins(BaseTestPlugins):
 
917
 
 
918
    def test_describe_plugins(self):
 
919
        class DummyModule(object):
 
920
            __doc__ = 'Hi there'
 
921
        class DummyPlugin(object):
 
922
            __version__ = '0.1.0'
 
923
            module = DummyModule()
 
924
        self.plugin_warnings = {'bad': ['Failed to load (just testing)']}
 
925
        self.plugins = {'good': DummyPlugin()}
 
926
        self.assertEqual("""\
 
927
bad (failed to load)
 
928
  ** Failed to load (just testing)
 
929
 
 
930
good 0.1.0
 
931
  Hi there
 
932
 
 
933
""", ''.join(plugin.describe_plugins(state=self)))