/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: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2012, 2016 Canonical Ltd, 2017 Breezy developers
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Tests for plugins"""
18
18
 
19
 
try:
20
 
    from importlib.util import module_from_spec
21
 
except ImportError:  # python < 3
22
 
    from imp import new_module as module_from_spec
23
 
import importlib
 
19
# XXX: There are no plugin tests at the moment because the plugin module
 
20
# affects the global state of the process.  See bzrlib/plugins.py for more
 
21
# comments.
 
22
 
 
23
from cStringIO import StringIO
24
24
import logging
25
25
import os
26
26
import sys
27
27
 
28
 
import breezy
29
 
from .. import (
 
28
import bzrlib
 
29
from bzrlib import (
30
30
    errors,
31
31
    osutils,
32
32
    plugin,
 
33
    plugins,
33
34
    tests,
34
35
    trace,
35
36
    )
36
 
from ..sixish import (
37
 
    PY3,
38
 
    StringIO,
39
 
    viewkeys,
40
 
    )
41
37
 
42
38
 
43
39
# TODO: Write a test for plugin decoration of commands.
44
40
 
45
 
invalidate_caches = getattr(importlib, "invalidate_caches", lambda: None)
46
 
 
47
 
 
48
41
class BaseTestPlugins(tests.TestCaseInTempDir):
49
 
    """TestCase that isolates plugin imports and cleans up on completion."""
50
 
 
51
 
    def setUp(self):
52
 
        super(BaseTestPlugins, self).setUp()
53
 
        self.module_name = "breezy.testingplugins"
54
 
        self.module_prefix = self.module_name + "."
55
 
        self.module = module_from_spec(self.module_name)
56
 
 
57
 
        self.overrideAttr(plugin, "_MODULE_PREFIX", self.module_prefix)
58
 
        self.overrideAttr(breezy, "testingplugins", self.module)
59
 
 
60
 
        sys.modules[self.module_name] = self.module
61
 
        self.addCleanup(self._unregister_all)
62
 
        self.addCleanup(self._unregister_finder)
63
 
 
64
 
        invalidate_caches()
65
 
 
66
 
    def reset(self):
67
 
        """Remove all global testing state and clean up module."""
68
 
        # GZ 2017-06-02: Ideally don't do this, write new test or generate
69
 
        # bytecode by other mechanism.
70
 
        self.log("resetting plugin testing context")
71
 
        self._unregister_all()
72
 
        self._unregister_finder()
73
 
        sys.modules[self.module_name] = self.module
74
 
        for name in list(self.module.__dict__):
75
 
            if name[:2] != '__':
76
 
                delattr(self.module, name)
77
 
        invalidate_caches()
78
 
        self.plugins = None
79
 
 
80
 
    def update_module_paths(self, paths):
81
 
        paths = plugin.extend_path(paths, self.module_name)
82
 
        self.module.__path__ = paths
83
 
        self.log("using %r", paths)
84
 
        return paths
85
 
 
86
 
    def load_with_paths(self, paths):
87
 
        self.log("loading plugins!")
88
 
        plugin.load_plugins(self.update_module_paths(paths), state=self)
89
42
 
90
43
    def create_plugin(self, name, source=None, dir='.', file_name=None):
91
44
        if source is None:
96
49
            file_name = name + '.py'
97
50
        # 'source' must not fail to load
98
51
        path = osutils.pathjoin(dir, file_name)
99
 
        with open(path, 'w') as f:
 
52
        f = open(path, 'w')
 
53
        self.addCleanup(os.unlink, path)
 
54
        try:
100
55
            f.write(source + '\n')
 
56
        finally:
 
57
            f.close()
101
58
 
102
59
    def create_plugin_package(self, name, dir=None, source=None):
103
60
        if dir is None:
108
65
dir_source = '%s'
109
66
''' % (name, dir)
110
67
        os.makedirs(dir)
 
68
        def cleanup():
 
69
            # Workaround lazy import random? madness
 
70
            osutils.rmtree(dir)
 
71
        self.addCleanup(cleanup)
111
72
        self.create_plugin(name, source, dir,
112
73
                           file_name='__init__.py')
113
74
 
114
 
    def promote_cache(self, directory):
115
 
        """Move bytecode files out of __pycache__ in given directory."""
116
 
        cache_dir = os.path.join(directory, '__pycache__')
117
 
        if os.path.isdir(cache_dir):
118
 
            for name in os.listdir(cache_dir):
119
 
                magicless_name = '.'.join(name.split('.')[0::name.count('.')])
120
 
                rel = osutils.relpath(self.test_dir, cache_dir)
121
 
                self.log("moving %s in %s to %s", name, rel, magicless_name)
122
 
                os.rename(os.path.join(cache_dir, name),
123
 
                    os.path.join(directory, magicless_name))
124
 
 
125
 
    def _unregister_finder(self):
126
 
        """Removes any test copies of _PluginsAtFinder from sys.meta_path."""
127
 
        idx = len(sys.meta_path)
128
 
        while idx:
129
 
            idx -= 1
130
 
            finder = sys.meta_path[idx]
131
 
            if getattr(finder, "prefix", "") == self.module_prefix:
132
 
                self.log("removed %r from sys.meta_path", finder)
133
 
                sys.meta_path.pop(idx)
134
 
 
135
 
    def _unregister_all(self):
136
 
        """Remove all plugins in the test namespace from sys.modules."""
137
 
        for name in list(sys.modules):
138
 
            if name.startswith(self.module_prefix) or name == self.module_name:
139
 
                self.log("removed %s from sys.modules", name)
140
 
                del sys.modules[name]
141
 
 
142
 
    def assertPluginModules(self, plugin_dict):
143
 
        self.assertEqual(
144
 
            dict((k[len(self.module_prefix):], sys.modules[k])
145
 
                for k in sys.modules if k.startswith(self.module_prefix)),
146
 
            plugin_dict)
 
75
    def _unregister_plugin(self, name):
 
76
        """Remove the plugin from sys.modules and the bzrlib namespace."""
 
77
        py_name = 'bzrlib.plugins.%s' % name
 
78
        if py_name in sys.modules:
 
79
            del sys.modules[py_name]
 
80
        if getattr(bzrlib.plugins, name, None) is not None:
 
81
            delattr(bzrlib.plugins, name)
 
82
 
 
83
    def _unregister_plugin_submodule(self, plugin_name, submodule_name):
 
84
        """Remove the submodule from sys.modules and the bzrlib namespace."""
 
85
        py_name = 'bzrlib.plugins.%s.%s' % (plugin_name, submodule_name)
 
86
        if py_name in sys.modules:
 
87
            del sys.modules[py_name]
 
88
        plugin = getattr(bzrlib.plugins, plugin_name, None)
 
89
        if plugin is not None:
 
90
            if getattr(plugin, submodule_name, None) is not None:
 
91
                delattr(plugin, submodule_name)
147
92
 
148
93
    def assertPluginUnknown(self, name):
149
 
        self.assertTrue(getattr(self.module, name, None) is None)
150
 
        self.assertFalse(self.module_prefix + name in sys.modules)
 
94
        self.assertFalse(getattr(bzrlib.plugins, name, None) is not None)
 
95
        self.assertFalse('bzrlib.plugins.%s' % name in sys.modules)
151
96
 
152
97
    def assertPluginKnown(self, name):
153
 
        self.assertTrue(getattr(self.module, name, None) is not None)
154
 
        self.assertTrue(self.module_prefix + name in sys.modules)
 
98
        self.assertTrue(getattr(bzrlib.plugins, name, None) is not None)
 
99
        self.assertTrue('bzrlib.plugins.%s' % name in sys.modules)
155
100
 
156
101
 
157
102
class TestLoadingPlugins(BaseTestPlugins):
175
120
        os.mkdir('second')
176
121
        # write a plugin that will record when its loaded in the
177
122
        # tempattribute list.
178
 
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
 
123
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
179
124
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
180
125
 
181
 
        with open(os.path.join('first', 'plugin.py'), 'w') as outfile:
 
126
        outfile = open(os.path.join('first', 'plugin.py'), 'w')
 
127
        try:
182
128
            outfile.write(template % (tempattribute, 'first'))
183
129
            outfile.write('\n')
 
130
        finally:
 
131
            outfile.close()
184
132
 
185
 
        with open(os.path.join('second', 'plugin.py'), 'w') as outfile:
 
133
        outfile = open(os.path.join('second', 'plugin.py'), 'w')
 
134
        try:
186
135
            outfile.write(template % (tempattribute, 'second'))
187
136
            outfile.write('\n')
 
137
        finally:
 
138
            outfile.close()
188
139
 
189
140
        try:
190
 
            self.load_with_paths(['first', 'second'])
 
141
            bzrlib.plugin.load_from_path(['first', 'second'])
191
142
            self.assertEqual(['first'], self.activeattributes[tempattribute])
192
143
        finally:
 
144
            # remove the plugin 'plugin'
193
145
            del self.activeattributes[tempattribute]
 
146
            self._unregister_plugin('plugin')
 
147
        self.assertPluginUnknown('plugin')
194
148
 
195
149
    def test_plugins_from_different_dirs_can_demand_load(self):
196
 
        self.assertFalse('breezy.plugins.pluginone' in sys.modules)
197
 
        self.assertFalse('breezy.plugins.plugintwo' in sys.modules)
 
150
        self.assertFalse('bzrlib.plugins.pluginone' in sys.modules)
 
151
        self.assertFalse('bzrlib.plugins.plugintwo' in sys.modules)
198
152
        # This test tests that having two plugins in different
199
153
        # directories with different names allows them both to be loaded, when
200
154
        # we do a direct import statement.
205
159
        # set a place for the plugins to record their loading, and at the same
206
160
        # time validate that the location the plugins should record to is
207
161
        # valid and correct.
208
 
        breezy.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
162
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
209
163
            [tempattribute] = []
210
164
        self.assertTrue(tempattribute in self.activeattributes)
211
165
        # create two plugin directories
213
167
        os.mkdir('second')
214
168
        # write plugins that will record when they are loaded in the
215
169
        # tempattribute list.
216
 
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
 
170
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
217
171
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
218
172
 
219
 
        with open(os.path.join('first', 'pluginone.py'), 'w') as outfile:
 
173
        outfile = open(os.path.join('first', 'pluginone.py'), 'w')
 
174
        try:
220
175
            outfile.write(template % (tempattribute, 'first'))
221
176
            outfile.write('\n')
 
177
        finally:
 
178
            outfile.close()
222
179
 
223
 
        with open(os.path.join('second', 'plugintwo.py'), 'w') as outfile:
 
180
        outfile = open(os.path.join('second', 'plugintwo.py'), 'w')
 
181
        try:
224
182
            outfile.write(template % (tempattribute, 'second'))
225
183
            outfile.write('\n')
 
184
        finally:
 
185
            outfile.close()
226
186
 
 
187
        oldpath = bzrlib.plugins.__path__
227
188
        try:
228
 
            self.assertPluginUnknown('pluginone')
229
 
            self.assertPluginUnknown('plugintwo')
230
 
            self.update_module_paths(['first', 'second'])
231
 
            exec("import %spluginone" % self.module_prefix)
 
189
            self.assertFalse('bzrlib.plugins.pluginone' in sys.modules)
 
190
            self.assertFalse('bzrlib.plugins.plugintwo' in sys.modules)
 
191
            bzrlib.plugins.__path__ = ['first', 'second']
 
192
            exec "import bzrlib.plugins.pluginone"
232
193
            self.assertEqual(['first'], self.activeattributes[tempattribute])
233
 
            exec("import %splugintwo" % self.module_prefix)
 
194
            exec "import bzrlib.plugins.plugintwo"
234
195
            self.assertEqual(['first', 'second'],
235
196
                self.activeattributes[tempattribute])
236
197
        finally:
 
198
            # remove the plugin 'plugin'
237
199
            del self.activeattributes[tempattribute]
 
200
            self._unregister_plugin('pluginone')
 
201
            self._unregister_plugin('plugintwo')
 
202
        self.assertPluginUnknown('pluginone')
 
203
        self.assertPluginUnknown('plugintwo')
238
204
 
239
205
    def test_plugins_can_load_from_directory_with_trailing_slash(self):
240
206
        # This test tests that a plugin can load from a directory when the
246
212
        # set a place for the plugin to record its loading, and at the same
247
213
        # time validate that the location the plugin should record to is
248
214
        # valid and correct.
249
 
        breezy.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
215
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
250
216
            [tempattribute] = []
251
217
        self.assertTrue(tempattribute in self.activeattributes)
252
218
        # create a directory for the plugin
253
219
        os.mkdir('plugin_test')
254
220
        # write a plugin that will record when its loaded in the
255
221
        # tempattribute list.
256
 
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
 
222
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
257
223
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
258
224
 
259
 
        with open(os.path.join('plugin_test', 'ts_plugin.py'), 'w') as outfile:
 
225
        outfile = open(os.path.join('plugin_test', 'ts_plugin.py'), 'w')
 
226
        try:
260
227
            outfile.write(template % (tempattribute, 'plugin'))
261
228
            outfile.write('\n')
 
229
        finally:
 
230
            outfile.close()
262
231
 
263
232
        try:
264
 
            self.load_with_paths(['plugin_test'+os.sep])
 
233
            bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
265
234
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
266
 
            self.assertPluginKnown('ts_plugin')
267
235
        finally:
268
236
            del self.activeattributes[tempattribute]
 
237
            self._unregister_plugin('ts_plugin')
 
238
        self.assertPluginUnknown('ts_plugin')
269
239
 
270
240
    def load_and_capture(self, name):
271
241
        """Load plugins from '.' capturing the output.
