82
47
# TODO: Write a test for plugin decoration of commands.
84
class TestOneNamedPluginOnly(TestCaseInTempDir):
49
class TestLoadingPlugins(TestCaseInTempDir):
86
51
activeattributes = {}
88
53
def test_plugins_with_the_same_name_are_not_loaded(self):
54
# This test tests that having two plugins in different directories does
55
# not result in both being loaded when they have the same name. get a
56
# file name we can use which is also a valid attribute for accessing in
57
# activeattributes. - we cannot give import parameters.
59
self.failIf(tempattribute in self.activeattributes)
60
# set a place for the plugins to record their loading, and at the same
61
# time validate that the location the plugins should record to is
63
bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
65
self.failUnless(tempattribute in self.activeattributes)
66
# create two plugin directories
69
# write a plugin that will record when its loaded in the
71
template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
72
"TestLoadingPlugins.activeattributes[%r].append('%s')\n")
74
outfile = open(os.path.join('first', 'plugin.py'), 'w')
76
outfile.write(template % (tempattribute, 'first'))
81
outfile = open(os.path.join('second', 'plugin.py'), 'w')
83
outfile.write(template % (tempattribute, 'second'))
89
bzrlib.plugin.load_from_path(['first', 'second'])
90
self.assertEqual(['first'], self.activeattributes[tempattribute])
92
# remove the plugin 'plugin'
93
del self.activeattributes[tempattribute]
94
if 'bzrlib.plugins.plugin' in sys.modules:
95
del sys.modules['bzrlib.plugins.plugin']
96
if getattr(bzrlib.plugins, 'plugin', None):
97
del bzrlib.plugins.plugin
98
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
100
def test_plugins_from_different_dirs_can_demand_load(self):
89
101
# This test tests that having two plugins in different
90
# directories does not result in both being loaded.
91
# get a file name we can use which is also a valid attribute
102
# directories with different names allows them both to be loaded, when
103
# we do a direct import statement.
104
# Determine a file name we can use which is also a valid attribute
92
105
# for accessing in activeattributes. - we cannot give import parameters.
106
tempattribute = "different-dirs"
94
107
self.failIf(tempattribute in self.activeattributes)
95
108
# set a place for the plugins to record their loading, and at the same
96
109
# time validate that the location the plugins should record to is
97
110
# valid and correct.
98
bzrlib.tests.test_plugins.TestOneNamedPluginOnly.activeattributes \
111
bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
99
112
[tempattribute] = []
100
113
self.failUnless(tempattribute in self.activeattributes)
101
114
# create two plugin directories
102
115
os.mkdir('first')
103
116
os.mkdir('second')
117
# write plugins that will record when they are loaded in the
118
# tempattribute list.
119
template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
120
"TestLoadingPlugins.activeattributes[%r].append('%s')\n")
122
outfile = open(os.path.join('first', 'pluginone.py'), 'w')
124
outfile.write(template % (tempattribute, 'first'))
129
outfile = open(os.path.join('second', 'plugintwo.py'), 'w')
131
outfile.write(template % (tempattribute, 'second'))
136
oldpath = bzrlib.plugins.__path__
138
bzrlib.plugins.__path__ = ['first', 'second']
139
exec "import bzrlib.plugins.pluginone"
140
self.assertEqual(['first'], self.activeattributes[tempattribute])
141
exec "import bzrlib.plugins.plugintwo"
142
self.assertEqual(['first', 'second'],
143
self.activeattributes[tempattribute])
145
# remove the plugin 'plugin'
146
del self.activeattributes[tempattribute]
147
if getattr(bzrlib.plugins, 'pluginone', None):
148
del bzrlib.plugins.pluginone
149
if getattr(bzrlib.plugins, 'plugintwo', None):
150
del bzrlib.plugins.plugintwo
151
self.failIf(getattr(bzrlib.plugins, 'pluginone', None))
152
self.failIf(getattr(bzrlib.plugins, 'plugintwo', None))
154
def test_plugins_can_load_from_directory_with_trailing_slash(self):
155
# This test tests that a plugin can load from a directory when the
156
# directory in the path has a trailing slash.
157
# check the plugin is not loaded already
158
self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
159
tempattribute = "trailing-slash"
160
self.failIf(tempattribute in self.activeattributes)
161
# set a place for the plugin to record its loading, and at the same
162
# time validate that the location the plugin should record to is
164
bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
166
self.failUnless(tempattribute in self.activeattributes)
167
# create a directory for the plugin
168
os.mkdir('plugin_test')
104
169
# write a plugin that will record when its loaded in the
105
170
# tempattribute list.
106
template = ("from bzrlib.tests.test_plugins import TestOneNamedPluginOnly\n"
107
"TestOneNamedPluginOnly.activeattributes[%r].append('%s')\n")
108
print >> file(os.path.join('first', 'plugin.py'), 'w'), template % (tempattribute, 'first')
109
print >> file(os.path.join('second', 'plugin.py'), 'w'), template % (tempattribute, 'second')
111
bzrlib.plugin.load_from_dirs(['first', 'second'])
112
self.assertEqual(['first'], self.activeattributes[tempattribute])
171
template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
172
"TestLoadingPlugins.activeattributes[%r].append('%s')\n")
174
outfile = open(os.path.join('plugin_test', 'ts_plugin.py'), 'w')
176
outfile.write(template % (tempattribute, 'plugin'))
182
bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
183
self.assertEqual(['plugin'], self.activeattributes[tempattribute])
114
185
# remove the plugin 'plugin'
115
186
del self.activeattributes[tempattribute]
116
if getattr(bzrlib.plugins, 'plugin', None):
117
del bzrlib.plugins.plugin
118
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
187
if getattr(bzrlib.plugins, 'ts_plugin', None):
188
del bzrlib.plugins.ts_plugin
189
self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
121
192
class TestAllPlugins(TestCaseInTempDir):
125
196
# check the plugin is not loaded already
126
197
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
127
198
# write a plugin that _cannot_ fail to load.
128
print >> file('plugin.py', 'w'), ""
199
file('plugin.py', 'w').write("\n")
130
bzrlib.plugin.load_from_dirs(['.'])
131
self.failUnless('plugin' in bzrlib.plugin.all_plugins())
201
bzrlib.plugin.load_from_path(['.'])
202
all_plugins = self.applyDeprecated(zero_ninetyone,
203
bzrlib.plugin.all_plugins)
204
self.failUnless('plugin' in all_plugins)
132
205
self.failUnless(getattr(bzrlib.plugins, 'plugin', None))
133
self.assertEqual(bzrlib.plugin.all_plugins()['plugin'],
134
bzrlib.plugins.plugin)
206
self.assertEqual(all_plugins['plugin'], bzrlib.plugins.plugin)
136
208
# remove the plugin 'plugin'
209
if 'bzrlib.plugins.plugin' in sys.modules:
210
del sys.modules['bzrlib.plugins.plugin']
137
211
if getattr(bzrlib.plugins, 'plugin', None):
138
212
del bzrlib.plugins.plugin
139
213
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
216
class TestPlugins(TestCaseInTempDir):
218
def setup_plugin(self, source=""):
219
# This test tests a new plugin appears in bzrlib.plugin.plugins().
220
# check the plugin is not loaded already
221
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
222
# write a plugin that _cannot_ fail to load.
223
file('plugin.py', 'w').write(source + '\n')
224
self.addCleanup(self.teardown_plugin)
225
bzrlib.plugin.load_from_path(['.'])
227
def teardown_plugin(self):
228
# remove the plugin 'plugin'
229
if 'bzrlib.plugins.plugin' in sys.modules:
230
del sys.modules['bzrlib.plugins.plugin']
231
if getattr(bzrlib.plugins, 'plugin', None):
232
del bzrlib.plugins.plugin
233
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
235
def test_plugin_appears_in_plugins(self):
237
self.failUnless('plugin' in bzrlib.plugin.plugins())
238
self.failUnless(getattr(bzrlib.plugins, 'plugin', None))
239
plugins = bzrlib.plugin.plugins()
240
plugin = plugins['plugin']
241
self.assertIsInstance(plugin, bzrlib.plugin.PlugIn)
242
self.assertEqual(bzrlib.plugins.plugin, plugin.module)
244
def test_trivial_plugin_get_path(self):
246
plugins = bzrlib.plugin.plugins()
247
plugin = plugins['plugin']
248
plugin_path = self.test_dir + '/plugin.py'
249
self.assertIsSameRealPath(plugin_path, normpath(plugin.path()))
251
def test_no_test_suite_gives_None_for_test_suite(self):
253
plugin = bzrlib.plugin.plugins()['plugin']
254
self.assertEqual(None, plugin.test_suite())
256
def test_test_suite_gives_test_suite_result(self):
257
source = """def test_suite(): return 'foo'"""
258
self.setup_plugin(source)
259
plugin = bzrlib.plugin.plugins()['plugin']
260
self.assertEqual('foo', plugin.test_suite())
262
def test_no_version_info(self):
264
plugin = bzrlib.plugin.plugins()['plugin']
265
self.assertEqual(None, plugin.version_info())
267
def test_with_version_info(self):
268
self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
269
plugin = bzrlib.plugin.plugins()['plugin']
270
self.assertEqual((1, 2, 3, 'dev', 4), plugin.version_info())
272
def test_short_version_info_gets_padded(self):
273
# the gtk plugin has version_info = (1,2,3) rather than the 5-tuple.
275
self.setup_plugin("version_info = (1, 2, 3)")
276
plugin = bzrlib.plugin.plugins()['plugin']
277
self.assertEqual((1, 2, 3, 'final', 0), plugin.version_info())
279
def test_no_version_info___version__(self):
281
plugin = bzrlib.plugin.plugins()['plugin']
282
self.assertEqual("unknown", plugin.__version__)
284
def test___version__with_version_info(self):
285
self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
286
plugin = bzrlib.plugin.plugins()['plugin']
287
self.assertEqual("1.2.3dev4", plugin.__version__)
289
def test_final__version__with_version_info(self):
290
self.setup_plugin("version_info = (1, 2, 3, 'final', 4)")
291
plugin = bzrlib.plugin.plugins()['plugin']
292
self.assertEqual("1.2.3", plugin.__version__)
295
class TestPluginHelp(TestCaseInTempDir):
297
def split_help_commands(self):
300
for line in self.run_bzr('help commands')[0].splitlines():
301
if not line.startswith(' '):
302
current = line.split()[0]
303
help[current] = help.get(current, '') + line
307
def test_plugin_help_builtins_unaffected(self):
308
# Check we don't get false positives
309
help_commands = self.split_help_commands()
310
for cmd_name in bzrlib.commands.builtin_command_names():
311
if cmd_name in bzrlib.commands.plugin_command_names():
314
help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
315
except NotImplementedError:
316
# some commands have no help
319
self.assertNotContainsRe(help, 'plugin "[^"]*"')
321
if cmd_name in help_commands.keys():
322
# some commands are hidden
323
help = help_commands[cmd_name]
324
self.assertNotContainsRe(help, 'plugin "[^"]*"')
326
def test_plugin_help_shows_plugin(self):
327
# Create a test plugin
328
os.mkdir('plugin_test')
329
f = open(pathjoin('plugin_test', 'myplug.py'), 'w')
335
bzrlib.plugin.load_from_path(['plugin_test'])
336
bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
337
help = self.run_bzr('help myplug')[0]
338
self.assertContainsRe(help, 'plugin "myplug"')
339
help = self.split_help_commands()['myplug']
340
self.assertContainsRe(help, '\[myplug\]')
343
if bzrlib.commands.plugin_cmds.get('myplug', None):
344
del bzrlib.commands.plugin_cmds['myplug']
345
# remove the plugin 'myplug'
346
if getattr(bzrlib.plugins, 'myplug', None):
347
delattr(bzrlib.plugins, 'myplug')
350
class TestPluginFromZip(TestCaseInTempDir):
352
def make_zipped_plugin(self, zip_name, filename):
353
z = zipfile.ZipFile(zip_name, 'w')
354
z.writestr(filename, PLUGIN_TEXT)
357
def check_plugin_load(self, zip_name, plugin_name):
358
self.assertFalse(plugin_name in dir(bzrlib.plugins),
359
'Plugin already loaded')
360
old_path = bzrlib.plugins.__path__
362
# this is normally done by load_plugins -> set_plugins_path
363
bzrlib.plugins.__path__ = [zip_name]
364
bzrlib.plugin.load_from_zip(zip_name)
365
self.assertTrue(plugin_name in dir(bzrlib.plugins),
366
'Plugin is not loaded')
369
if getattr(bzrlib.plugins, plugin_name, None):
370
delattr(bzrlib.plugins, plugin_name)
371
del sys.modules['bzrlib.plugins.' + plugin_name]
372
bzrlib.plugins.__path__ = old_path
374
def test_load_module(self):
375
self.make_zipped_plugin('./test.zip', 'ziplug.py')
376
self.check_plugin_load('./test.zip', 'ziplug')
378
def test_load_package(self):
379
self.make_zipped_plugin('./test.zip', 'ziplug/__init__.py')
380
self.check_plugin_load('./test.zip', 'ziplug')
383
class TestSetPluginsPath(TestCase):
385
def test_set_plugins_path(self):
386
"""set_plugins_path should set the module __path__ correctly."""
387
old_path = bzrlib.plugins.__path__
389
bzrlib.plugins.__path__ = []
390
expected_path = bzrlib.plugin.set_plugins_path()
391
self.assertEqual(expected_path, bzrlib.plugins.__path__)
393
bzrlib.plugins.__path__ = old_path
395
def test_set_plugins_path_with_trailing_slashes(self):
396
"""set_plugins_path should set the module __path__ based on
398
old_path = bzrlib.plugins.__path__
399
old_env = os.environ.get('BZR_PLUGIN_PATH')
401
bzrlib.plugins.__path__ = []
402
os.environ['BZR_PLUGIN_PATH'] = "first\\//\\" + os.pathsep + \
404
bzrlib.plugin.set_plugins_path()
405
expected_path = ['first', 'second',
406
os.path.dirname(bzrlib.plugins.__file__)]
407
self.assertEqual(expected_path, bzrlib.plugins.__path__)
409
bzrlib.plugins.__path__ = old_path
411
os.environ['BZR_PLUGIN_PATH'] = old_env
413
del os.environ['BZR_PLUGIN_PATH']
415
class TestHelpIndex(tests.TestCase):
416
"""Tests for the PluginsHelpIndex class."""
418
def test_default_constructable(self):
419
index = plugin.PluginsHelpIndex()
421
def test_get_topics_None(self):
422
"""Searching for None returns an empty list."""
423
index = plugin.PluginsHelpIndex()
424
self.assertEqual([], index.get_topics(None))
426
def test_get_topics_for_plugin(self):
427
"""Searching for plugin name gets its docstring."""
428
index = plugin.PluginsHelpIndex()
429
# make a new plugin here for this test, even if we're run with
431
self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
432
demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
433
sys.modules['bzrlib.plugins.demo_module'] = demo_module
435
topics = index.get_topics('demo_module')
436
self.assertEqual(1, len(topics))
437
self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
438
self.assertEqual(demo_module, topics[0].module)
440
del sys.modules['bzrlib.plugins.demo_module']
442
def test_get_topics_no_topic(self):
443
"""Searching for something that is not a plugin returns []."""
444
# test this by using a name that cannot be a plugin - its not
445
# a valid python identifier.
446
index = plugin.PluginsHelpIndex()
447
self.assertEqual([], index.get_topics('nothing by this name'))
449
def test_prefix(self):
450
"""PluginsHelpIndex has a prefix of 'plugins/'."""
451
index = plugin.PluginsHelpIndex()
452
self.assertEqual('plugins/', index.prefix)
454
def test_get_plugin_topic_with_prefix(self):
455
"""Searching for plugins/demo_module returns help."""
456
index = plugin.PluginsHelpIndex()
457
self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
458
demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
459
sys.modules['bzrlib.plugins.demo_module'] = demo_module
461
topics = index.get_topics('plugins/demo_module')
462
self.assertEqual(1, len(topics))
463
self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
464
self.assertEqual(demo_module, topics[0].module)
466
del sys.modules['bzrlib.plugins.demo_module']
469
class FakeModule(object):
470
"""A fake module to test with."""
472
def __init__(self, doc, name):
477
class TestModuleHelpTopic(tests.TestCase):
478
"""Tests for the ModuleHelpTopic class."""
480
def test_contruct(self):
481
"""Construction takes the module to document."""
482
mod = FakeModule('foo', 'foo')
483
topic = plugin.ModuleHelpTopic(mod)
484
self.assertEqual(mod, topic.module)
486
def test_get_help_text_None(self):
487
"""A ModuleHelpTopic returns the docstring for get_help_text."""
488
mod = FakeModule(None, 'demo')
489
topic = plugin.ModuleHelpTopic(mod)
490
self.assertEqual("Plugin 'demo' has no docstring.\n",
491
topic.get_help_text())
493
def test_get_help_text_no_carriage_return(self):
494
"""ModuleHelpTopic.get_help_text adds a \n if needed."""
495
mod = FakeModule('one line of help', 'demo')
496
topic = plugin.ModuleHelpTopic(mod)
497
self.assertEqual("one line of help\n",
498
topic.get_help_text())
500
def test_get_help_text_carriage_return(self):
501
"""ModuleHelpTopic.get_help_text adds a \n if needed."""
502
mod = FakeModule('two lines of help\nand more\n', 'demo')
503
topic = plugin.ModuleHelpTopic(mod)
504
self.assertEqual("two lines of help\nand more\n",
505
topic.get_help_text())
507
def test_get_help_text_with_additional_see_also(self):
508
mod = FakeModule('two lines of help\nand more', 'demo')
509
topic = plugin.ModuleHelpTopic(mod)
510
self.assertEqual("two lines of help\nand more\nSee also: bar, foo\n",
511
topic.get_help_text(['foo', 'bar']))
513
def test_get_help_topic(self):
514
"""The help topic for a plugin is its module name."""
515
mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
516
topic = plugin.ModuleHelpTopic(mod)
517
self.assertEqual('demo', topic.get_help_topic())
518
mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
519
topic = plugin.ModuleHelpTopic(mod)
520
self.assertEqual('foo_bar', topic.get_help_topic())