/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
7015.1.3 by Martin
Tweak copyright headers
1
# Copyright (C) 2005-2012, 2016 Canonical Ltd
2
# Copyright (C) 2017-2018 Breezy developers
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
3
#
750 by Martin Pool
- stubbed-out tests for python plugins
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
8
#
750 by Martin Pool
- stubbed-out tests for python plugins
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
13
#
750 by Martin Pool
- stubbed-out tests for python plugins
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
750 by Martin Pool
- stubbed-out tests for python plugins
17
18
"""Tests for plugins"""
19
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
20
import importlib
7479.2.1 by Jelmer Vernooij
Drop python2 support.
21
from io import StringIO
2967.4.5 by Daniel Watkins
Added test for badly-named plugins.
22
import logging
1185.16.83 by mbp at sourcefrog
- notes on testability of plugins
23
import os
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
24
import sys
7015.1.1 by Martin
Switch to compatible means of creating a module
25
import types
750 by Martin Pool
- stubbed-out tests for python plugins
26
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
27
import breezy
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
28
from .. import (
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
29
    osutils,
30
    plugin,
31
    tests,
32
    )
7236.3.4 by Jelmer Vernooij
Add tests.
33
from ..tests.features import pkg_resources_feature
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
34
1185.16.83 by mbp at sourcefrog
- notes on testability of plugins
35
1492 by Robert Collins
Support decoration of commands.
36
# TODO: Write a test for plugin decoration of commands.
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
37
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
38
invalidate_caches = getattr(importlib, "invalidate_caches", lambda: None)
39
40
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
41
class BaseTestPlugins(tests.TestCaseInTempDir):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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 + "."
7015.1.1 by Martin
Switch to compatible means of creating a module
48
        self.module = types.ModuleType(self.module_name)
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
79
    def load_with_paths(self, paths, warn_load_problems=True):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
80
        self.log("loading plugins!")
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
81
        plugin.load_plugins(
82
            self.update_module_paths(paths), state=self,
83
            warn_load_problems=warn_load_problems)
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
84
5086.5.8 by Vincent Ladeuil
Make sure we can load from a non-standard directory name.
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)
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
90
        if file_name is None:
91
            file_name = name + '.py'
92
        # 'source' must not fail to load
5086.1.7 by Vincent Ladeuil
Cleaner fix for bug #411413.
93
        path = osutils.pathjoin(dir, file_name)
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
94
        with open(path, 'w') as f:
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
95
            f.write(source + '\n')
96
5086.5.8 by Vincent Ladeuil
Make sure we can load from a non-standard directory name.
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,
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
107
                           file_name='__init__.py')
108
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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),
7143.15.2 by Jelmer Vernooij
Run autopep8.
118
                          os.path.join(directory, magicless_name))
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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])
7143.15.2 by Jelmer Vernooij
Run autopep8.
140
                 for k in sys.modules if k.startswith(self.module_prefix)),
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
141
            plugin_dict)
5268.6.1 by Vincent Ladeuil
Drive-by fix of the submodule leak.
142
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
143
    def assertPluginUnknown(self, name):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
144
        self.assertTrue(getattr(self.module, name, None) is None)
145
        self.assertFalse(self.module_prefix + name in sys.modules)
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
146
147
    def assertPluginKnown(self, name):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
148
        self.assertTrue(getattr(self.module, name, None) is not None)
149
        self.assertTrue(self.module_prefix + name in sys.modules)
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
150
151
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
152
class TestLoadingPlugins(BaseTestPlugins):
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
153
154
    activeattributes = {}
155
156
    def test_plugins_with_the_same_name_are_not_loaded(self):
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
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.
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
161
        tempattribute = "0"
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
162
        self.assertFalse(tempattribute in self.activeattributes)
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
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.
7143.15.2 by Jelmer Vernooij
Run autopep8.
166
        self.__class__.activeattributes[tempattribute] = []
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
167
        self.assertTrue(tempattribute in self.activeattributes)
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
168
        # create two plugin directories
169
        os.mkdir('first')
170
        os.mkdir('second')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
171
        # write a plugin that will record when its loaded in the
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
172
        # tempattribute list.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
173
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
174
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
175
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
176
        with open(os.path.join('first', 'plugin.py'), 'w') as outfile:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
177
            outfile.write(template % (tempattribute, 'first'))
178
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
179
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
180
        with open(os.path.join('second', 'plugin.py'), 'w') as outfile:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
181
            outfile.write(template % (tempattribute, 'second'))