277
247
        stream = StringIO()
278
248
        try:
279
249
            handler = logging.StreamHandler(stream)
280
 
            log = logging.getLogger('brz')
 
250
            log = logging.getLogger('bzr')
281
251
            log.addHandler(handler)
282
252
            try:
283
 
                self.load_with_paths(['.'])
 
253
                try:
 
254
                    bzrlib.plugin.load_from_path(['.'])
 
255
                finally:
 
256
                    if 'bzrlib.plugins.%s' % name in sys.modules:
 
257
                        del sys.modules['bzrlib.plugins.%s' % name]
 
258
                    if getattr(bzrlib.plugins, name, None):
 
259
                        delattr(bzrlib.plugins, name)
284
260
            finally:
285
261
                # Stop capturing output
286
262
                handler.flush()
292
268
 
293
269
    def test_plugin_with_bad_api_version_reports(self):
294
270
        """Try loading a plugin that requests an unsupported api.
295
 
 
 
271
        
296
272
        Observe that it records the problem but doesn't complain on stderr.
297
273
 
298
274
        See https://bugs.launchpad.net/bzr/+bug/704195
299
275
        """
 
276
        self.overrideAttr(plugin, 'plugin_warnings', {})
300
277
        name = 'wants100.py'
301
 
        with open(name, 'w') as f:
