1
# Copyright (C) 2005 by Canonical Ltd
1
# Copyright (C) 2005-2011 Canonical Ltd
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
17
"""Tests for plugins"""
28
from bzrlib.selftest import InTempDir
31
def PluginTest(InTempDir):
32
"""Create an external plugin and test loading."""
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
23
from cStringIO import StringIO
39
# TODO: Write a test for plugin decoration of commands.
41
class BaseTestPlugins(tests.TestCaseInTempDir):
43
def create_plugin(self, name, source=None, dir='.', file_name=None):
46
"""This is the doc for %s"""
49
file_name = name + '.py'
50
# 'source' must not fail to load
51
path = osutils.pathjoin(dir, file_name)
53
self.addCleanup(os.unlink, path)
55
f.write(source + '\n')
59
def create_plugin_package(self, name, dir=None, source=None):
64
"""This is the doc for %s"""
69
# Workaround lazy import random? madness
71
self.addCleanup(cleanup)
72
self.create_plugin(name, source, dir,
73
file_name='__init__.py')
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)
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)
93
def assertPluginUnknown(self, name):
94
self.assertFalse(getattr(bzrlib.plugins, name, None) is not None)
95
self.assertFalse('bzrlib.plugins.%s' % name in sys.modules)
97
def assertPluginKnown(self, name):
98
self.assertTrue(getattr(bzrlib.plugins, name, None) is not None)
99
self.assertTrue('bzrlib.plugins.%s' % name in sys.modules)
102
class TestLoadingPlugins(BaseTestPlugins):
104
activeattributes = {}
106
def test_plugins_with_the_same_name_are_not_loaded(self):
107
# This test tests that having two plugins in different directories does
108
# not result in both being loaded when they have the same name. get a
109
# file name we can use which is also a valid attribute for accessing in
110
# activeattributes. - we cannot give import parameters.
112
self.assertFalse(tempattribute in self.activeattributes)
113
# set a place for the plugins to record their loading, and at the same
114
# time validate that the location the plugins should record to is
116
self.__class__.activeattributes [tempattribute] = []
117
self.assertTrue(tempattribute in self.activeattributes)
118
# create two plugin directories
121
# write a plugin that will record when its loaded in the
122
# tempattribute list.
123
template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
124
"TestLoadingPlugins.activeattributes[%r].append('%s')\n")
126
outfile = open(os.path.join('first', 'plugin.py'), 'w')
128
outfile.write(template % (tempattribute, 'first'))
133
outfile = open(os.path.join('second', 'plugin.py'), 'w')
135
outfile.write(template % (tempattribute, 'second'))
141
bzrlib.plugin.load_from_path(['first', 'second'])
142
self.assertEqual(['first'], self.activeattributes[tempattribute])
144
# remove the plugin 'plugin'
145
del self.activeattributes[tempattribute]
146
self._unregister_plugin('plugin')
147
self.assertPluginUnknown('plugin')
149
def test_plugins_from_different_dirs_can_demand_load(self):
150
self.assertFalse('bzrlib.plugins.pluginone' in sys.modules)
151
self.assertFalse('bzrlib.plugins.plugintwo' in sys.modules)
152
# This test tests that having two plugins in different
153
# directories with different names allows them both to be loaded, when
154
# we do a direct import statement.
155
# Determine a file name we can use which is also a valid attribute
156
# for accessing in activeattributes. - we cannot give import parameters.
157
tempattribute = "different-dirs"
158
self.assertFalse(tempattribute in self.activeattributes)
159
# set a place for the plugins to record their loading, and at the same
160
# time validate that the location the plugins should record to is
162
bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
164
self.assertTrue(tempattribute in self.activeattributes)
165
# create two plugin directories
168
# write plugins that will record when they are loaded in the
169
# tempattribute list.
170
template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
171
"TestLoadingPlugins.activeattributes[%r].append('%s')\n")
173
outfile = open(os.path.join('first', 'pluginone.py'), 'w')
175
outfile.write(template % (tempattribute, 'first'))
180
outfile = open(os.path.join('second', 'plugintwo.py'), 'w')
182
outfile.write(template % (tempattribute, 'second'))
187
oldpath = bzrlib.plugins.__path__
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"
193
self.assertEqual(['first'], self.activeattributes[tempattribute])
194
exec "import bzrlib.plugins.plugintwo"
195
self.assertEqual(['first', 'second'],
196
self.activeattributes[tempattribute])
198
# remove the plugin 'plugin'
199
del self.activeattributes[tempattribute]
200
self._unregister_plugin('pluginone')
201
self._unregister_plugin('plugintwo')
202
self.assertPluginUnknown('pluginone')
203
self.assertPluginUnknown('plugintwo')
205
def test_plugins_can_load_from_directory_with_trailing_slash(self):
206
# This test tests that a plugin can load from a directory when the
207
# directory in the path has a trailing slash.
208
# check the plugin is not loaded already
209
self.assertPluginUnknown('ts_plugin')
210
tempattribute = "trailing-slash"
211
self.assertFalse(tempattribute in self.activeattributes)
212
# set a place for the plugin to record its loading, and at the same
213
# time validate that the location the plugin should record to is
215
bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
217
self.assertTrue(tempattribute in self.activeattributes)
218
# create a directory for the plugin
219
os.mkdir('plugin_test')
220
# write a plugin that will record when its loaded in the
221
# tempattribute list.
222
template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
223
"TestLoadingPlugins.activeattributes[%r].append('%s')\n")
225
outfile = open(os.path.join('plugin_test', 'ts_plugin.py'), 'w')
227
outfile.write(template % (tempattribute, 'plugin'))
233
bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
234
self.assertEqual(['plugin'], self.activeattributes[tempattribute])
236
del self.activeattributes[tempattribute]
237
self._unregister_plugin('ts_plugin')
238
self.assertPluginUnknown('ts_plugin')
240
def load_and_capture(self, name):
241
"""Load plugins from '.' capturing the output.
243
:param name: The name of the plugin.
244
:return: A string with the log from the plugin loading call.
249
handler = logging.StreamHandler(stream)
250
log = logging.getLogger('bzr')
251
log.addHandler(handler)
254
bzrlib.plugin.load_from_path(['.'])
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)
261
# Stop capturing output
264
log.removeHandler(handler)
265
return stream.getvalue()
269
def test_plugin_with_bad_api_version_reports(self):
270
"""Try loading a plugin that requests an unsupported api.
36
orig_help = self.backtick('bzr help commands') # No plugins yet
272
Observe that it records the problem but doesn't complain on stderr.
274
See https://bugs.launchpad.net/bzr/+bug/704195
276
self.overrideAttr(plugin, 'plugin_warnings', {})
280
f.write("import bzrlib.api\n"
281
"bzrlib.api.require_any_api(bzrlib, [(1, 0, 0)])\n")
284
log = self.load_and_capture(name)
285
self.assertNotContainsRe(log,
286
r"It requested API version")
289
plugin.plugin_warnings.keys())
290
self.assertContainsRe(
291
plugin.plugin_warnings['wants100'][0],
292
r"It requested API version")
294
def test_plugin_with_bad_name_does_not_load(self):
295
# The file name here invalid for a python module.
296
name = 'bzr-bad plugin-name..py'
297
file(name, 'w').close()
298
log = self.load_and_capture(name)
299
self.assertContainsRe(log,
300
r"Unable to load 'bzr-bad plugin-name\.' in '\.' as a plugin "
301
"because the file path isn't a valid module name; try renaming "
302
"it to 'bad_plugin_name_'\.")
305
class TestPlugins(BaseTestPlugins):
307
def setup_plugin(self, source=""):
308
# This test tests a new plugin appears in bzrlib.plugin.plugins().
309
# check the plugin is not loaded already
310
self.assertPluginUnknown('plugin')
311
# write a plugin that _cannot_ fail to load.
312
file('plugin.py', 'w').write(source + '\n')
313
self.addCleanup(self.teardown_plugin)
314
plugin.load_from_path(['.'])
316
def teardown_plugin(self):
317
self._unregister_plugin('plugin')
318
self.assertPluginUnknown('plugin')
320
def test_plugin_appears_in_plugins(self):
322
self.assertPluginKnown('plugin')
323
p = plugin.plugins()['plugin']
324
self.assertIsInstance(p, bzrlib.plugin.PlugIn)
325
self.assertEqual(p.module, plugins.plugin)
327
def test_trivial_plugin_get_path(self):
329
p = plugin.plugins()['plugin']
330
plugin_path = self.test_dir + '/plugin.py'
331
self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
333
def test_plugin_get_path_py_not_pyc(self):
334
# first import creates plugin.pyc
336
self.teardown_plugin()
337
plugin.load_from_path(['.']) # import plugin.pyc
338
p = plugin.plugins()['plugin']
339
plugin_path = self.test_dir + '/plugin.py'
340
self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
342
def test_plugin_get_path_pyc_only(self):
343
# first import creates plugin.pyc (or plugin.pyo depending on __debug__)
345
self.teardown_plugin()
346
os.unlink(self.test_dir + '/plugin.py')
347
plugin.load_from_path(['.']) # import plugin.pyc (or .pyo)
348
p = plugin.plugins()['plugin']
350
plugin_path = self.test_dir + '/plugin.pyc'
352
plugin_path = self.test_dir + '/plugin.pyo'
353
self.assertIsSameRealPath(plugin_path, osutils.normpath(p.path()))
355
def test_no_test_suite_gives_None_for_test_suite(self):
357
p = plugin.plugins()['plugin']
358
self.assertEqual(None, p.test_suite())
360
def test_test_suite_gives_test_suite_result(self):
361
source = """def test_suite(): return 'foo'"""
362
self.setup_plugin(source)
363
p = plugin.plugins()['plugin']
364
self.assertEqual('foo', p.test_suite())
366
def test_no_load_plugin_tests_gives_None_for_load_plugin_tests(self):
368
loader = tests.TestUtil.TestLoader()
369
p = plugin.plugins()['plugin']
370
self.assertEqual(None, p.load_plugin_tests(loader))
372
def test_load_plugin_tests_gives_load_plugin_tests_result(self):
374
def load_tests(standard_tests, module, loader):
376
self.setup_plugin(source)
377
loader = tests.TestUtil.TestLoader()
378
p = plugin.plugins()['plugin']
379
self.assertEqual('foo', p.load_plugin_tests(loader))
381
def check_version_info(self, expected, source='', name='plugin'):
382
self.setup_plugin(source)
383
self.assertEqual(expected, plugin.plugins()[name].version_info())
385
def test_no_version_info(self):
386
self.check_version_info(None)
388
def test_with_version_info(self):
389
self.check_version_info((1, 2, 3, 'dev', 4),
390
"version_info = (1, 2, 3, 'dev', 4)")
392
def test_short_version_info_gets_padded(self):
393
# the gtk plugin has version_info = (1,2,3) rather than the 5-tuple.
395
self.check_version_info((1, 2, 3, 'final', 0),
396
"version_info = (1, 2, 3)")
398
def check_version(self, expected, source=None, name='plugin'):
399
self.setup_plugin(source)
400
self.assertEqual(expected, plugins[name].__version__)
402
def test_no_version_info___version__(self):
404
plugin = bzrlib.plugin.plugins()['plugin']
405
self.assertEqual("unknown", plugin.__version__)
407
def test_str__version__with_version_info(self):
408
self.setup_plugin("version_info = '1.2.3'")
409
plugin = bzrlib.plugin.plugins()['plugin']
410
self.assertEqual("1.2.3", plugin.__version__)
412
def test_noniterable__version__with_version_info(self):
413
self.setup_plugin("version_info = (1)")
414
plugin = bzrlib.plugin.plugins()['plugin']
415
self.assertEqual("1", plugin.__version__)
417
def test_1__version__with_version_info(self):
418
self.setup_plugin("version_info = (1,)")
419
plugin = bzrlib.plugin.plugins()['plugin']
420
self.assertEqual("1", plugin.__version__)
422
def test_1_2__version__with_version_info(self):
423
self.setup_plugin("version_info = (1, 2)")
424
plugin = bzrlib.plugin.plugins()['plugin']
425
self.assertEqual("1.2", plugin.__version__)
427
def test_1_2_3__version__with_version_info(self):
428
self.setup_plugin("version_info = (1, 2, 3)")
429
plugin = bzrlib.plugin.plugins()['plugin']
430
self.assertEqual("1.2.3", plugin.__version__)
432
def test_candidate__version__with_version_info(self):
433
self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
434
plugin = bzrlib.plugin.plugins()['plugin']
435
self.assertEqual("1.2.3rc1", plugin.__version__)
437
def test_dev__version__with_version_info(self):
438
self.setup_plugin("version_info = (1, 2, 3, 'dev', 0)")
439
plugin = bzrlib.plugin.plugins()['plugin']
440
self.assertEqual("1.2.3dev", plugin.__version__)
442
def test_dev_fallback__version__with_version_info(self):
443
self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
444
plugin = bzrlib.plugin.plugins()['plugin']
445
self.assertEqual("1.2.3dev4", plugin.__version__)
447
def test_final__version__with_version_info(self):
448
self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
449
plugin = bzrlib.plugin.plugins()['plugin']
450
self.assertEqual("1.2.3", plugin.__version__)
452
def test_final_fallback__version__with_version_info(self):
453
self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
454
plugin = bzrlib.plugin.plugins()['plugin']
455
self.assertEqual("1.2.3.2", plugin.__version__)
458
class TestPluginHelp(tests.TestCaseInTempDir):
460
def split_help_commands(self):
463
out, err = self.run_bzr('--no-plugins help commands')
464
for line in out.splitlines():
465
if not line.startswith(' '):
466
current = line.split()[0]
467
help[current] = help.get(current, '') + line
471
def test_plugin_help_builtins_unaffected(self):
472
# Check we don't get false positives
473
help_commands = self.split_help_commands()
474
for cmd_name in bzrlib.commands.builtin_command_names():
475
if cmd_name in bzrlib.commands.plugin_command_names():
478
help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
479
except NotImplementedError:
480
# some commands have no help
483
self.assertNotContainsRe(help, 'plugin "[^"]*"')
485
if cmd_name in help_commands.keys():
486
# some commands are hidden
487
help = help_commands[cmd_name]
488
self.assertNotContainsRe(help, 'plugin "[^"]*"')
490
def test_plugin_help_shows_plugin(self):
491
# Create a test plugin
37
492
os.mkdir('plugin_test')
38
f = open(os.path.join('plugin_test', 'myplug.py'), 'wt')
42
newhelp = backtick('bzr help commands')
43
assert newhelp.startswith('You have been overridden\n')
44
# We added a line, but the rest should work
45
assert newhelp[25:] == help
47
assert backtick('bzr commit -m test') == "I'm sorry dave, you can't do that\n"
49
shutil.rmtree('plugin_test')
55
"""import bzrlib, bzrlib.commands
56
class cmd_myplug(bzrlib.commands.Command):
57
'''Just a simple test plugin.'''
493
f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
495
from bzrlib import commands
496
class cmd_myplug(commands.Command):
497
__doc__ = '''Just a simple test plugin.'''
58
498
aliases = ['mplg']
60
500
print 'Hello from my plugin'
64
os.environ['BZRPLUGINPATH'] = os.path.abspath('plugin_test')
65
help = backtick('bzr help commands')
66
assert help.find('myplug') != -1
67
assert help.find('Just a simple test plugin.') != -1
70
assert backtick('bzr myplug') == 'Hello from my plugin\n'
71
assert backtick('bzr mplg') == 'Hello from my plugin\n'
73
f = open(os.path.join('plugin_test', 'override.py'), 'wb')
74
f.write("""import bzrlib, bzrlib.commands
75
class cmd_commit(bzrlib.commands.cmd_commit):
76
'''Commit changes into a new revision.'''
77
def run(self, *args, **kwargs):
78
print "I'm sorry dave, you can't do that"
80
class cmd_help(bzrlib.commands.cmd_help):
81
'''Show help on a command or other topic.'''
82
def run(self, *args, **kwargs):
83
print "You have been overridden"
84
bzrlib.commands.cmd_help.run(self, *args, **kwargs)
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\]')
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')
523
class TestHelpIndex(tests.TestCase):
524
"""Tests for the PluginsHelpIndex class."""
526
def test_default_constructable(self):
527
index = plugin.PluginsHelpIndex()
529
def test_get_topics_None(self):
530
"""Searching for None returns an empty list."""
531
index = plugin.PluginsHelpIndex()
532
self.assertEqual([], index.get_topics(None))
534
def test_get_topics_for_plugin(self):
535
"""Searching for plugin name gets its docstring."""
536
index = plugin.PluginsHelpIndex()
537
# make a new plugin here for this test, even if we're run with
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
543
topics = index.get_topics('demo_module')
544
self.assertEqual(1, len(topics))
545
self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
546
self.assertEqual(demo_module, topics[0].module)
548
del sys.modules['bzrlib.plugins.demo_module']
550
def test_get_topics_no_topic(self):
551
"""Searching for something that is not a plugin returns []."""
552
# test this by using a name that cannot be a plugin - its not
553
# a valid python identifier.
554
index = plugin.PluginsHelpIndex()
555
self.assertEqual([], index.get_topics('nothing by this name'))
557
def test_prefix(self):
558
"""PluginsHelpIndex has a prefix of 'plugins/'."""
559
index = plugin.PluginsHelpIndex()
560
self.assertEqual('plugins/', index.prefix)
562
def test_get_plugin_topic_with_prefix(self):
563
"""Searching for plugins/demo_module returns help."""
564
index = plugin.PluginsHelpIndex()
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
569
topics = index.get_topics('plugins/demo_module')
570
self.assertEqual(1, len(topics))
571
self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
572
self.assertEqual(demo_module, topics[0].module)
574
del sys.modules['bzrlib.plugins.demo_module']
577
class FakeModule(object):
578
"""A fake module to test with."""
580
def __init__(self, doc, name):
585
class TestModuleHelpTopic(tests.TestCase):
586
"""Tests for the ModuleHelpTopic class."""
588
def test_contruct(self):
589
"""Construction takes the module to document."""
590
mod = FakeModule('foo', 'foo')
591
topic = plugin.ModuleHelpTopic(mod)
592
self.assertEqual(mod, topic.module)
594
def test_get_help_text_None(self):
595
"""A ModuleHelpTopic returns the docstring for get_help_text."""
596
mod = FakeModule(None, 'demo')
597
topic = plugin.ModuleHelpTopic(mod)
598
self.assertEqual("Plugin 'demo' has no docstring.\n",
599
topic.get_help_text())
601
def test_get_help_text_no_carriage_return(self):
602
"""ModuleHelpTopic.get_help_text adds a \n if needed."""
603
mod = FakeModule('one line of help', 'demo')
604
topic = plugin.ModuleHelpTopic(mod)
605
self.assertEqual("one line of help\n",
606
topic.get_help_text())
608
def test_get_help_text_carriage_return(self):
609
"""ModuleHelpTopic.get_help_text adds a \n if needed."""
610
mod = FakeModule('two lines of help\nand more\n', 'demo')
611
topic = plugin.ModuleHelpTopic(mod)
612
self.assertEqual("two lines of help\nand more\n",
613
topic.get_help_text())
615
def test_get_help_text_with_additional_see_also(self):
616
mod = FakeModule('two lines of help\nand more', 'demo')
617
topic = plugin.ModuleHelpTopic(mod)
618
self.assertEqual("two lines of help\nand more\nSee also: bar, foo\n",
619
topic.get_help_text(['foo', 'bar']))
621
def test_get_help_topic(self):
622
"""The help topic for a plugin is its module name."""
623
mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
624
topic = plugin.ModuleHelpTopic(mod)
625
self.assertEqual('demo', topic.get_help_topic())
626
mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
627
topic = plugin.ModuleHelpTopic(mod)
628
self.assertEqual('foo_bar', topic.get_help_topic())
631
class TestLoadFromPath(tests.TestCaseInTempDir):
634
super(TestLoadFromPath, self).setUp()
635
# Change bzrlib.plugin to think no plugins have been loaded yet.
636
self.overrideAttr(bzrlib.plugins, '__path__', [])
637
self.overrideAttr(plugin, '_loaded', False)
639
# Monkey-patch load_from_path to stop it from actually loading anything.
640
self.overrideAttr(plugin, 'load_from_path', lambda dirs: None)
642
def test_set_plugins_path_with_args(self):
643
plugin.set_plugins_path(['a', 'b'])
644
self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
646
def test_set_plugins_path_defaults(self):
647
plugin.set_plugins_path()
648
self.assertEqual(plugin.get_standard_plugins_path(),
649
bzrlib.plugins.__path__)
651
def test_get_standard_plugins_path(self):
652
path = plugin.get_standard_plugins_path()
653
for directory in path:
654
self.assertNotContainsRe(directory, r'\\/$')
656
from distutils.sysconfig import get_python_lib
660
if sys.platform != 'win32':
661
python_lib = get_python_lib()
662
for directory in path:
663
if directory.startswith(python_lib):
666
self.fail('No path to global plugins')
668
def test_get_standard_plugins_path_env(self):
669
self.overrideEnv('BZR_PLUGIN_PATH', 'foo/')
670
path = plugin.get_standard_plugins_path()
671
for directory in path:
672
self.assertNotContainsRe(directory, r'\\/$')
674
def test_load_plugins(self):
675
plugin.load_plugins(['.'])
676
self.assertEqual(bzrlib.plugins.__path__, ['.'])
677
# subsequent loads are no-ops
678
plugin.load_plugins(['foo'])
679
self.assertEqual(bzrlib.plugins.__path__, ['.'])
681
def test_load_plugins_default(self):
682
plugin.load_plugins()
683
path = plugin.get_standard_plugins_path()
684
self.assertEqual(path, bzrlib.plugins.__path__)
687
class TestEnvPluginPath(tests.TestCase):
690
super(TestEnvPluginPath, self).setUp()
691
self.overrideAttr(plugin, 'DEFAULT_PLUGIN_PATH', None)
693
self.user = plugin.get_user_plugin_path()
694
self.site = plugin.get_site_plugin_path()
695
self.core = plugin.get_core_plugin_path()
697
def _list2paths(self, *args):
700
plugin._append_new_path(paths, p)
703
def _set_path(self, *args):
704
path = os.pathsep.join(self._list2paths(*args))
705
self.overrideEnv('BZR_PLUGIN_PATH', path)
707
def check_path(self, expected_dirs, setting_dirs):
709
self._set_path(*setting_dirs)
710
actual = plugin.get_standard_plugins_path()
711
self.assertEquals(self._list2paths(*expected_dirs), actual)
713
def test_default(self):
714
self.check_path([self.user, self.core, self.site],
717
def test_adhoc_policy(self):
718
self.check_path([self.user, self.core, self.site],
719
['+user', '+core', '+site'])
721
def test_fallback_policy(self):
722
self.check_path([self.core, self.site, self.user],
723
['+core', '+site', '+user'])
725
def test_override_policy(self):
726
self.check_path([self.user, self.site, self.core],
727
['+user', '+site', '+core'])
729
def test_disable_user(self):
730
self.check_path([self.core, self.site], ['-user'])
732
def test_disable_user_twice(self):
733
# Ensures multiple removals don't left cruft
734
self.check_path([self.core, self.site], ['-user', '-user'])
736
def test_duplicates_are_removed(self):
737
self.check_path([self.user, self.core, self.site],
739
# And only the first reference is kept (since the later references will
740
# only produce '<plugin> already loaded' mutters)
741
self.check_path([self.user, self.core, self.site],
742
['+user', '+user', '+core',
743
'+user', '+site', '+site',
746
def test_disable_overrides_enable(self):
747
self.check_path([self.core, self.site], ['-user', '+user'])
749
def test_disable_core(self):
750
self.check_path([self.site], ['-core'])
751
self.check_path([self.user, self.site], ['+user', '-core'])
753
def test_disable_site(self):
754
self.check_path([self.core], ['-site'])
755
self.check_path([self.user, self.core], ['-site', '+user'])
757
def test_override_site(self):
758
self.check_path(['mysite', self.user, self.core],
759
['mysite', '-site', '+user'])
760
self.check_path(['mysite', self.core],
763
def test_override_core(self):
764
self.check_path(['mycore', self.user, self.site],
765
['mycore', '-core', '+user', '+site'])
766
self.check_path(['mycore', self.site],
769
def test_my_plugin_only(self):
770
self.check_path(['myplugin'], ['myplugin', '-user', '-core', '-site'])
772
def test_my_plugin_first(self):
773
self.check_path(['myplugin', self.core, self.site, self.user],
774
['myplugin', '+core', '+site', '+user'])
776
def test_bogus_references(self):
777
self.check_path(['+foo', '-bar', self.core, self.site],
781
class TestDisablePlugin(BaseTestPlugins):
784
super(TestDisablePlugin, self).setUp()
785
self.create_plugin_package('test_foo')
786
# Make sure we don't pollute the plugins namespace
787
self.overrideAttr(plugins, '__path__')
788
# Be paranoid in case a test fail
789
self.addCleanup(self._unregister_plugin, 'test_foo')
791
def test_cannot_import(self):
792
self.overrideEnv('BZR_DISABLE_PLUGINS', 'test_foo')
793
plugin.set_plugins_path(['.'])
795
import bzrlib.plugins.test_foo
798
self.assertPluginUnknown('test_foo')
800
def test_regular_load(self):
801
self.overrideAttr(plugin, '_loaded', False)
802
plugin.load_plugins(['.'])
803
self.assertPluginKnown('test_foo')
804
self.assertDocstring("This is the doc for test_foo",
805
bzrlib.plugins.test_foo)
807
def test_not_loaded(self):
809
def captured_warning(*args, **kwargs):
810
self.warnings.append((args, kwargs))
811
self.overrideAttr(trace, 'warning', captured_warning)
812
# Reset the flag that protect against double loading
813
self.overrideAttr(plugin, '_loaded', False)
814
self.overrideEnv('BZR_DISABLE_PLUGINS', 'test_foo')
815
plugin.load_plugins(['.'])
816
self.assertPluginUnknown('test_foo')
817
# Make sure we don't warn about the plugin ImportError since this has
818
# been *requested* by the user.
819
self.assertLength(0, self.warnings)
823
class TestLoadPluginAtSyntax(tests.TestCase):
825
def _get_paths(self, paths):
826
return plugin._get_specific_plugin_paths(paths)
828
def test_empty(self):
829
self.assertEquals([], self._get_paths(None))
830
self.assertEquals([], self._get_paths(''))
832
def test_one_path(self):
833
self.assertEquals([('b', 'man')], self._get_paths('b@man'))
835
def test_bogus_path(self):
837
self.assertRaises(errors.BzrCommandError, self._get_paths, 'batman')
838
# Too much '@' isn't good either
839
self.assertRaises(errors.BzrCommandError, self._get_paths,
840
'batman@mobile@cave')
841
# An empty description probably indicates a problem
842
self.assertRaises(errors.BzrCommandError, self._get_paths,
843
os.pathsep.join(['batman@cave', '', 'robin@mobile']))
846
class TestLoadPluginAt(BaseTestPlugins):
849
super(TestLoadPluginAt, self).setUp()
850
# Make sure we don't pollute the plugins namespace
851
self.overrideAttr(plugins, '__path__')
852
# Reset the flag that protect against double loading
853
self.overrideAttr(plugin, '_loaded', False)
854
# Create the same plugin in two directories
855
self.create_plugin_package('test_foo', dir='non-standard-dir')
856
# The "normal" directory, we use 'standard' instead of 'plugins' to
857
# avoid depending on the precise naming.
858
self.create_plugin_package('test_foo', dir='standard/test_foo')
859
# All the tests will load the 'test_foo' plugin from various locations
860
self.addCleanup(self._unregister_plugin, 'test_foo')
861
# Unfortunately there's global cached state for the specific
863
self.addCleanup(plugin.PluginImporter.reset)
865
def assertTestFooLoadedFrom(self, path):
866
self.assertPluginKnown('test_foo')
867
self.assertDocstring('This is the doc for test_foo',
868
bzrlib.plugins.test_foo)
869
self.assertEqual(path, bzrlib.plugins.test_foo.dir_source)
871
def test_regular_load(self):
872
plugin.load_plugins(['standard'])
873
self.assertTestFooLoadedFrom('standard/test_foo')
875
def test_import(self):
876
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
877
plugin.set_plugins_path(['standard'])
879
import bzrlib.plugins.test_foo
882
self.assertTestFooLoadedFrom('non-standard-dir')
884
def test_loading(self):
885
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
886
plugin.load_plugins(['standard'])
887
self.assertTestFooLoadedFrom('non-standard-dir')
889
def test_compiled_loaded(self):
890
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
891
plugin.load_plugins(['standard'])
892
self.assertTestFooLoadedFrom('non-standard-dir')
893
self.assertIsSameRealPath('non-standard-dir/__init__.py',
894
bzrlib.plugins.test_foo.__file__)
896
# Try importing again now that the source has been compiled
897
self._unregister_plugin('test_foo')
898
plugin._loaded = False
899
plugin.load_plugins(['standard'])
900
self.assertTestFooLoadedFrom('non-standard-dir')
905
self.assertIsSameRealPath('non-standard-dir/__init__.%s' % suffix,
906
bzrlib.plugins.test_foo.__file__)
908
def test_submodule_loading(self):
909
# We create an additional directory under the one for test_foo
910
self.create_plugin_package('test_bar', dir='non-standard-dir/test_bar')
911
self.addCleanup(self._unregister_plugin_submodule,
912
'test_foo', 'test_bar')
913
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
914
plugin.set_plugins_path(['standard'])
915
import bzrlib.plugins.test_foo
916
self.assertEqual('bzrlib.plugins.test_foo',
917
bzrlib.plugins.test_foo.__package__)
918
import bzrlib.plugins.test_foo.test_bar
919
self.assertIsSameRealPath('non-standard-dir/test_bar/__init__.py',
920
bzrlib.plugins.test_foo.test_bar.__file__)
922
def test_relative_submodule_loading(self):
923
self.create_plugin_package('test_foo', dir='another-dir', source='''
926
# We create an additional directory under the one for test_foo
927
self.create_plugin_package('test_bar', dir='another-dir/test_bar')
928
self.addCleanup(self._unregister_plugin_submodule,
929
'test_foo', 'test_bar')
930
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@another-dir')
931
plugin.set_plugins_path(['standard'])
932
import bzrlib.plugins.test_foo
933
self.assertEqual('bzrlib.plugins.test_foo',
934
bzrlib.plugins.test_foo.__package__)
935
self.assertIsSameRealPath('another-dir/test_bar/__init__.py',
936
bzrlib.plugins.test_foo.test_bar.__file__)
938
def test_loading_from___init__only(self):
939
# We rename the existing __init__.py file to ensure that we don't load
941
init = 'non-standard-dir/__init__.py'
942
random = 'non-standard-dir/setup.py'
943
os.rename(init, random)
944
self.addCleanup(os.rename, random, init)
945
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
946
plugin.load_plugins(['standard'])
947
self.assertPluginUnknown('test_foo')
949
def test_loading_from_specific_file(self):
950
plugin_dir = 'non-standard-dir'
951
plugin_file_name = 'iamtestfoo.py'
952
plugin_path = osutils.pathjoin(plugin_dir, plugin_file_name)
954
"""This is the doc for %s"""
956
''' % ('test_foo', plugin_path)
957
self.create_plugin('test_foo', source=source,
958
dir=plugin_dir, file_name=plugin_file_name)
959
self.overrideEnv('BZR_PLUGINS_AT', 'test_foo@%s' % plugin_path)
960
plugin.load_plugins(['standard'])
961
self.assertTestFooLoadedFrom(plugin_path)
964
class TestDescribePlugins(BaseTestPlugins):
966
def test_describe_plugins(self):
967
class DummyModule(object):
969
class DummyPlugin(object):
970
__version__ = '0.1.0'
971
module = DummyModule()
973
return { 'good': DummyPlugin() }
974
self.overrideAttr(plugin, 'plugin_warnings',
975
{'bad': ['Failed to load (just testing)']})
976
self.overrideAttr(plugin, 'plugins', dummy_plugins)
977
self.assertEquals("""\
979
** Failed to load (just testing)
984
""", ''.join(plugin.describe_plugins()))