~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_plugins.py

  • Committer: Martin Pool
  • Date: 2009-03-24 05:21:02 UTC
  • mfrom: (4192 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4202.
  • Revision ID: mbp@sourcefrog.net-20090324052102-8kk087b32tep3d9h
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
31
31
import bzrlib.plugins
32
32
import bzrlib.commands
33
33
import bzrlib.help
34
 
from bzrlib.symbol_versioning import one_three
35
34
from bzrlib.tests import (
36
35
    TestCase,
37
36
    TestCaseInTempDir,
71
70
        # create two plugin directories
72
71
        os.mkdir('first')
73
72
        os.mkdir('second')
74
 
        # write a plugin that will record when its loaded in the 
 
73
        # write a plugin that will record when its loaded in the
75
74
        # tempattribute list.
76
75
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
77
76
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
119
118
        # create two plugin directories
120
119
        os.mkdir('first')
121
120
        os.mkdir('second')
122
 
        # write plugins that will record when they are loaded in the 
 
121
        # write plugins that will record when they are loaded in the
123
122
        # tempattribute list.
124
123
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
125
124
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
171
170
        self.failUnless(tempattribute in self.activeattributes)
172
171
        # create a directory for the plugin
173
172
        os.mkdir('plugin_test')
174
 
        # write a plugin that will record when its loaded in the 
 
173
        # write a plugin that will record when its loaded in the
175
174
        # tempattribute list.
176
175
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
177
176
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
193
192
                del bzrlib.plugins.ts_plugin
194
193
        self.failIf(getattr(bzrlib.plugins, 'ts_plugin', None))
195
194
 
196
 
    def test_plugin_with_bad_name_does_not_load(self):
197
 
        # Create badly-named plugin
198
 
        file('bzr-bad plugin-name..py', 'w').close()
 
195
    def load_and_capture(self, name):
 
196
        """Load plugins from '.' capturing the output.
199
197
 
 
198
        :param name: The name of the plugin.
 
199
        :return: A string with the log from the plugin loading call.
 
200
        """
200
201
        # Capture output
201
202
        stream = StringIO()
202
 
        handler = logging.StreamHandler(stream)
203
 
        log = logging.getLogger('bzr')
204
 
        log.addHandler(handler)
205
 
 
206
 
        bzrlib.plugin.load_from_dir('.')
207
 
 
208
 
        # Stop capturing output
209
 
        handler.flush()
210
 
        handler.close()
211
 
        log.removeHandler(handler)
212
 
 
213
 
        self.assertContainsRe(stream.getvalue(),
 
203
        try:
 
204
            handler = logging.StreamHandler(stream)
 
205
            log = logging.getLogger('bzr')
 
206
            log.addHandler(handler)
 
207
            try:
 
208
                try:
 
209
                    bzrlib.plugin.load_from_path(['.'])
 
210
                finally:
 
211
                    if 'bzrlib.plugins.%s' % name in sys.modules:
 
212
                        del sys.modules['bzrlib.plugins.%s' % name]
 
213
                    if getattr(bzrlib.plugins, name, None):
 
214
                        delattr(bzrlib.plugins, name)
 
215
            finally:
 
216
                # Stop capturing output
 
217
                handler.flush()
 
218
                handler.close()
 
219
                log.removeHandler(handler)
 
220
            return stream.getvalue()
 
221
        finally:
 
222
            stream.close()
 
223
 
 
224
    def test_plugin_with_bad_api_version_reports(self):
 
225
        # This plugin asks for bzrlib api version 1.0.0, which is not supported
 
226
        # anymore.
 
227
        name = 'wants100.py'
 
228
        f = file(name, 'w')
 
229
        try:
 
230
            f.write("import bzrlib.api\n"
 
231
                "bzrlib.api.require_any_api(bzrlib, [(1, 0, 0)])\n")
 
232
        finally:
 
233
            f.close()
 
234
 
 
235
        log = self.load_and_capture(name)
 
236
        self.assertContainsRe(log,
 
237
            r"It requested API version")
 
238
 
 
239
    def test_plugin_with_bad_name_does_not_load(self):
 
240
        # The file name here invalid for a python module.
 
241
        name = 'bzr-bad plugin-name..py'
 
242
        file(name, 'w').close()
 
243
        log = self.load_and_capture(name)
 
244
        self.assertContainsRe(log,
214
245
            r"Unable to load 'bzr-bad plugin-name\.' in '\.' as a plugin "
215
246
            "because the file path isn't a valid module name; try renaming "
216
247
            "it to 'bad_plugin_name_'\.")
217
248
 
218
 
        stream.close()
219
 
 
220
249
 
221
250
class TestPlugins(TestCaseInTempDir):
222
251
 
228
257
        file('plugin.py', 'w').write(source + '\n')
229
258
        self.addCleanup(self.teardown_plugin)
230
259
        bzrlib.plugin.load_from_path(['.'])
231
 
    
 
260
 
232
261
    def teardown_plugin(self):
233
262
        # remove the plugin 'plugin'
234
263
        if 'bzrlib.plugins.plugin' in sys.modules:
323
352
        plugin = bzrlib.plugin.plugins()['plugin']
324
353
        self.assertEqual("unknown", plugin.__version__)
325
354
 
326
 
    def test___version__with_version_info(self):
 
355
    def test_str__version__with_version_info(self):
 
356
        self.setup_plugin("version_info = '1.2.3'")
 
357
        plugin = bzrlib.plugin.plugins()['plugin']
 
358
        self.assertEqual("1.2.3", plugin.__version__)
 
359
 
 
360
    def test_noniterable__version__with_version_info(self):
 
361
        self.setup_plugin("version_info = (1)")
 
362
        plugin = bzrlib.plugin.plugins()['plugin']
 
363
        self.assertEqual("1", plugin.__version__)
 
364
 
 
365
    def test_1__version__with_version_info(self):
 
366
        self.setup_plugin("version_info = (1,)")
 
367
        plugin = bzrlib.plugin.plugins()['plugin']
 
368
        self.assertEqual("1", plugin.__version__)
 
369
 
 
370
    def test_1_2__version__with_version_info(self):
 
371
        self.setup_plugin("version_info = (1, 2)")
 
372
        plugin = bzrlib.plugin.plugins()['plugin']
 
373
        self.assertEqual("1.2", plugin.__version__)
 
374
 
 
375
    def test_1_2_3__version__with_version_info(self):
 
376
        self.setup_plugin("version_info = (1, 2, 3)")
 
377
        plugin = bzrlib.plugin.plugins()['plugin']
 
378
        self.assertEqual("1.2.3", plugin.__version__)
 
379
 
 
380
    def test_candidate__version__with_version_info(self):
 
381
        self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
 
382
        plugin = bzrlib.plugin.plugins()['plugin']
 
383
        self.assertEqual("1.2.3rc1", plugin.__version__)
 
384
 
 
385
    def test_dev__version__with_version_info(self):
 
386
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 0)")
 
387
        plugin = bzrlib.plugin.plugins()['plugin']
 
388
        self.assertEqual("1.2.3dev", plugin.__version__)
 
389
 
 
390
    def test_dev_fallback__version__with_version_info(self):
327
391
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
328
392
        plugin = bzrlib.plugin.plugins()['plugin']
329
 
        self.assertEqual("1.2.3dev4", plugin.__version__)
 
393
        self.assertEqual("1.2.3.dev.4", plugin.__version__)
330
394
 
331
395
    def test_final__version__with_version_info(self):
332
 
        self.setup_plugin("version_info = (1, 2, 3, 'final', 4)")
 
396
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
333
397
        plugin = bzrlib.plugin.plugins()['plugin']
334
398
        self.assertEqual("1.2.3", plugin.__version__)
335
399
 
339
403
    def split_help_commands(self):
340
404
        help = {}
341
405
        current = None
342
 
        for line in self.run_bzr('help commands')[0].splitlines():
 
406
        out, err = self.run_bzr('--no-plugins help commands')
 
407
        for line in out.splitlines():
343
408
            if not line.startswith(' '):
344
409
                current = line.split()[0]
345
410
            help[current] = help.get(current, '') + line
382
447
            self.assertContainsRe(help, '\[myplug\]')
383
448
        finally:
384
449
            # unregister command
385
 
            if bzrlib.commands.plugin_cmds.get('myplug', None):
386
 
                del bzrlib.commands.plugin_cmds['myplug']
 
450
            if 'myplug' in bzrlib.commands.plugin_cmds:
 
451
                bzrlib.commands.plugin_cmds.remove('myplug')
387
452
            # remove the plugin 'myplug'
388
453
            if getattr(bzrlib.plugins, 'myplug', None):
389
454
                delattr(bzrlib.plugins, 'myplug')
390
455
 
391
456
 
392
 
class TestPluginFromZip(TestCaseInTempDir):
393
 
 
394
 
    def make_zipped_plugin(self, zip_name, filename):
395
 
        z = zipfile.ZipFile(zip_name, 'w')
396
 
        z.writestr(filename, PLUGIN_TEXT)
397
 
        z.close()
398
 
 
399
 
    def check_plugin_load(self, zip_name, plugin_name):
400
 
        self.assertFalse(plugin_name in dir(bzrlib.plugins),
401
 
                         'Plugin already loaded')
402
 
        old_path = bzrlib.plugins.__path__
403
 
        try:
404
 
            # this is normally done by load_plugins -> set_plugins_path
405
 
            bzrlib.plugins.__path__ = [zip_name]
406
 
            self.applyDeprecated(one_three,
407
 
                bzrlib.plugin.load_from_zip, zip_name)
408
 
            self.assertTrue(plugin_name in dir(bzrlib.plugins),
409
 
                            'Plugin is not loaded')
410
 
        finally:
411
 
            # unregister plugin
412
 
            if getattr(bzrlib.plugins, plugin_name, None):
413
 
                delattr(bzrlib.plugins, plugin_name)
414
 
                del sys.modules['bzrlib.plugins.' + plugin_name]
415
 
            bzrlib.plugins.__path__ = old_path
416
 
 
417
 
    def test_load_module(self):
418
 
        self.make_zipped_plugin('./test.zip', 'ziplug.py')
419
 
        self.check_plugin_load('./test.zip', 'ziplug')
420
 
 
421
 
    def test_load_package(self):
422
 
        self.make_zipped_plugin('./test.zip', 'ziplug/__init__.py')
423
 
        self.check_plugin_load('./test.zip', 'ziplug')
424
 
 
425
 
 
426
457
class TestSetPluginsPath(TestCase):
427
 
    
 
458
 
428
459
    def test_set_plugins_path(self):
429
460
        """set_plugins_path should set the module __path__ correctly."""
430
461
        old_path = bzrlib.plugins.__path__
437
468
 
438
469
    def test_set_plugins_path_with_trailing_slashes(self):
439
470
        """set_plugins_path should set the module __path__ based on
440
 
        BZR_PLUGIN_PATH."""
 
471
        BZR_PLUGIN_PATH after removing all trailing slashes."""
441
472
        old_path = bzrlib.plugins.__path__
442
473
        old_env = os.environ.get('BZR_PLUGIN_PATH')
443
474
        try:
445
476
            os.environ['BZR_PLUGIN_PATH'] = "first\\//\\" + os.pathsep + \
446
477
                "second/\\/\\/"
447
478
            bzrlib.plugin.set_plugins_path()
448
 
            expected_path = ['first', 'second',
449
 
                os.path.dirname(bzrlib.plugins.__file__)]
 
479
            # We expect our nominated paths to have all path-seps removed,
 
480
            # and this is testing only that.
 
481
            expected_path = ['first', 'second']
450
482
            self.assertEqual(expected_path,
451
483
                bzrlib.plugins.__path__[:len(expected_path)])
452
484
        finally:
563
595
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
564
596
        topic = plugin.ModuleHelpTopic(mod)
565
597
        self.assertEqual('foo_bar', topic.get_help_topic())
 
598
 
 
599
 
 
600
def clear_plugins(test_case):
 
601
    # Save the attributes that we're about to monkey-patch.
 
602
    old_plugins_path = bzrlib.plugins.__path__
 
603
    old_loaded = plugin._loaded
 
604
    old_load_from_path = plugin.load_from_path
 
605
    # Change bzrlib.plugin to think no plugins have been loaded yet.
 
606
    bzrlib.plugins.__path__ = []
 
607
    plugin._loaded = False
 
608
    # Monkey-patch load_from_path to stop it from actually loading anything.
 
609
    def load_from_path(dirs):
 
610
        pass
 
611
    plugin.load_from_path = load_from_path
 
612
    def restore_plugins():
 
613
        bzrlib.plugins.__path__ = old_plugins_path
 
614
        plugin._loaded = old_loaded
 
615
        plugin.load_from_path = old_load_from_path
 
616
    test_case.addCleanup(restore_plugins)
 
617
 
 
618
 
 
619
class TestPluginPaths(tests.TestCase):
 
620
 
 
621
    def test_set_plugins_path_with_args(self):
 
622
        clear_plugins(self)
 
623
        plugin.set_plugins_path(['a', 'b'])
 
624
        self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
 
625
 
 
626
    def test_set_plugins_path_defaults(self):
 
627
        clear_plugins(self)
 
628
        plugin.set_plugins_path()
 
629
        self.assertEqual(plugin.get_standard_plugins_path(),
 
630
                         bzrlib.plugins.__path__)
 
631
 
 
632
    def test_get_standard_plugins_path(self):
 
633
        path = plugin.get_standard_plugins_path()
 
634
        self.assertEqual(plugin.get_default_plugin_path(), path[0])
 
635
        for directory in path:
 
636
            self.assertNotContainsRe(r'\\/$', directory)
 
637
        try:
 
638
            from distutils.sysconfig import get_python_lib
 
639
        except ImportError:
 
640
            pass
 
641
        else:
 
642
            if sys.platform != 'win32':
 
643
                python_lib = get_python_lib()
 
644
                for directory in path:
 
645
                    if directory.startswith(python_lib):
 
646
                        break
 
647
                else:
 
648
                    self.fail('No path to global plugins')
 
649
 
 
650
    def test_get_standard_plugins_path_env(self):
 
651
        os.environ['BZR_PLUGIN_PATH'] = 'foo/'
 
652
        self.assertEqual('foo', plugin.get_standard_plugins_path()[0])
 
653
 
 
654
 
 
655
class TestLoadPlugins(tests.TestCaseInTempDir):
 
656
 
 
657
    def test_load_plugins(self):
 
658
        clear_plugins(self)
 
659
        plugin.load_plugins(['.'])
 
660
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
661
        # subsequent loads are no-ops
 
662
        plugin.load_plugins(['foo'])
 
663
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
664
 
 
665
    def test_load_plugins_default(self):
 
666
        clear_plugins(self)
 
667
        plugin.load_plugins()
 
668
        path = plugin.get_standard_plugins_path()
 
669
        self.assertEqual(path, bzrlib.plugins.__path__)