182
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
183
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
184
        try:
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
185
            self.load_with_paths(['first', 'second'])
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
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):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
191
        self.assertFalse('breezy.plugins.pluginone' in sys.modules)
192
        self.assertFalse('breezy.plugins.plugintwo' in sys.modules)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
193
        # 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
197
        # for accessing in activeattributes. - we cannot give import parameters.
198
        tempattribute = "different-dirs"
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
199
        self.assertFalse(tempattribute in self.activeattributes)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
200
        # set a place for the plugins to record their loading, and at the same
201
        # time validate that the location the plugins should record to is
202
        # valid and correct.
7143.15.2 by Jelmer Vernooij
Run autopep8.
203
        breezy.tests.test_plugins.TestLoadingPlugins.activeattributes[tempattribute] = [
204
            ]
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
205
        self.assertTrue(tempattribute in self.activeattributes)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
206
        # create two plugin directories
207
        os.mkdir('first')
208
        os.mkdir('second')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
209
        # write plugins that will record when they are loaded in the
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
210
        # tempattribute list.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
211
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
212
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
213
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
214
        with open(os.path.join('first', 'pluginone.py'), 'w') as outfile:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
215
            outfile.write(template % (tempattribute, 'first'))
216
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
217
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
218
        with open(os.path.join('second', 'plugintwo.py'), 'w') as outfile:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
219
            outfile.write(template % (tempattribute, 'second'))
220
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
221
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
222
        try:
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
223
            self.assertPluginUnknown('pluginone')
224
            self.assertPluginUnknown('plugintwo')
225
            self.update_module_paths(['first', 'second'])
226
            exec("import %spluginone" % self.module_prefix)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
227
            self.assertEqual(['first'], self.activeattributes[tempattribute])
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
228
            exec("import %splugintwo" % self.module_prefix)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