302
 
            f.write("import breezy\n"
303
 
                "from breezy.errors import IncompatibleVersion\n"
304
 
                "raise IncompatibleVersion(breezy, [(1, 0, 0)], (0, 0, 5))\n")
 
278
        f = file(name, 'w')
 
279
        try:
 
280
            f.write("import bzrlib.api\n"
 
281
                "bzrlib.api.require_any_api(bzrlib, [(1, 0, 0)])\n")
 
282
        finally:
 
283
            f.close()
305
284
        log = self.load_and_capture(name)
306
285
        self.assertNotContainsRe(log,
307
 
            r"It supports breezy version")
308
 
        self.assertEqual({'wants100'}, viewkeys(self.plugin_warnings))
 
286
            r"It requested API version")
 
287
        self.assertEquals(
 
288
            ['wants100'],
 
289
            plugin.plugin_warnings.keys())
309
290
        self.assertContainsRe(
310
 
            self.plugin_warnings['wants100'][0],
311
 
            r"It supports breezy version")
 
291
            plugin.plugin_warnings['wants100'][0],
 
292
            r"It requested API version")
312
293
 
313
294
    def test_plugin_with_bad_name_does_not_load(self):
314
295
        # The file name here invalid for a python module.
315
 
        name = 'brz-bad plugin-name..py'
316
 
        open(name, 'w').close()
 
296
        name = 'bzr-bad plugin-name..py'
 
297
        file(name, 'w').close()
317
298
        log = self.load_and_capture(name)
318
299
        self.assertContainsRe(log,
319
 
            r"Unable to load 'brz-bad plugin-name\.' in '\.' as a plugin "
 
300
            r"Unable to load 'bzr-bad plugin-name\.' in '\.' as a plugin "
320
301
            "because the file path isn't a valid module name; try renaming "
321
 
            "it to 'bad_plugin_name_'\\.")
 
302
            "it to 'bad_plugin_name_'\.")
322
303
 
323
304
 
324
305
class TestPlugins(BaseTestPlugins):
325
306
 
326
307
    def setup_plugin(self, source=""):
327
 
        # This test tests a new plugin appears in breezy.plugin.plugins().
 
308
        # This test tests a new plugin appears in bzrlib.plugin.plugins().
328
309
        # check the plugin is not loaded already
329
310
        self.assertPluginUnknown('plugin')
330
311
        # write a plugin that _cannot_ fail to load.
331
 
        with open('plugin.py', 'w') as f: f.write(source + '\n')
332
 
        self.load_with_paths(['.'])
333
 
 
334
 
    def test_plugin_loaded(self):
335
 
        self.assertPluginUnknown('plugin')
336
 
        self.assertIs(None, breezy.plugin.get_loaded_plugin('plugin'))
337
 
        self.setup_plugin()
338
 
        p = breezy.plugin.get_loaded_plugin('plugin')
339
 
        self.assertIsInstance(p, breezy.plugin.PlugIn)
340
 
        self.assertIs(p.module, sys.modules[self.module_prefix + 'plugin'])
341
 
 
342
 
    def test_plugin_loaded_disabled(self):
343
 
        self.assertPluginUnknown('plugin')
344
 
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'plugin')
345
 
        self.setup_plugin()
346
 
        self.assertIs(None, breezy.plugin.get_loaded_plugin('plugin'))
 
312
        with file('plugin.py', 'w') as f: f.write(source + '\n')
 
313
        self.addCleanup(self.teardown_plugin)
 
314
        plugin.load_from_path(['.'])
 
315
 
 
316
    def teardown_plugin(self):
 
317
        self._unregister_plugin('plugin')
 
318
        self.assertPluginUnknown('plugin')
347
319
 
348
320
    def test_plugin_appears_in_plugins(self):
349
321
        self.setup_plugin()
350
322
        self.assertPluginKnown('plugin')
351
 
        p = self.plugins['plugin']
352
 
        self.assertIsInstance(p, breezy.plugin.PlugIn)
353
 
        self.assertIs(p.module, sys.modules[self.module_prefix + 'plugin'])
 
323
        p = plugin.plugins()['plugin']
 
