/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_plugins.py

  • Committer: Robert Collins
  • Date: 2005-12-24 02:20:45 UTC
  • mto: (1185.50.57 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1550.
  • Revision ID: robertc@robertcollins.net-20051224022045-14efc8dfa0e1a4e9
Start tests for api usage.

Show diffs side-by-side

added added

removed removed

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