229
            self.assertEqual(['first', 'second'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
230
                             self.activeattributes[tempattribute])
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
231
        finally:
232
            del self.activeattributes[tempattribute]
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
233
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
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.
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
237
        # check the plugin is not loaded already
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
238
        self.assertPluginUnknown('ts_plugin')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
239
        tempattribute = "trailing-slash"
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
240
        self.assertFalse(tempattribute in self.activeattributes)
2652.2.3 by Blake Winton
Understand the code and comments of the test, instead of just cargo-culting them.
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
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
243
        # valid and correct.
7143.15.2 by Jelmer Vernooij
Run autopep8.
244
        breezy.tests.test_plugins.TestLoadingPlugins.activeattributes[tempattribute] = [
245
            ]
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
246
        self.assertTrue(tempattribute in self.activeattributes)
2652.2.3 by Blake Winton
Understand the code and comments of the test, instead of just cargo-culting them.
247
        # create a directory for the plugin
248
        os.mkdir('plugin_test')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
249
        # write a plugin that will record when its loaded in the
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
250
        # tempattribute list.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
251
        template = ("from breezy.tests.test_plugins import TestLoadingPlugins\n"
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
252
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
253
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
254
        with open(os.path.join('plugin_test', 'ts_plugin.py'), 'w') as outfile:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
255
            outfile.write(template % (tempattribute, 'plugin'))
2911.6.4 by Blake Winton
Fix test failures
256
            outfile.write('\n')
2652.2.7 by Blake Winton
fix lines which were wider than 79 chars. Also handle files a little more safely.
257
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
258
        try:
7143.15.2 by Jelmer Vernooij
Run autopep8.
259
            self.load_with_paths(['plugin_test' + os.sep])
2652.2.3 by Blake Winton
Understand the code and comments of the test, instead of just cargo-culting them.
260
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
261
            self.assertPluginKnown('ts_plugin')
2652.2.1 by Blake Winton
Add a test for BZR_PLUGIN_PATH, and code and another test to allow BZR_PLUGIN_PATH to contain trailing slashes.
262
        finally:
263
            del self.activeattributes[tempattribute]
264
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
265
    def load_and_capture(self, name, warn_load_problems=True):
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
266
        """Load plugins from '.' capturing the output.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
267
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
268
        :param name: The name of the plugin.
269
        :return: A string with the log from the plugin loading call.
270
        """
2967.4.5 by Daniel Watkins
Added test for badly-named plugins.
271
        # Capture output
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
272
        stream = StringIO()
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
273
        try:
274
            handler = logging.StreamHandler(stream)
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
275
            log = logging.getLogger('brz')
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
276
            log.addHandler(handler)
277
            try:
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
278
                self.load_with_paths(
279
                    ['.'], warn_load_problems=warn_load_problems)
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
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()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
288
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
289
    def test_plugin_with_bad_api_version_reports(self):
5616.7.3 by Martin Pool
Put plugin warnings into both the apport and plain crash report
290
        """Try loading a plugin that requests an unsupported api.
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
291
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
292
        Observe that it records the problem but doesn't complain on stderr
293
        when warn_load_problems=False
5616.7.3 by Martin Pool
Put plugin warnings into both the apport and plain crash report
294
        """
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
295
        name = 'wants100.py'
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
296
        with open(name, 'w') as f:
6672.1.2 by Jelmer Vernooij
Remove breezy.api.
297
            f.write("import breezy\n"
7143.15.2 by Jelmer Vernooij
Run autopep8.
298
                    "from breezy.errors import IncompatibleVersion\n"
299
                    "raise IncompatibleVersion(breezy, [(1, 0, 0)], (0, 0, 5))\n")
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
300
        log = self.load_and_capture(name, warn_load_problems=False)
301
        self.assertNotContainsRe(log, r"It supports breezy version")
7479.2.1 by Jelmer Vernooij
Drop python2 support.
302
        self.assertEqual({'wants100'}, self.plugin_warnings.keys())
5616.7.1 by Martin Pool
Record but don't show warnings about updated plugins
303
        self.assertContainsRe(
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
304
            self.plugin_warnings['wants100'][0],
6672.1.2 by Jelmer Vernooij
Remove breezy.api.
305
            r"It supports breezy version")
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
306
307
    def test_plugin_with_bad_name_does_not_load(self):
308
        # The file name here invalid for a python module.
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
309
        name = 'brz-bad plugin-name..py'
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
310
        open(name, 'w').close()
3766.3.2 by Robert Collins
Fix reporting of incompatible api plugin load errors, fixing bug 279451.
311
        log = self.load_and_capture(name)
312
        self.assertContainsRe(log,
7143.15.2 by Jelmer Vernooij
Run autopep8.
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_'\\.")
2967.4.5 by Daniel Watkins
Added test for badly-named plugins.
316
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
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
7490.98.1 by Jelmer Vernooij
Add test for plugin that fails to load.
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')
7490.98.2 by Jelmer Vernooij
Don't hide problems from plugins by default.
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)
7490.98.1 by Jelmer Vernooij
Add test for plugin that fails to load.
333
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
334
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
335
class TestPlugins(BaseTestPlugins):
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
336
337
    def setup_plugin(self, source=""):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
338
        # This test tests a new plugin appears in breezy.plugin.plugins().
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
339
        # check the plugin is not loaded already
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
340
        self.assertPluginUnknown('plugin')
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
341
        # write a plugin that _cannot_ fail to load.
7143.15.2 by Jelmer Vernooij
Run autopep8.
342
        with open('plugin.py', 'w') as f:
343
            f.write(source + '\n')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
344
        self.load_with_paths(['.'])
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
345
6759.4.3 by Jelmer Vernooij
Avoid accessing global state.
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
6780.1.1 by Jelmer Vernooij
Check for plugin existing in sys.modules but being None.
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
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
360
    def test_plugin_appears_in_plugins(self):
361
        self.setup_plugin()
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
362
        self.assertPluginKnown('plugin')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
363
        p = self.plugins['plugin']
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
364
        self.assertIsInstance(p, breezy.plugin.PlugIn)
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
365
        self.assertIs(p.module, sys.modules[self.module_prefix + 'plugin'])
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
366
367
    def test_trivial_plugin_get_path(self):
368
        self.setup_plugin()
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
369
        p = self.plugins['plugin']
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
370
        plugin_path = self.test_dir + '/plugin.py'
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
371
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
372
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
373
    def test_plugin_get_path_py_not_pyc(self):
5086.1.3 by Vincent Ladeuil
Fix imports in test_plugins.
374
        # first import creates plugin.pyc
375
        self.setup_plugin()
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
376
        self.promote_cache(self.test_dir)
377
        self.reset()
7143.15.2 by Jelmer Vernooij
Run autopep8.
378
        self.load_with_paths(['.'])  # import plugin.pyc
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
379
        p = plugin.plugins()['plugin']
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
380
        plugin_path = self.test_dir + '/plugin.py'
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
381
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
382
383
    def test_plugin_get_path_pyc_only(self):
5086.1.3 by Vincent Ladeuil
Fix imports in test_plugins.
384
        # first import creates plugin.pyc (or plugin.pyo depending on __debug__)
385
        self.setup_plugin()
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
386
        os.unlink(self.test_dir + '/plugin.py')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
387
        self.promote_cache(self.test_dir)
388
        self.reset()
7143.15.2 by Jelmer Vernooij
Run autopep8.
389
        self.load_with_paths(['.'])  # import plugin.pyc (or .pyo)
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
390
        p = plugin.plugins()['plugin']
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
391
        plugin_path = self.test_dir + '/plugin' + plugin.COMPILED_EXT
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
392
        self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
393
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
394
    def test_no_test_suite_gives_None_for_test_suite(self):
395
        self.setup_plugin()
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
396
        p = plugin.plugins()['plugin']
397
        self.assertEqual(None, p.test_suite())
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
398
399
    def test_test_suite_gives_test_suite_result(self):
400
        source = """def test_suite(): return 'foo'"""
401
        self.setup_plugin(source)
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
402
        p = plugin.plugins()['plugin']
403
        self.assertEqual('foo', p.test_suite())
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
404
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
405
    def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
406
        self.setup_plugin()
5086.1.3 by Vincent Ladeuil
Fix imports in test_plugins.
407
        loader = tests.TestUtil.TestLoader()
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
408
        p = plugin.plugins()['plugin']
409
        self.assertEqual(None, p.load_plugin_tests(loader))
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
410
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
411
    def test_load_plugin_tests_gives_load_plugin_tests_result(self):
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
412
        source = """
6625.1.5 by Martin
Drop custom load_tests implementation and use unittest signature
413
def load_tests(loader, standard_tests, pattern):
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
414
    return 'foo'"""
415
        self.setup_plugin(source)
5086.1.3 by Vincent Ladeuil
Fix imports in test_plugins.
416
        loader = tests.TestUtil.TestLoader()
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
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())
3302.8.10 by Vincent Ladeuil
Prepare bzrlib.plugin to use the new test loader.
423
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
424
    def test_no_version_info(self):
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
425
        self.check_version_info(None)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
426
427
    def test_with_version_info(self):
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
428
        self.check_version_info((1, 2, 3, 'dev', 4),
429
                                "version_info = (1, 2, 3, 'dev', 4)")
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
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
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
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__)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
440
441
    def test_no_version_info___version__(self):