324
        self.assertIsInstance(p, bzrlib.plugin.PlugIn)
 
325
        self.assertEqual(p.module, plugins.plugin)
354
326
 
355
327
    def test_trivial_plugin_get_path(self):
356
328
        self.setup_plugin()
357
 
        p = self.plugins['plugin']
 
329
        p = plugin.plugins()['plugin']
358
330
        plugin_path = self.test_dir + '/plugin.py'
359
331
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
360
332
 
361
333
    def test_plugin_get_path_py_not_pyc(self):
362
334
        # first import creates plugin.pyc
363
335
        self.setup_plugin()
364
 
        self.promote_cache(self.test_dir)
365
 
        self.reset()
366
 
        self.load_with_paths(['.']) # import plugin.pyc
 
336
        self.teardown_plugin()
 
337
        plugin.load_from_path(['.']) # import plugin.pyc
367
338
        p = plugin.plugins()['plugin']
368
339
        plugin_path = self.test_dir + '/plugin.py'
369
340
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
371
342
    def test_plugin_get_path_pyc_only(self):
372
343
        # first import creates plugin.pyc (or plugin.pyo depending on __debug__)
373
344
        self.setup_plugin()
 
345
        self.teardown_plugin()
374
346
        os.unlink(self.test_dir + '/plugin.py')
375
 
        self.promote_cache(self.test_dir)
376
 
        self.reset()
377
 
        self.load_with_paths(['.']) # import plugin.pyc (or .pyo)
 
347
        plugin.load_from_path(['.']) # import plugin.pyc (or .pyo)
378
348
        p = plugin.plugins()['plugin']
379
 
        plugin_path = self.test_dir + '/plugin' + plugin.COMPILED_EXT
 
349
        if __debug__:
 
350
            plugin_path = self.test_dir + '/plugin.pyc'
 
351
        else:
 
352
            plugin_path = self.test_dir + '/plugin.pyo'
380
353
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
381
354
 
382
355
    def test_no_test_suite_gives_None_for_test_suite(self):
398
371
 
399
372
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
400
373
        source = """
401
 
def load_tests(loader, standard_tests, pattern):
 
374
def load_tests(standard_tests, module, loader):
402
375
    return 'foo'"""
403
376
        self.setup_plugin(source)
404
377
        loader = tests.TestUtil.TestLoader()
428
401
 
429
402
    def test_no_version_info___version__(self):
430
403
        self.setup_plugin()
431
 
        plugin = breezy.plugin.plugins()['plugin']
 
404
        plugin = bzrlib.plugin.plugins()['plugin']
432
405
        self.assertEqual("unknown", plugin.__version__)
433
406
 
434
407
    def test_str__version__with_version_info(self):
435
408
        self.setup_plugin("version_info = '1.2.3'")
436
 
        plugin = breezy.plugin.plugins()['plugin']
 
409
        plugin = bzrlib.plugin.plugins()['plugin']
437
410
        self.assertEqual("1.2.3", plugin.__version__)
438
411
 
439
412
    def test_noniterable__version__with_version_info(self):
440
413
        self.setup_plugin("version_info = (1)")
441
 
        plugin = breezy.plugin.plugins()['plugin']
 
414
        plugin = bzrlib.plugin.plugins()['plugin']
442
415
        self.assertEqual("1", plugin.__version__)
443
416
 
444
417
    def test_1__version__with_version_info(self):
445
418
        self.setup_plugin("version_info = (1,)")
446
 
        plugin = breezy.plugin.plugins()['plugin']
 
419
        plugin = bzrlib.plugin.plugins()['plugin']
447
420
        self.assertEqual("1", plugin.__version__)
448
421
 
449
422
    def test_1_2__version__with_version_info(self):
450
423
        self.setup_plugin("version_info = (1, 2)")
451
 
        plugin = breezy.plugin.plugins()['plugin']
 
424
        plugin = bzrlib.plugin.plugins()['plugin']
452
425
        self.assertEqual("1.2", plugin.__version__)
453
426
 
454
427
    def test_1_2_3__version__with_version_info(self):
455
428
        self.setup_plugin("version_info = (1, 2, 3)")
456
 
        plugin = breezy.plugin.plugins()['plugin']
 
429
        plugin = bzrlib.plugin.plugins()['plugin']
457
430
        self.assertEqual("1.2.3", plugin.__version__)
458
431
 
459
432
    def test_candidate__version__with_version_info(self):
460
433
        self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
461
 
        plugin = breezy.plugin.plugins()['plugin']
 
434
        plugin = bzrlib.plugin.plugins()['plugin']
462
435
        self.assertEqual("1.2.3rc1", plugin.__version__)
463
436
 
464
437
    def test_dev__version__with_version_info(self):
465
438
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 0)")
466
 
        plugin = breezy.plugin.plugins()['plugin']
 
439
        plugin = bzrlib.plugin.plugins()['plugin']
467
440
        self.assertEqual("1.2.3dev", plugin.__version__)
468
441
 
469
442
    def test_dev_fallback__version__with_version_info(self):
470
443
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
471
 
        plugin = breezy.plugin.plugins()['plugin']
 
444
        plugin = bzrlib.plugin.plugins()['plugin']
472
445
        self.assertEqual("1.2.3dev4", plugin.__version__)
473
446
 
474
447
    def test_final__version__with_version_info(self):
475
448
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
476
 
        plugin = breezy.plugin.plugins()['plugin']
 
449
        plugin = bzrlib.plugin.plugins()['plugin']
477
450
        self.assertEqual("1.2.3", plugin.__version__)
478
451
 
479
452
    def test_final_fallback__version__with_version_info(self):
480
453
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
481
 
        plugin = breezy.plugin.plugins()['plugin']
 
454
        plugin = bzrlib.plugin.plugins()['plugin']
482
455
        self.assertEqual("1.2.3.2", plugin.__version__)
483
456
 
484
457
 
485
 
# GZ 2017-06-02: Move this suite to blackbox, as it's what it actually is.
486
 
class TestPluginHelp(BaseTestPlugins):
 
458
class TestPluginHelp(tests.TestCaseInTempDir):
487
459
 
488
460
    def split_help_commands(self):
489
461
        help = {}
499
471
    def test_plugin_help_builtins_unaffected(self):
500
472
        # Check we don't get false positives
501
473
        help_commands = self.split_help_commands()
502
 
        for cmd_name in breezy.commands.builtin_command_names():
