24
25
from StringIO import StringIO
28
from bzrlib import plugin, tests
29
27
import bzrlib.plugin
30
28
import bzrlib.plugins
31
29
import bzrlib.commands
33
from bzrlib.symbol_versioning import zero_ninetyone
34
from bzrlib.tests import TestCase, TestCaseInTempDir
35
from bzrlib.osutils import pathjoin, abspath, normpath
31
from bzrlib.tests import TestCaseInTempDir
32
from bzrlib.osutils import pathjoin, abspath
34
class PluginTest(TestCaseInTempDir):
35
"""Create an external plugin and test loading."""
36
# def test_plugin_loading(self):
37
# orig_help = self.run_bzr_captured('bzr help commands')[0]
38
# os.mkdir('plugin_test')
39
# f = open(pathjoin('plugin_test', 'myplug.py'), 'wt')
40
# f.write(PLUGIN_TEXT)
42
# newhelp = self.run_bzr_captured('bzr help commands')[0]
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')
52
# os.environ['BZRPLUGINPATH'] = abspath('plugin_test')
53
# help = backtick('bzr help commands')
54
# assert help.find('myplug') != -1
55
# assert help.find('Just a simple test plugin.') != -1
58
# assert backtick('bzr myplug') == 'Hello from my plugin\n'
59
# assert backtick('bzr mplg') == 'Hello from my plugin\n'
61
# f = open(pathjoin('plugin_test', 'override.py'), 'wb')
62
# f.write("""import bzrlib, bzrlib.commands
63
# class cmd_commit(bzrlib.commands.cmd_commit):
64
# '''Commit changes into a new revision.'''
65
# def run(self, *args, **kwargs):
66
# print "I'm sorry dave, you can't do that"
68
# class cmd_help(bzrlib.commands.cmd_help):
69
# '''Show help on a command or other topic.'''
70
# def run(self, *args, **kwargs):
71
# print "You have been overridden"
72
# bzrlib.commands.cmd_help.run(self, *args, **kwargs)
39
77
import bzrlib.commands
47
85
# TODO: Write a test for plugin decoration of commands.
49
class TestLoadingPlugins(TestCaseInTempDir):
87
class TestOneNamedPluginOnly(TestCaseInTempDir):
51
89
activeattributes = {}
53
91
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):
101
92
# This test tests that having two plugins in different
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
93
# directories does not result in both being loaded.
94
# get a file name we can use which is also a valid attribute
105
95
# for accessing in activeattributes. - we cannot give import parameters.
106
tempattribute = "different-dirs"
107
97
self.failIf(tempattribute in self.activeattributes)
108
98
# set a place for the plugins to record their loading, and at the same
109
99
# time validate that the location the plugins should record to is
110
100
# valid and correct.
111
bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
101
bzrlib.tests.test_plugins.TestOneNamedPluginOnly.activeattributes \
112
102
[tempattribute] = []
113
103
self.failUnless(tempattribute in self.activeattributes)
114
104
# create two plugin directories
115
105
os.mkdir('first')
116
106
os.mkdir('second')
117
# write plugins that will record when they are loaded in the
107
# write a plugin that will record when its loaded in the
118
108
# 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"
109
template = ("from bzrlib.tests.test_plugins import TestOneNamedPluginOnly\n"
110
"TestOneNamedPluginOnly.activeattributes[%r].append('%s')\n")
111
print >> file(os.path.join('first', 'plugin.py'), 'w'), template % (tempattribute, 'first')
112
print >> file(os.path.join('second', 'plugin.py'), 'w'), template % (tempattribute, 'second')
114
bzrlib.plugin.load_from_dirs(['first', 'second'])
140
115
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')
169
# write a plugin that will record when its loaded in the
170
# tempattribute list.
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])
185
# remove the plugin 'plugin'
186
del self.activeattributes[tempattribute]
187
if getattr(bzrlib.plugins, 'ts_plugin', None):
188
del bzrlib.plugins.ts_plugin
189
self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
117
# remove the plugin 'plugin'
118
del self.activeattributes[tempattribute]
119
if getattr(bzrlib.plugins, 'plugin', None):
120
del bzrlib.plugins.plugin
121
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
192
124
class TestAllPlugins(TestCaseInTempDir):
196
128
# check the plugin is not loaded already
197
129
self.failIf(getattr(bzrlib.plugins, 'plugin', None))
198
130
# write a plugin that _cannot_ fail to load.
199
file('plugin.py', 'w').write("\n")
131
print >> file('plugin.py', 'w'), ""
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)
133
bzrlib.plugin.load_from_dirs(['.'])
134
self.failUnless('plugin' in bzrlib.plugin.all_plugins())
205
135
self.failUnless(getattr(bzrlib.plugins, 'plugin', None))
206
self.assertEqual(all_plugins['plugin'], bzrlib.plugins.plugin)
136
self.assertEqual(bzrlib.plugin.all_plugins()['plugin'],
137
bzrlib.plugins.plugin)
208
139
# remove the plugin 'plugin'
209
if 'bzrlib.plugins.plugin' in sys.modules:
210
del sys.modules['bzrlib.plugins.plugin']
211
140
if getattr(bzrlib.plugins, 'plugin', None):
212
141
del bzrlib.plugins.plugin
213
142
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
145
class TestPluginHelp(TestCaseInTempDir):
297
147
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]
150
for line in self.capture('help commands').splitlines():
151
if line.startswith('bzr '):
152
current = line.split()[1]
303
153
help[current] = help.get(current, '') + line
335
bzrlib.plugin.load_from_path(['plugin_test'])
187
bzrlib.plugin.load_from_dirs(['plugin_test'])
336
188
bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
337
help = self.run_bzr('help myplug')[0]
338
self.assertContainsRe(help, 'plugin "myplug"')
189
help = self.capture('help myplug')
190
self.assertContainsRe(help, 'From plugin "myplug"')
339
191
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())
192
self.assertContainsRe(help, 'From plugin "myplug"')
194
# remove the plugin 'plugin'
195
if getattr(bzrlib.plugins, 'plugin', None):
196
del bzrlib.plugins.plugin