442
        self.setup_plugin()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
443
        plugin = breezy.plugin.plugins()['plugin']
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
444
        self.assertEqual("unknown", plugin.__version__)
445
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
446
    def test_str__version__with_version_info(self):
447
        self.setup_plugin("version_info = '1.2.3'")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
448
        plugin = breezy.plugin.plugins()['plugin']
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
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)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
453
        plugin = breezy.plugin.plugins()['plugin']
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
454
        self.assertEqual("1", plugin.__version__)
455
456
    def test_1__version__with_version_info(self):
457
        self.setup_plugin("version_info = (1,)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
458
        plugin = breezy.plugin.plugins()['plugin']
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
459
        self.assertEqual("1", plugin.__version__)
460
461
    def test_1_2__version__with_version_info(self):
3777.6.5 by Marius Kruger
add 2 more tests for plugin version numbers
462
        self.setup_plugin("version_info = (1, 2)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
463
        plugin = breezy.plugin.plugins()['plugin']
3777.6.5 by Marius Kruger
add 2 more tests for plugin version numbers
464
        self.assertEqual("1.2", plugin.__version__)
465
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
466
    def test_1_2_3__version__with_version_info(self):
3777.6.5 by Marius Kruger
add 2 more tests for plugin version numbers
467
        self.setup_plugin("version_info = (1, 2, 3)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
468
        plugin = breezy.plugin.plugins()['plugin']
3777.6.5 by Marius Kruger
add 2 more tests for plugin version numbers
469
        self.assertEqual("1.2.3", plugin.__version__)
470
471
    def test_candidate__version__with_version_info(self):
3777.6.4 by Marius Kruger
fix tests
472
        self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
473
        plugin = breezy.plugin.plugins()['plugin']
3777.6.4 by Marius Kruger
fix tests
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)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
478
        plugin = breezy.plugin.plugins()['plugin']
3777.6.4 by Marius Kruger
fix tests
479
        self.assertEqual("1.2.3dev", plugin.__version__)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
480
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
481
    def test_dev_fallback__version__with_version_info(self):
482
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
483
        plugin = breezy.plugin.plugins()['plugin']
4634.50.6 by John Arbash Meinel
Handle a plugin fallback versioning issue.
484
        self.assertEqual("1.2.3dev4", plugin.__version__)
3777.6.7 by Marius Kruger
* Can now also handle non-iteratable and string plugin versions.
485
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
486
    def test_final__version__with_version_info(self):
3777.6.4 by Marius Kruger
fix tests
487
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
488
        plugin = breezy.plugin.plugins()['plugin']
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
489
        self.assertEqual("1.2.3", plugin.__version__)
490
4634.50.6 by John Arbash Meinel
Handle a plugin fallback versioning issue.
491
    def test_final_fallback__version__with_version_info(self):
492
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
493
        plugin = breezy.plugin.plugins()['plugin']
5851.2.2 by Martin Pool
Format plugin version as 1.2.3.2 not 1.2.3.final.2
494
        self.assertEqual("1.2.3.2", plugin.__version__)
4634.50.6 by John Arbash Meinel
Handle a plugin fallback versioning issue.
495
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
496
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
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
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
508
    def test_get_topics_for_plugin(self):
509
        """Searching for plugin name gets its docstring."""
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
510
        index = plugin.PluginsHelpIndex()
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
511
        # make a new plugin here for this test, even if we're run with
512
        # --no-plugins
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
513
        self.assertFalse('breezy.plugins.demo_module' in sys.modules)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
514
        demo_module = FakeModule('', 'breezy.plugins.demo_module')
515
        sys.modules['breezy.plugins.demo_module'] = demo_module
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
516
        try:
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
517
            topics = index.get_topics('demo_module')
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
518
            self.assertEqual(1, len(topics))
519
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
520
            self.assertEqual(demo_module, topics[0].module)
521
        finally:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
522
            del sys.modules['breezy.plugins.demo_module']
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
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
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
536
    def test_get_plugin_topic_with_prefix(self):
537
        """Searching for plugins/demo_module returns help."""
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
538
        index = plugin.PluginsHelpIndex()
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
539
        self.assertFalse('breezy.plugins.demo_module' in sys.modules)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
540
        demo_module = FakeModule('', 'breezy.plugins.demo_module')
541
        sys.modules['breezy.plugins.demo_module'] = demo_module
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
542
        try:
2475.1.1 by Martin Pool
Rename test_plugin tests and the example module used there.
543
            topics = index.get_topics('plugins/demo_module')
2457.1.1 by Robert Collins
(robertc) Fix bzr --no-plugins selftest which was broken by the help indices patch. (Robert Collins, Martin Pool)
544
            self.assertEqual(1, len(topics))
545
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
546
            self.assertEqual(demo_module, topics[0].module)
547
        finally:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
548
            del sys.modules['breezy.plugins.demo_module']
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
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",
7143.15.2 by Jelmer Vernooij
Run autopep8.
573
                         topic.get_help_text())
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
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",
7143.15.2 by Jelmer Vernooij
Run autopep8.
580
                         topic.get_help_text())
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
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",
7143.15.2 by Jelmer Vernooij
Run autopep8.
587
                         topic.get_help_text())
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
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)
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
592
        self.assertEqual(
593
            "two lines of help\nand more\n\n:See also: bar, foo\n",
594
            topic.get_help_text(['foo', 'bar']))
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
595
596
    def test_get_help_topic(self):