503
 
            if cmd_name in breezy.commands.plugin_command_names():
 
474
        for cmd_name in bzrlib.commands.builtin_command_names():
 
475
            if cmd_name in bzrlib.commands.plugin_command_names():
504
476
                continue
505
477
            try:
506
 
                help = breezy.commands.get_cmd_object(cmd_name).get_help_text()
 
478
                help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
507
479
            except NotImplementedError:
508
480
                # some commands have no help
509
481
                pass
510
482
            else:
511
483
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
512
484
 
513
 
            if cmd_name in help_commands:
 
485
            if cmd_name in help_commands.keys():
514
486
                # some commands are hidden
515
487
                help = help_commands[cmd_name]
516
488
                self.assertNotContainsRe(help, 'plugin "[^"]*"')
518
490
    def test_plugin_help_shows_plugin(self):
519
491
        # Create a test plugin
520
492
        os.mkdir('plugin_test')
521
 
        source = (
522
 
            "from breezy import commands\n"
523
 
            "class cmd_myplug(commands.Command):\n"
524
 
            "    __doc__ = '''Just a simple test plugin.'''\n"
525
 
            "    aliases = ['mplg']\n"
526
 
            "    def run(self):\n"
527
 
            "        print ('Hello from my plugin')\n"
528
 
        )
529
 
        self.create_plugin('myplug', source, 'plugin_test')
530
 
 
531
 
        # Check its help
532
 
        self.load_with_paths(['plugin_test'])
533
 
        myplug = self.plugins['myplug'].module
534
 
        breezy.commands.register_command(myplug.cmd_myplug)
535
 
        self.addCleanup(breezy.commands.plugin_cmds.remove, 'myplug')
536
 
        help = self.run_bzr('help myplug')[0]
537
 
        self.assertContainsRe(help, 'plugin "myplug"')
538
 
        help = self.split_help_commands()['myplug']
539
 
        self.assertContainsRe(help, '\\[myplug\\]')
 
493
        f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
 
494
        f.write("""\
 
495
from bzrlib import commands
 
496
class cmd_myplug(commands.Command):
 
497
    __doc__ = '''Just a simple test plugin.'''
 
498
    aliases = ['mplg']
 
499
    def run(self):
 
500
        print 'Hello from my plugin'
 
501
 
 
502
"""
 
503
)
 
504
        f.close()
 
505
 
 
506
        try:
 
507
            # Check its help
 
508
            bzrlib.plugin.load_from_path(['plugin_test'])
 
509
            bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
 
510
            help = self.run_bzr('help myplug')[0]
 
511
            self.assertContainsRe(help, 'plugin "myplug"')
 
512
            help = self.split_help_commands()['myplug']
 
513
            self.assertContainsRe(help, '\[myplug\]')
 
514
        finally:
 
515
            # unregister command
 
516
            if 'myplug' in bzrlib.commands.plugin_cmds:
 
517
                bzrlib.commands.plugin_cmds.remove('myplug')
 
518
            # remove the plugin 'myplug'
 
519
            if getattr(bzrlib.plugins, 'myplug', None):
 
520
                delattr(bzrlib.plugins, 'myplug')
540
521
 
541
522
 
542
523
class TestHelpIndex(tests.TestCase):
555
536
        index = plugin.PluginsHelpIndex()
556
537
        # make a new plugin here for this test, even if we're run with
557
538
        # --no-plugins
558
 
        self.assertFalse('breezy.plugins.demo_module' in sys.modules)
559
 
        demo_module = FakeModule('', 'breezy.plugins.demo_module')
560
 
        sys.modules['breezy.plugins.demo_module'] = demo_module
 
539
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
 
540
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
 
541
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
561
542
        try:
562
543
            topics = index.get_topics('demo_module')
563
544
            self.assertEqual(1, len(topics))
564
545
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
565
546
            self.assertEqual(demo_module, topics[0].module)
566
547
        finally:
567
 
            del sys.modules['breezy.plugins.demo_module']
 
548
            del sys.modules['bzrlib.plugins.demo_module']
568
549
 
569
550
    def test_get_topics_no_topic(self):
570
551
        """Searching for something that is not a plugin returns []."""
581
562
    def test_get_plugin_topic_with_prefix(self):
582
563
        """Searching for plugins/demo_module returns help."""
583
564
        index = plugin.PluginsHelpIndex()
584
 
        self.assertFalse('breezy.plugins.demo_module' in sys.modules)
585
 
        demo_module = FakeModule('', 'breezy.plugins.demo_module')
586
 
        sys.modules['breezy.plugins.demo_module'] = demo_module
 
565
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
 
566
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
 
567
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
587
568
        try:
588
569
            topics = index.get_topics('plugins/demo_module')
589
570
            self.assertEqual(1, len(topics))
590
571
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
591
572
            self.assertEqual(demo_module, topics[0].module)
592
573
        finally:
593
 
            del sys.modules['breezy.plugins.demo_module']
 
574
            del sys.modules['bzrlib.plugins.demo_module']
594
575
 
595
576
 
596
577
class FakeModule(object):
639
620
 
640
621
    def test_get_help_topic(self):
641
622
        """The help topic for a plugin is its module name."""
642
 
        mod = FakeModule('two lines of help\nand more', 'breezy.plugins.demo')
 
623
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
643
624
        topic = plugin.ModuleHelpTopic(mod)
644
625
        self.assertEqual('demo', topic.get_help_topic())
645
626
        mod = FakeModule('two lines of help\nand more',
646
 
                         'breezy.plugins.foo_bar')
 
627
                         'bzrlib.plugins.foo_bar')
647
628
        topic = plugin.ModuleHelpTopic(mod)
648
629
        self.assertEqual('foo_bar', topic.get_help_topic())
649
630
 
650
631
 
 
632
class TestLoadFromPath(tests.TestCaseInTempDir):
 
633
 
 
634
    def setUp(self):
 
635
        super(TestLoadFromPath, self).setUp()
 
636
        # Change bzrlib.plugin to think no plugins have been loaded yet.
 
637
        self.overrideAttr(bzrlib.plugins, '__path__', [])
 
638
        self.overrideAttr(plugin, '_loaded', False)
 
639
 
 
640
        # Monkey-patch load_from_path to stop it from actually loading anything.
 
641
        self.overrideAttr(plugin, 'load_from_path', lambda dirs: None)
 
642
 
 
643
    def test_set_plugins_path_with_args(self):
 