597
        """The help topic for a plugin is its module name."""
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
598
        mod = FakeModule('two lines of help\nand more', 'breezy.plugins.demo')
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
599
        topic = plugin.ModuleHelpTopic(mod)
600
        self.assertEqual('demo', topic.get_help_topic())
6059.3.6 by Vincent Ladeuil
Fix tests failing on pqm.
601
        mod = FakeModule('two lines of help\nand more',
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
602
                         'breezy.plugins.foo_bar')
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
603
        topic = plugin.ModuleHelpTopic(mod)
604
        self.assertEqual('foo_bar', topic.get_help_topic())
3835.2.7 by Aaron Bentley
Add tests for plugins
605
606
5086.1.2 by Vincent Ladeuil
Cosmetic changes.
607
class TestEnvPluginPath(tests.TestCase):
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
608
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
609
    user = "USER"
610
    core = "CORE"
611
    site = "SITE"
7236.3.2 by Jelmer Vernooij
Fix tests.
612
    entrypoints = "ENTRYPOINTS"
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
613
614
    def check_path(self, expected_dirs, setting_dirs):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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())
7143.15.2 by Jelmer Vernooij
Run autopep8.
620
                  for p, t in plugin._env_plugin_path()]
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
621
        self.assertEqual(expected_dirs, actual)
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
622
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
623
    def test_default(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
624
        self.check_path([self.user, self.core, self.site], None)
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
625
626
    def test_adhoc_policy(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
627
        self.check_path([self.user, self.core, self.site],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
628
                        ['+user', '+core', '+site'])
629
630
    def test_fallback_policy(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
631
        self.check_path([self.core, self.site, self.user],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
632
                        ['+core', '+site', '+user'])
633
634
    def test_override_policy(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
635
        self.check_path([self.user, self.site, self.core],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
636
                        ['+user', '+site', '+core'])
637
7290.33.3 by Jelmer Vernooij
Fix tests.
638
    def test_enable_entrypoints(self):
639
        self.check_path([self.user, self.core, self.site, self.entrypoints],
640
                        ['+user', '+core', '+site', '+entrypoints'])
641
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
642
    def test_disable_user(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
643
        self.check_path([self.core, self.site], ['-user'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
644
645
    def test_disable_user_twice(self):
646
        # Ensures multiple removals don't left cruft
7290.33.3 by Jelmer Vernooij
Fix tests.
647
        self.check_path([self.core, self.site], ['-user', '-user'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
648
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
649
    def test_duplicates_are_removed(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
650
        self.check_path([self.user, self.core, self.site],
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
651
                        ['+user', '+user'])
652
        # And only the first reference is kept (since the later references will
5086.1.2 by Vincent Ladeuil
Cosmetic changes.
653
        # only produce '<plugin> already loaded' mutters)
7290.33.3 by Jelmer Vernooij
Fix tests.
654
        self.check_path([self.user, self.core, self.site],
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
655
                        ['+user', '+user', '+core',
656
                         '+user', '+site', '+site',
657
                         '+core'])
658
5086.1.5 by Vincent Ladeuil
Fix typo in test name.
659
    def test_disable_overrides_enable(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
660
        self.check_path([self.core, self.site], ['-user', '+user'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
661
662
    def test_disable_core(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
663
        self.check_path([self.site], ['-core'])
664
        self.check_path([self.user, self.site], ['+user', '-core'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
665
666
    def test_disable_site(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
667
        self.check_path([self.core], ['-site'])
668
        self.check_path([self.user, self.core], ['-site', '+user'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
669
670
    def test_override_site(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
671
        self.check_path(['mysite', self.user, self.core],
4628.2.3 by Vincent Ladeuil
Update doc and add NEWS entry.
672
                        ['mysite', '-site', '+user'])
7290.33.3 by Jelmer Vernooij
Fix tests.
673
        self.check_path(['mysite', self.core],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
674
                        ['mysite', '-site'])
675
676
    def test_override_core(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
677
        self.check_path(['mycore', self.user, self.site],
4628.2.3 by Vincent Ladeuil
Update doc and add NEWS entry.
678
                        ['mycore', '-core', '+user', '+site'])
7290.33.3 by Jelmer Vernooij
Fix tests.
679
        self.check_path(['mycore', self.site],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
680
                        ['mycore', '-core'])
681
682
    def test_my_plugin_only(self):
7236.3.2 by Jelmer Vernooij
Fix tests.
683
        self.check_path(
684
            ['myplugin'],
685
            ['myplugin', '-user', '-core', '-site', '-entrypoints'])
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
686
687
    def test_my_plugin_first(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
688
        self.check_path(['myplugin', self.core, self.site, self.user],
4628.2.2 by Vincent Ladeuil
Add [+-]{user|core|site} handling in BZR_PLUGIN_PATH.
689
                        ['myplugin', '+core', '+site', '+user'])
4628.2.1 by Vincent Ladeuil
Start introducing accessors for plugin paths.
690
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
691
    def test_bogus_references(self):
7290.33.3 by Jelmer Vernooij
Fix tests.
692
        self.check_path(['+foo', '-bar', self.core, self.site],
4628.2.5 by Vincent Ladeuil
Fixes prompted by review.
693
                        ['+foo', '-bar'])
5086.1.4 by Vincent Ladeuil
Slight plugin tests rewriting.
694
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
695
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
696
class TestDisablePlugin(BaseTestPlugins):
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
697
5086.1.8 by Vincent Ladeuil
Fix warnings during autoload, add doc and a NEWS entry.
698
    def test_cannot_import(self):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
704
        try:
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
705
            import breezy.testingplugins.fails as fails
5086.1.6 by Vincent Ladeuil
Crude fix for bug #411413.
706
        except ImportError:
707
            pass
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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(['.'])
7479.2.1 by Jelmer Vernooij
Drop python2 support.
718
        self.assertEqual({'good'}, self.plugins.keys())
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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))
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
751
        self.assertContainsRe(
752
            self.get_log(),
753
            r"Invalid name 'in-valid' in BRZ_DISABLE_PLUGINS=" + repr(value))
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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())
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
764
        self.assertEqual([], self._get_paths(''))
5268.5.1 by Vincent Ladeuil
Reproduce bug #591215.
765
766
    def test_one_path(self):
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
767
        self.assertEqual([('b', 'man')], self._get_paths('b@man'))
5268.5.1 by Vincent Ladeuil
Reproduce bug #591215.
768
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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'))
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
787
        self.assertContainsRe(
788
            self.get_log(),
789
            r"Invalid name 'bzr-git' in BRZ_PLUGINS_AT='/usr/local/bzr-git'")
5268.5.1 by Vincent Ladeuil
Reproduce bug #591215.
790
791
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
792
class TestLoadPluginAt(BaseTestPlugins):
5086.5.3 by Vincent Ladeuil
First shot at loading plugins from a specific directory.
793
794
    def setUp(self):
795
        super(TestLoadPluginAt, self).setUp()
796
        # Create the same plugin in two directories
5086.5.8 by Vincent Ladeuil
Make sure we can load from a non-standard directory name.
797
        self.create_plugin_package('test_foo', dir='non-standard-dir')
5086.5.13 by Vincent Ladeuil
Reproduce bug #552922.
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')
5086.5.8 by Vincent Ladeuil
Make sure we can load from a non-standard directory name.
801
5086.5.14 by Vincent Ladeuil
Fix bug #552922 by controlling which files can be used to load a plugin.
802
    def assertTestFooLoadedFrom(self, path):
5086.5.8 by Vincent Ladeuil
Make sure we can load from a non-standard directory name.
803
        self.assertPluginKnown('test_foo')
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
804
        self.assertDocstring('This is the doc for test_foo',
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
805
                             self.module.test_foo)
806
        self.assertEqual(path, self.module.test_foo.dir_source)
5086.5.3 by Vincent Ladeuil
First shot at loading plugins from a specific directory.
807
808
    def test_regular_load(self):
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
809
        self.load_with_paths(['standard'])
5086.5.13 by Vincent Ladeuil
Reproduce bug #552922.
810
        self.assertTestFooLoadedFrom('standard/test_foo')
5086.5.3 by Vincent Ladeuil
First shot at loading plugins from a specific directory.
811
812
    def test_import(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
813
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
814
        self.update_module_paths(['standard'])
815
        import breezy.testingplugins.test_foo
5086.5.8 by Vincent Ladeuil
Make sure we can load from a non-standard directory name.
816
        self.assertTestFooLoadedFrom('non-standard-dir')
817
818
    def test_loading(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
819
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
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'])
5086.5.9 by Vincent Ladeuil
More tests.
827
        self.assertTestFooLoadedFrom('non-standard-dir')
828
829
    def test_compiled_loaded(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
830
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
831
        self.load_with_paths(['standard'])
5086.5.9 by Vincent Ladeuil
More tests.
832
        self.assertTestFooLoadedFrom('non-standard-dir')
5235.1.1 by Martin
Make BZR_PLUGINS_AT tests that check filenames use a path-based assertion method rather than just string comparison
833
        self.assertIsSameRealPath('non-standard-dir/__init__.py',
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
834
                                  self.module.test_foo.__file__)
5086.5.9 by Vincent Ladeuil
More tests.
835
836
        # Try importing again now that the source has been compiled
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
837
        os.remove('non-standard-dir/__init__.py')
838
        self.promote_cache('non-standard-dir')
839
        self.reset()
840
        self.load_with_paths(['standard'])
5086.5.9 by Vincent Ladeuil
More tests.
841
        self.assertTestFooLoadedFrom('non-standard-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
842
        suffix = plugin.COMPILED_EXT
843
        self.assertIsSameRealPath('non-standard-dir/__init__' + suffix,
844
                                  self.module.test_foo.__file__)
5086.5.9 by Vincent Ladeuil
More tests.
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')
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
849
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
850
        self.update_module_paths(['standard'])
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
851
        import breezy.testingplugins.test_foo  # noqa: F401
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
852
        self.assertEqual(self.module_prefix + 'test_foo',
853
                         self.module.test_foo.__package__)
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
854
        import breezy.testingplugins.test_foo.test_bar  # noqa: F401
5235.1.1 by Martin
Make BZR_PLUGINS_AT tests that check filenames use a path-based assertion method rather than just string comparison
855
        self.assertIsSameRealPath('non-standard-dir/test_bar/__init__.py',
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
856
                                  self.module.test_foo.test_bar.__file__)
5086.5.13 by Vincent Ladeuil
Reproduce bug #552922.
857
5268.6.2 by Vincent Ladeuil
Reproduce bug #588959.
858
    def test_relative_submodule_loading(self):
859
        self.create_plugin_package('test_foo', dir='another-dir', source='''
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
860
from . import test_bar
5268.6.2 by Vincent Ladeuil
Reproduce bug #588959.
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')
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
864
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@another-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
865
        self.update_module_paths(['standard'])
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
866
        import breezy.testingplugins.test_foo  # noqa: F401
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
867
        self.assertEqual(self.module_prefix + 'test_foo',
868
                         self.module.test_foo.__package__)
5268.6.2 by Vincent Ladeuil
Reproduce bug #588959.
869
        self.assertIsSameRealPath('another-dir/test_bar/__init__.py',
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
870
                                  self.module.test_foo.test_bar.__file__)
5268.6.2 by Vincent Ladeuil
Reproduce bug #588959.
871
5086.5.15 by Vincent Ladeuil
Fixed as per Ian's review.
872
    def test_loading_from___init__only(self):
5086.5.13 by Vincent Ladeuil
Reproduce bug #552922.
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)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
878
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
879
        self.load_with_paths(['standard'])
5086.5.13 by Vincent Ladeuil
Reproduce bug #552922.
880
        self.assertPluginUnknown('test_foo')
5086.5.14 by Vincent Ladeuil
Fix bug #552922 by controlling which files can be used to load a plugin.
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)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
892
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@%s' % plugin_path)
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
893
        self.load_with_paths(['standard'])
5086.5.14 by Vincent Ladeuil
Fix bug #552922 by controlling which files can be used to load a plugin.
894
        self.assertTestFooLoadedFrom(plugin_path)
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
895
896
897
class TestDescribePlugins(BaseTestPlugins):
898
899
    def test_describe_plugins(self):
5616.7.11 by Martin Pool
Additional tests and fixes for refactored describe_plugins.
900
        class DummyModule(object):
901
            __doc__ = 'Hi there'
7143.15.2 by Jelmer Vernooij
Run autopep8.
902
5616.7.11 by Martin Pool
Additional tests and fixes for refactored describe_plugins.
903
        class DummyPlugin(object):
904
            __version__ = '0.1.0'
905
            module = DummyModule()
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
906
        self.plugin_warnings = {'bad': ['Failed to load (just testing)']}
907
        self.plugins = {'good': DummyPlugin()}
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
908
        self.assertEqual("""\
5616.7.10 by Martin Pool
Clean up describe_plugins to sort loaded and unloaded plugins together.
909
bad (failed to load)
910
  ** Failed to load (just testing)
911
5616.7.11 by Martin Pool
Additional tests and fixes for refactored describe_plugins.
912
good 0.1.0
913
  Hi there
914
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
915
""", ''.join(plugin.describe_plugins(state=self)))
7236.3.4 by Jelmer Vernooij
Add tests.
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}}
7236.3.7 by Jelmer Vernooij
Fix tests.
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])
7236.3.4 by Jelmer Vernooij
Add tests.
939
        self.load_with_paths(['.'])
940
        self.addCleanup(d._ep_map.clear)
941
942
    def test_plugin_loaded(self):
943
        self.assertPluginUnknown('plugin')
7290.33.3 by Jelmer Vernooij
Fix tests.
944
        self.overrideEnv('BRZ_PLUGIN_PATH', '+entrypoints')
7236.3.4 by Jelmer Vernooij
Add tests.
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')
7290.33.3 by Jelmer Vernooij
Fix tests.
952
        self.overrideEnv('BRZ_PLUGIN_PATH', '+entrypoints')
7236.3.4 by Jelmer Vernooij
Add tests.
953
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'plugin')
954
        self.setup_plugin()
955
        self.assertNotIn('plugin', self.plugins)