644
        plugin.set_plugins_path(['a', 'b'])
 
645
        self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
 
646
 
 
647
    def test_set_plugins_path_defaults(self):
 
648
        plugin.set_plugins_path()
 
649
        self.assertEqual(plugin.get_standard_plugins_path(),
 
650
                         bzrlib.plugins.__path__)
 
651
 
 
652
    def test_get_standard_plugins_path(self):
 
653
        path = plugin.get_standard_plugins_path()
 
654
        for directory in path:
 
655
            self.assertNotContainsRe(directory, r'\\/$')
 
656
        try:
 
657
            from distutils.sysconfig import get_python_lib
 
658
        except ImportError:
 
659
            pass
 
660
        else:
 
661
            if sys.platform != 'win32':
 
662
                python_lib = get_python_lib()
 
663
                for directory in path:
 
664
                    if directory.startswith(python_lib):
 
665
                        break
 
666
                else:
 
667
                    self.fail('No path to global plugins')
 
668
 
 
669
    def test_get_standard_plugins_path_env(self):
 
670
        self.overrideEnv('BZR_PLUGIN_PATH', 'foo/')
 
671
        path = plugin.get_standard_plugins_path()
 
672
        for directory in path:
 
673
            self.assertNotContainsRe(directory, r'\\/$')
 
674
 
 
675
    def test_load_plugins(self):
 
676
        plugin.load_plugins(['.'])
 
677
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
678
        # subsequent loads are no-ops
 
679
        plugin.load_plugins(['foo'])
 
680
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
681
 
 
682
    def test_load_plugins_default(self):
 
683
        plugin.load_plugins()
 
684
        path = plugin.get_standard_plugins_path()
 
685
        self.assertEqual(path, bzrlib.plugins.__path__)
 
686
 
 
687
 
651
688
class TestEnvPluginPath(tests.TestCase):
652
689
 
653
 
    user = "USER"
654
 
    core = "CORE"
655
 
    site = "SITE"
 
690
    def setUp(self):
 
691
        super(TestEnvPluginPath, self).setUp()
 
692
        self.overrideAttr(plugin, 'DEFAULT_PLUGIN_PATH', None)
 
693
 
 
694
        self.user = plugin.get_user_plugin_path()
 
695
        self.site = plugin.get_site_plugin_path()
 
696
        self.core = plugin.get_core_plugin_path()
 
697
 
 
698
    def _list2paths(self, *args):
 
699
        paths = []
 
700
        for p in args:
 
701
            plugin._append_new_path(paths, p)
 
702
        return paths
 
703
 
 
704
    def _set_path(self, *args):
 
705
        path = os.pathsep.join(self._list2paths(*args))
 
706
        self.overrideEnv('BZR_PLUGIN_PATH', path)
656
707
 
657
708
    def check_path(self, expected_dirs, setting_dirs):
658
 
        if setting_dirs is None:
659
 
            del os.environ['BRZ_PLUGIN_PATH']
660
 
        else:
661
 
            os.environ['BRZ_PLUGIN_PATH'] = os.pathsep.join(setting_dirs)
662
 
        actual = [(p if t == 'path' else t.upper())
663
 
            for p, t in plugin._env_plugin_path()]
664
 
        self.assertEqual(expected_dirs, actual)
 
709
        if setting_dirs:
 
710
            self._set_path(*setting_dirs)
 
711
        actual = plugin.get_standard_plugins_path()
 
712
        self.assertEquals(self._list2paths(*expected_dirs), actual)
665
713
 
666
714
    def test_default(self):
667
715
        self.check_path([self.user, self.core, self.site],
733
781
 
734
782
class TestDisablePlugin(BaseTestPlugins):
735
783
 
 
784
    def setUp(self):
 
785
        super(TestDisablePlugin, self).setUp()
 
786
        self.create_plugin_package('test_foo')
 
787
        # Make sure we don't pollute the plugins namespace
 
788
        self.overrideAttr(plugins, '__path__')
 
789
        # Be paranoid in case a test fail
 
790
        self.addCleanup(self._unregister_plugin, 'test_foo')
 
791
 
736
792
    def test_cannot_import(self):
737
 
        self.create_plugin_package('works')
738
 
        self.create_plugin_package('fails')
739
 
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'fails')
740
 
        self.update_module_paths(["."])
741
 
        import breezy.testingplugins.works as works
 
793
        self.overrideEnv('BZR_DISABLE_PLUGINS', 'test_foo')
 
794
        plugin.set_plugins_path(['.'])
742
795
        try:
743
 
            import breezy.testingplugins.fails as fails
 
796
            import bzrlib.plugins.test_foo
744
797
        except ImportError:
745
798
            pass
746
 
        else:
747
 
            self.fail("Loaded blocked plugin: " + repr(fails))
748
 
        self.assertPluginModules({'fails': None, 'works': works})
749
 
 
750
 
    def test_partial_imports(self):
751
 
        self.create_plugin('good')
752
 
        self.create_plugin('bad')
753
 
        self.create_plugin_package('ugly')
754
 
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'bad:ugly')
755
 
        self.load_with_paths(['.'])
756
 
        self.assertEqual({'good'}, viewkeys(self.plugins))
757
 
        self.assertPluginModules({
758
 
            'good': self.plugins['good'].module,
759
 
            'bad': None,
760
 
            'ugly': None,
761
 
        })
762
 
        # Ensure there are no warnings about plugins not being imported as
763
 
        # the user has explictly requested they be disabled.
764
 
        self.assertNotContainsRe(self.get_log(), r"Unable to load plugin")
765
 
 
766
 
 
767
 
class TestEnvDisablePlugins(tests.TestCase):
768
 
 
769
 
    def _get_names(self, env_value):
770
 
        os.environ['BRZ_DISABLE_PLUGINS'] = env_value
771
 
        return plugin._env_disable_plugins()
772
 
 
773
 
    def test_unset(self):
774
 
        self.assertEqual([], plugin._env_disable_plugins())
775
 
 
776
 
    def test_empty(self):
777
 
        self.assertEqual([], self._get_names(''))
778
 
 
779
 
    def test_single(self):
780
 
        self.assertEqual(['single'], self._get_names('single'))
781
 
 
782
 
    def test_multi(self):
783
 
        expected = ['one', 'two']
784
 
        self.assertEqual(expected, self._get_names(os.pathsep.join(expected)))
785
 
 
786
 
    def test_mixed(self):
787
 
        value = os.pathsep.join(['valid', 'in-valid'])
788
 
        self.assertEqual(['valid'], self._get_names(value))
789
 
        self.assertContainsRe(self.get_log(),
790
 
            r"Invalid name 'in-valid' in BRZ_DISABLE_PLUGINS=" + repr(value))
791
 
 
792
 
 
793
 
class TestEnvPluginsAt(tests.TestCase):
794
 
 
795
 
    def _get_paths(self, env_value):
796
 
        os.environ['BRZ_PLUGINS_AT'] = env_value
797
 
        return plugin._env_plugins_at()
798
 
 
799
 
    def test_empty(self):
800
 
        self.assertEqual([], plugin._env_plugins_at())
801
 
        self.assertEqual([], self._get_paths(''))
 
799
        self.assertPluginUnknown('test_foo')
 
800
 
 
801
    def test_regular_load(self):
 
802
        self.overrideAttr(plugin, '_loaded', False)
 
803
        plugin.load_plugins(['.'])
 
804
        self.assertPluginKnown('test_foo')
 
805
        self.assertDocstring("This is the doc for test_foo",
 
806
                             bzrlib.plugins.test_foo)
 
807
 
 
808
    def test_not_loaded(self):
 
809
        self.warnings = []
 
810
        def captured_warning(*args, **kwargs):
 
811
            self.warnings.append((args, kwargs))
 
812
        self.overrideAttr(trace, 'warning', captured_warning)
 
813
        # Reset the flag that protect against double loading
 
814
        self.overrideAttr(plugin, '_loaded', False)
 
815
        self.overrideEnv('BZR_DISABLE_PLUGINS', 'test_foo')
 
816
        plugin.load_plugins(['.'])
 
817
        self.assertPluginUnknown('test_foo')
 
818
        # Make sure we don't warn about the plugin ImportError since this has
 
819
        # been *requested* by the user.
 
820
        self.assertLength(0, self.warnings)
 
821
 
 
822
 
 
823
 
 
824
class TestLoadPluginAtSyntax(tests.TestCase):
 
825
 
 
826
    def _get_paths(self, paths):
 
827
        return plugin._get_specific_plugin_paths(paths)
 
828
 
 
829
    def test_empty(self):
 
830
        self.assertEquals([], self._get_paths(None))
 
831
        self.assertEquals([], self._get_paths(''))
802
832
 
803
833
    def test_one_path(self):
804
 
        self.assertEqual([('b', 'man')], self._get_paths('b@man'))
805
 
 
806
 
    def test_multiple(self):
807
 
        self.assertEqual(
808
 
            [('tools', 'bzr-tools'), ('p', 'play.py')],
809
 
            self._get_paths(os.pathsep.join(('tools@bzr-tools', 'p@play.py'))))
810
 
 
811
 
    def test_many_at(self):
812
 
        self.assertEqual(
813
 
            [('church', 'StMichael@Plea@Norwich')],
814
 
            self._get_paths('church@StMichael@Plea@Norwich'))
815
 
 
816
 
    def test_only_py(self):
817
 
        self.assertEqual([('test', './test.py')], self._get_paths('./test.py'))
818
 
 
819
 
    def test_only_package(self):
820
 
        self.assertEqual([('py', '/opt/b/py')], self._get_paths('/opt/b/py'))
821
 
 
822
 
    def test_bad_name(self):
823
 
        self.assertEqual([], self._get_paths('/usr/local/bzr-git'))
824
 
        self.assertContainsRe(self.get_log(),
825
 
            r"Invalid name 'bzr-git' in BRZ_PLUGINS_AT='/usr/local/bzr-git'")
 
834
        self.assertEquals([('b', 'man')], self._get_paths('b@man'))
 
835
 
 
836
    def test_bogus_path(self):
 
837
        # We need a '@'
 
838
        self.assertRaises(errors.BzrCommandError, self._get_paths, 'batman')
 
839
        # Too much '@' isn't good either
 
840
        self.assertRaises(errors.BzrCommandError, self._get_paths,
 
841
                          'batman@mobile@cave')
 
842
        # An empty description probably indicates a problem
 
843
        self.assertRaises(errors.BzrCommandError, self._get_paths,
 
844
                          os.pathsep.join(['batman@cave', '', 'robin@mobile']))
826
845
 
827
846
 
828
847
class TestLoadPluginAt(BaseTestPlugins):
829
848
 
830
849
    def setUp(self):
831
850
        super(TestLoadPluginAt, self).setUp()
 
851
        # Make sure we don't pollute the plugins namespace
 
852
        self.overrideAttr(plugins, '__path__')
 
853
        # Reset the flag that protect against double loading
 
854
        self.overrideAttr(plugin, '_loaded', False)
832
855
        # Create the same plugin in two directories
833
856
        self.create_plugin_package('test_foo', dir='non-standard-dir')
834
857
        # The "normal" directory, we use 'standard' instead of 'plugins' to
835
858
        # avoid depending on the precise naming.
836
859
        self.create_plugin_package('test_foo', dir='standard/test_foo')
 
860
        # All the tests will load the 'test_foo' plugin from various locations
 
861
        self.addCleanup(self._unregister_plugin, 'test_foo')
 
862
        # Unfortunately there's global cached state for the specific
 
863
        # registered paths.
 
864
        self.addCleanup(plugin.PluginImporter.reset)
837
865
 
838
866
    def assertTestFooLoadedFrom(self, path):
839
867
        self.assertPluginKnown('test_foo')
840
868
        self.assertDocstring('This is the doc for test_foo',
841
 
                             self.module.test_foo)
842
 
        self.assertEqual(path, self.module.test_foo.dir_source)
 
869
                             bzrlib.plugins.test_foo)
 
870
        self.assertEqual(path, bzrlib.plugins.test_foo.dir_source)
843
871
 
844
872
    def test_regular_load(self):
845
 
        self.load_with_paths(['standard'])
 
873
        plugin.load_plugins(['standard'])
846
874
        self.assertTestFooLoadedFrom('standard/test_foo')
847
875
 
848
876
    def test_import(self):
849
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
850
 
        self.update_module_paths(['standard'])
851
 
        import breezy.testingplugins.test_foo
 
877
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
878
        plugin.set_plugins_path(['standard'])
 
879
        try:
 
880
            import bzrlib.plugins.test_foo
 
881
        except ImportError:
 
882
            pass
852
883
        self.assertTestFooLoadedFrom('non-standard-dir')
853
884
 
854
885
    def test_loading(self):
855
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
856
 
        self.load_with_paths(['standard'])
857
 
        self.assertTestFooLoadedFrom('non-standard-dir')
858
 
 
859
 
    def test_loading_other_name(self):
860
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
861
 
        os.rename('standard/test_foo', 'standard/test_bar')
862
 
        self.load_with_paths(['standard'])
 
886
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
887
        plugin.load_plugins(['standard'])
863
888
        self.assertTestFooLoadedFrom('non-standard-dir')
864
889
 
865
890
    def test_compiled_loaded(self):
866
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
867
 
        self.load_with_paths(['standard'])
 
891
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
892
        plugin.load_plugins(['standard'])
868
893
        self.assertTestFooLoadedFrom('non-standard-dir')
869
894
        self.assertIsSameRealPath('non-standard-dir/__init__.py',
870
 
                                  self.module.test_foo.__file__)
 
895
                                  bzrlib.plugins.test_foo.__file__)
871
896
 
872
897
        # Try importing again now that the source has been compiled
873
 
        os.remove('non-standard-dir/__init__.py')
874
 
        self.promote_cache('non-standard-dir')
875
 
        self.reset()
876
 
        self.load_with_paths(['standard'])
 
898
        self._unregister_plugin('test_foo')
 
899
        plugin._loaded = False
 
900
        plugin.load_plugins(['standard'])
877
901
        self.assertTestFooLoadedFrom('non-standard-dir')
878
 
        suffix = plugin.COMPILED_EXT
879
 
        self.assertIsSameRealPath('non-standard-dir/__init__' + suffix,
880
 
                                  self.module.test_foo.__file__)
 
902
        if __debug__:
 
903
            suffix = 'pyc'
 
904
        else:
 
905
            suffix = 'pyo'
 
906
        self.assertIsSameRealPath('non-standard-dir/__init__.%s' % suffix,
 
907
                                  bzrlib.plugins.test_foo.__file__)
881
908
 
882
909
    def test_submodule_loading(self):
883
910
        # We create an additional directory under the one for test_foo
884
911
        self.create_plugin_package('test_bar', dir='non-standard-dir/test_bar')
885
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
886
 
        self.update_module_paths(['standard'])
887
 
        import breezy.testingplugins.test_foo
888
 
        self.assertEqual(self.module_prefix + 'test_foo',
889
 
                         self.module.test_foo.__package__)
890
 
        import breezy.testingplugins.test_foo.test_bar
 
912
        self.addCleanup(self._unregister_plugin_submodule,
 
913
                        'test_foo', 'test_bar')
 
914
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
915
        plugin.set_plugins_path(['standard'])
 
916
        import bzrlib.plugins.test_foo
 
917
        self.assertEqual('bzrlib.plugins.test_foo',
 
918
                         bzrlib.plugins.test_foo.__package__)
 
919
        import bzrlib.plugins.test_foo.test_bar
891
920
        self.assertIsSameRealPath('non-standard-dir/test_bar/__init__.py',
892
 
                                  self.module.test_foo.test_bar.__file__)
 
921
                                  bzrlib.plugins.test_foo.test_bar.__file__)
893
922
 
894
923
    def test_relative_submodule_loading(self):
895
924
        self.create_plugin_package('test_foo', dir='another-dir', source='''
896
 
from . import test_bar
 
925
import test_bar
897
926
''')
898
927
        # We create an additional directory under the one for test_foo
899
928
        self.create_plugin_package('test_bar', dir='another-dir/test_bar')
900
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@another-dir')
901
 
        self.update_module_paths(['standard'])
902
 
        import breezy.testingplugins.test_foo
903
 
        self.assertEqual(self.module_prefix + 'test_foo',
904
 
                         self.module.test_foo.__package__)
 
929
        self.addCleanup(self._unregister_plugin_submodule,
 
930
                        'test_foo', 'test_bar')
 
931
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@another-dir')
 
932
        plugin.set_plugins_path(['standard'])
 
933
        import bzrlib.plugins.test_foo
 
934
        self.assertEqual('bzrlib.plugins.test_foo',
 
935
                         bzrlib.plugins.test_foo.__package__)
905
936
        self.assertIsSameRealPath('another-dir/test_bar/__init__.py',
906
 
                                  self.module.test_foo.test_bar.__file__)
 
937
                                  bzrlib.plugins.test_foo.test_bar.__file__)
907
938
 
908
939
    def test_loading_from___init__only(self):
909
940
        # We rename the existing __init__.py file to ensure that we don't load
911
942
        init = 'non-standard-dir/__init__.py'
912
943
        random = 'non-standard-dir/setup.py'
913
944
        os.rename(init, random)
914
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
915
 
        self.load_with_paths(['standard'])
 
945
        self.addCleanup(os.rename, random, init)
 
946
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
947
        plugin.load_plugins(['standard'])
916
948
        self.assertPluginUnknown('test_foo')
917
949
 
918
950
    def test_loading_from_specific_file(self):
925
957
''' % ('test_foo', plugin_path)
926
958
        self.create_plugin('test_foo', source=source,
927
959
                           dir=plugin_dir, file_name=plugin_file_name)
928
 
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@%s' % plugin_path)
929
 
        self.load_with_paths(['standard'])
 
960
        self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@%s' % plugin_path)
 
961
        plugin.load_plugins(['standard'])
930
962
        self.assertTestFooLoadedFrom(plugin_path)
931
963
 
932
964
 
938
970
        class DummyPlugin(object):
939
971
            __version__ = '0.1.0'
940
972
            module = DummyModule()
941
 
        self.plugin_warnings = {'bad': ['Failed to load (just testing)']}
942
 
        self.plugins = {'good': DummyPlugin()}
943
 
        self.assertEqual("""\
 
973
        def dummy_plugins():
 
974
            return { 'good': DummyPlugin() }
 
975
        self.overrideAttr(plugin, 'plugin_warnings',
 
976
            {'bad': ['Failed to load (just testing)']})
 
977
        self.overrideAttr(plugin, 'plugins', dummy_plugins)
 
978
        self.assertEquals("""\
944
979
bad (failed to load)
945
980
  ** Failed to load (just testing)
946
981
 
947
982
good 0.1.0
948
983
  Hi there
949
984
 
950
 
""", ''.join(plugin.describe_plugins(state=self)))
 
985
""", ''.join(plugin.describe_plugins()))