/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to brzlib/tests/test_plugins.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 14:47:52 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521144752-8o6jt0a6xat9g7lm
More renames; commands in output, environment variables.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2012, 2016 Canonical Ltd
2
2
#
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
17
17
"""Tests for plugins"""
18
18
 
19
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
 
20
# affects the global state of the process.  See brzlib/plugins.py for more
21
21
# comments.
22
22
 
23
23
from cStringIO import StringIO
25
25
import os
26
26
import sys
27
27
 
28
 
import bzrlib
29
 
from bzrlib import (
 
28
import brzlib
 
29
from brzlib import (
 
30
    errors,
30
31
    osutils,
31
32
    plugin,
32
33
    plugins,
37
38
 
38
39
# TODO: Write a test for plugin decoration of commands.
39
40
 
40
 
class TestPluginMixin(object):
 
41
class BaseTestPlugins(tests.TestCaseInTempDir):
41
42
 
42
43
    def create_plugin(self, name, source=None, dir='.', file_name=None):
43
44
        if source is None:
72
73
                           file_name='__init__.py')
73
74
 
74
75
    def _unregister_plugin(self, name):
75
 
        """Remove the plugin from sys.modules and the bzrlib namespace."""
76
 
        py_name = 'bzrlib.plugins.%s' % name
77
 
        if py_name in sys.modules:
78
 
            del sys.modules[py_name]
79
 
        if getattr(bzrlib.plugins, name, None) is not None:
80
 
            delattr(bzrlib.plugins, name)
 
76
        """Remove the plugin from sys.modules and the brzlib namespace."""
 
77
        py_name = 'brzlib.plugins.%s' % name
 
78
        if py_name in sys.modules:
 
79
            del sys.modules[py_name]
 
80
        if getattr(brzlib.plugins, name, None) is not None:
 
81
            delattr(brzlib.plugins, name)
 
82
 
 
83
    def _unregister_plugin_submodule(self, plugin_name, submodule_name):
 
84
        """Remove the submodule from sys.modules and the brzlib namespace."""
 
85
        py_name = 'brzlib.plugins.%s.%s' % (plugin_name, submodule_name)
 
86
        if py_name in sys.modules:
 
87
            del sys.modules[py_name]
 
88
        plugin = getattr(brzlib.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)
81
92
 
82
93
    def assertPluginUnknown(self, name):
83
 
        self.failIf(getattr(bzrlib.plugins, name, None) is not None)
84
 
        self.failIf('bzrlib.plugins.%s' % name in sys.modules)
 
94
        self.assertFalse(getattr(brzlib.plugins, name, None) is not None)
 
95
        self.assertFalse('brzlib.plugins.%s' % name in sys.modules)
85
96
 
86
97
    def assertPluginKnown(self, name):
87
 
        self.failUnless(getattr(bzrlib.plugins, name, None) is not None)
88
 
        self.failUnless('bzrlib.plugins.%s' % name in sys.modules)
89
 
 
90
 
 
91
 
class TestLoadingPlugins(tests.TestCaseInTempDir, TestPluginMixin):
 
98
        self.assertTrue(getattr(brzlib.plugins, name, None) is not None)
 
99
        self.assertTrue('brzlib.plugins.%s' % name in sys.modules)
 
100
 
 
101
 
 
102
class TestLoadingPlugins(BaseTestPlugins):
92
103
 
93
104
    activeattributes = {}
94
105
 
98
109
        # file name we can use which is also a valid attribute for accessing in
99
110
        # activeattributes. - we cannot give import parameters.
100
111
        tempattribute = "0"
101
 
        self.failIf(tempattribute in self.activeattributes)
 
112
        self.assertFalse(tempattribute in self.activeattributes)
102
113
        # set a place for the plugins to record their loading, and at the same
103
114
        # time validate that the location the plugins should record to is
104
115
        # valid and correct.
105
116
        self.__class__.activeattributes [tempattribute] = []
106
 
        self.failUnless(tempattribute in self.activeattributes)
 
117
        self.assertTrue(tempattribute in self.activeattributes)
107
118
        # create two plugin directories
108
119
        os.mkdir('first')
109
120
        os.mkdir('second')
110
121
        # write a plugin that will record when its loaded in the
111
122
        # tempattribute list.
112
 
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
 
123
        template = ("from brzlib.tests.test_plugins import TestLoadingPlugins\n"
113
124
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
114
125
 
115
126
        outfile = open(os.path.join('first', 'plugin.py'), 'w')
127
138
            outfile.close()
128
139
 
129
140
        try:
130
 
            bzrlib.plugin.load_from_path(['first', 'second'])
 
141
            brzlib.plugin.load_from_path(['first', 'second'])
131
142
            self.assertEqual(['first'], self.activeattributes[tempattribute])
132
143
        finally:
133
144
            # remove the plugin 'plugin'
136
147
        self.assertPluginUnknown('plugin')
137
148
 
138
149
    def test_plugins_from_different_dirs_can_demand_load(self):
139
 
        self.failIf('bzrlib.plugins.pluginone' in sys.modules)
140
 
        self.failIf('bzrlib.plugins.plugintwo' in sys.modules)
 
150
        self.assertFalse('brzlib.plugins.pluginone' in sys.modules)
 
151
        self.assertFalse('brzlib.plugins.plugintwo' in sys.modules)
141
152
        # This test tests that having two plugins in different
142
153
        # directories with different names allows them both to be loaded, when
143
154
        # we do a direct import statement.
144
155
        # Determine a file name we can use which is also a valid attribute
145
156
        # for accessing in activeattributes. - we cannot give import parameters.
146
157
        tempattribute = "different-dirs"
147
 
        self.failIf(tempattribute in self.activeattributes)
 
158
        self.assertFalse(tempattribute in self.activeattributes)
148
159
        # set a place for the plugins to record their loading, and at the same
149
160
        # time validate that the location the plugins should record to is
150
161
        # valid and correct.
151
 
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
162
        brzlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
152
163
            [tempattribute] = []
153
 
        self.failUnless(tempattribute in self.activeattributes)
 
164
        self.assertTrue(tempattribute in self.activeattributes)
154
165
        # create two plugin directories
155
166
        os.mkdir('first')
156
167
        os.mkdir('second')
157
168
        # write plugins that will record when they are loaded in the
158
169
        # tempattribute list.
159
 
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
 
170
        template = ("from brzlib.tests.test_plugins import TestLoadingPlugins\n"
160
171
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
161
172
 
162
173
        outfile = open(os.path.join('first', 'pluginone.py'), 'w')
173
184
        finally:
174
185
            outfile.close()
175
186
 
176
 
        oldpath = bzrlib.plugins.__path__
 
187
        oldpath = brzlib.plugins.__path__
177
188
        try:
178
 
            self.failIf('bzrlib.plugins.pluginone' in sys.modules)
179
 
            self.failIf('bzrlib.plugins.plugintwo' in sys.modules)
180
 
            bzrlib.plugins.__path__ = ['first', 'second']
181
 
            exec "import bzrlib.plugins.pluginone"
 
189
            self.assertFalse('brzlib.plugins.pluginone' in sys.modules)
 
190
            self.assertFalse('brzlib.plugins.plugintwo' in sys.modules)
 
191
            brzlib.plugins.__path__ = ['first', 'second']
 
192
            exec "import brzlib.plugins.pluginone"
182
193
            self.assertEqual(['first'], self.activeattributes[tempattribute])
183
 
            exec "import bzrlib.plugins.plugintwo"
 
194
            exec "import brzlib.plugins.plugintwo"
184
195
            self.assertEqual(['first', 'second'],
185
196
                self.activeattributes[tempattribute])
186
197
        finally:
197
208
        # check the plugin is not loaded already
198
209
        self.assertPluginUnknown('ts_plugin')
199
210
        tempattribute = "trailing-slash"
200
 
        self.failIf(tempattribute in self.activeattributes)
 
211
        self.assertFalse(tempattribute in self.activeattributes)
201
212
        # set a place for the plugin to record its loading, and at the same
202
213
        # time validate that the location the plugin should record to is
203
214
        # valid and correct.
204
 
        bzrlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
 
215
        brzlib.tests.test_plugins.TestLoadingPlugins.activeattributes \
205
216
            [tempattribute] = []
206
 
        self.failUnless(tempattribute in self.activeattributes)
 
217
        self.assertTrue(tempattribute in self.activeattributes)
207
218
        # create a directory for the plugin
208
219
        os.mkdir('plugin_test')
209
220
        # write a plugin that will record when its loaded in the
210
221
        # tempattribute list.
211
 
        template = ("from bzrlib.tests.test_plugins import TestLoadingPlugins\n"
 
222
        template = ("from brzlib.tests.test_plugins import TestLoadingPlugins\n"
212
223
                    "TestLoadingPlugins.activeattributes[%r].append('%s')\n")
213
224
 
214
225
        outfile = open(os.path.join('plugin_test', 'ts_plugin.py'), 'w')
219
230
            outfile.close()
220
231
 
221
232
        try:
222
 
            bzrlib.plugin.load_from_path(['plugin_test'+os.sep])
 
233
            brzlib.plugin.load_from_path(['plugin_test'+os.sep])
223
234
            self.assertEqual(['plugin'], self.activeattributes[tempattribute])
224
235
        finally:
225
236
            del self.activeattributes[tempattribute]
240
251
            log.addHandler(handler)
241
252
            try:
242
253
                try:
243
 
                    bzrlib.plugin.load_from_path(['.'])
 
254
                    brzlib.plugin.load_from_path(['.'])
244
255
                finally:
245
 
                    if 'bzrlib.plugins.%s' % name in sys.modules:
246
 
                        del sys.modules['bzrlib.plugins.%s' % name]
247
 
                    if getattr(bzrlib.plugins, name, None):
248
 
                        delattr(bzrlib.plugins, name)
 
256
                    if 'brzlib.plugins.%s' % name in sys.modules:
 
257
                        del sys.modules['brzlib.plugins.%s' % name]
 
258
                    if getattr(brzlib.plugins, name, None):
 
259
                        delattr(brzlib.plugins, name)
249
260
            finally:
250
261
                # Stop capturing output
251
262
                handler.flush()
256
267
            stream.close()
257
268
 
258
269
    def test_plugin_with_bad_api_version_reports(self):
259
 
        # This plugin asks for bzrlib api version 1.0.0, which is not supported
260
 
        # anymore.
 
270
        """Try loading a plugin that requests an unsupported api.
 
271
        
 
272
        Observe that it records the problem but doesn't complain on stderr.
 
273
 
 
274
        See https://bugs.launchpad.net/bzr/+bug/704195
 
275
        """
 
276
        self.overrideAttr(plugin, 'plugin_warnings', {})
261
277
        name = 'wants100.py'
262
278
        f = file(name, 'w')
263
279
        try:
264
 
            f.write("import bzrlib.api\n"
265
 
                "bzrlib.api.require_any_api(bzrlib, [(1, 0, 0)])\n")
 
280
            f.write("import brzlib.api\n"
 
281
                "brzlib.api.require_any_api(brzlib, [(1, 0, 0)])\n")
266
282
        finally:
267
283
            f.close()
268
 
 
269
284
        log = self.load_and_capture(name)
270
 
        self.assertContainsRe(log,
 
285
        self.assertNotContainsRe(log,
 
286
            r"It requested API version")
 
287
        self.assertEqual(
 
288
            ['wants100'],
 
289
            plugin.plugin_warnings.keys())
 
290
        self.assertContainsRe(
 
291
            plugin.plugin_warnings['wants100'][0],
271
292
            r"It requested API version")
272
293
 
273
294
    def test_plugin_with_bad_name_does_not_load(self):
281
302
            "it to 'bad_plugin_name_'\.")
282
303
 
283
304
 
284
 
class TestPlugins(tests.TestCaseInTempDir, TestPluginMixin):
 
305
class TestPlugins(BaseTestPlugins):
285
306
 
286
307
    def setup_plugin(self, source=""):
287
 
        # This test tests a new plugin appears in bzrlib.plugin.plugins().
 
308
        # This test tests a new plugin appears in brzlib.plugin.plugins().
288
309
        # check the plugin is not loaded already
289
310
        self.assertPluginUnknown('plugin')
290
311
        # write a plugin that _cannot_ fail to load.
291
 
        file('plugin.py', 'w').write(source + '\n')
 
312
        with file('plugin.py', 'w') as f: f.write(source + '\n')
292
313
        self.addCleanup(self.teardown_plugin)
293
314
        plugin.load_from_path(['.'])
294
315
 
300
321
        self.setup_plugin()
301
322
        self.assertPluginKnown('plugin')
302
323
        p = plugin.plugins()['plugin']
303
 
        self.assertIsInstance(p, bzrlib.plugin.PlugIn)
 
324
        self.assertIsInstance(p, brzlib.plugin.PlugIn)
304
325
        self.assertEqual(p.module, plugins.plugin)
305
326
 
306
327
    def test_trivial_plugin_get_path(self):
380
401
 
381
402
    def test_no_version_info___version__(self):
382
403
        self.setup_plugin()
383
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
404
        plugin = brzlib.plugin.plugins()['plugin']
384
405
        self.assertEqual("unknown", plugin.__version__)
385
406
 
386
407
    def test_str__version__with_version_info(self):
387
408
        self.setup_plugin("version_info = '1.2.3'")
388
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
409
        plugin = brzlib.plugin.plugins()['plugin']
389
410
        self.assertEqual("1.2.3", plugin.__version__)
390
411
 
391
412
    def test_noniterable__version__with_version_info(self):
392
413
        self.setup_plugin("version_info = (1)")
393
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
414
        plugin = brzlib.plugin.plugins()['plugin']
394
415
        self.assertEqual("1", plugin.__version__)
395
416
 
396
417
    def test_1__version__with_version_info(self):
397
418
        self.setup_plugin("version_info = (1,)")
398
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
419
        plugin = brzlib.plugin.plugins()['plugin']
399
420
        self.assertEqual("1", plugin.__version__)
400
421
 
401
422
    def test_1_2__version__with_version_info(self):
402
423
        self.setup_plugin("version_info = (1, 2)")
403
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
424
        plugin = brzlib.plugin.plugins()['plugin']
404
425
        self.assertEqual("1.2", plugin.__version__)
405
426
 
406
427
    def test_1_2_3__version__with_version_info(self):
407
428
        self.setup_plugin("version_info = (1, 2, 3)")
408
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
429
        plugin = brzlib.plugin.plugins()['plugin']
409
430
        self.assertEqual("1.2.3", plugin.__version__)
410
431
 
411
432
    def test_candidate__version__with_version_info(self):
412
433
        self.setup_plugin("version_info = (1, 2, 3, 'candidate', 1)")
413
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
434
        plugin = brzlib.plugin.plugins()['plugin']
414
435
        self.assertEqual("1.2.3rc1", plugin.__version__)
415
436
 
416
437
    def test_dev__version__with_version_info(self):
417
438
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 0)")
418
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
439
        plugin = brzlib.plugin.plugins()['plugin']
419
440
        self.assertEqual("1.2.3dev", plugin.__version__)
420
441
 
421
442
    def test_dev_fallback__version__with_version_info(self):
422
443
        self.setup_plugin("version_info = (1, 2, 3, 'dev', 4)")
423
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
444
        plugin = brzlib.plugin.plugins()['plugin']
424
445
        self.assertEqual("1.2.3dev4", plugin.__version__)
425
446
 
426
447
    def test_final__version__with_version_info(self):
427
448
        self.setup_plugin("version_info = (1, 2, 3, 'final', 0)")
428
 
        plugin = bzrlib.plugin.plugins()['plugin']
 
449
        plugin = brzlib.plugin.plugins()['plugin']
429
450
        self.assertEqual("1.2.3", plugin.__version__)
430
451
 
431
452
    def test_final_fallback__version__with_version_info(self):
432
453
        self.setup_plugin("version_info = (1, 2, 3, 'final', 2)")
433
 
        plugin = bzrlib.plugin.plugins()['plugin']
434
 
        self.assertEqual("1.2.3.final.2", plugin.__version__)
 
454
        plugin = brzlib.plugin.plugins()['plugin']
 
455
        self.assertEqual("1.2.3.2", plugin.__version__)
435
456
 
436
457
 
437
458
class TestPluginHelp(tests.TestCaseInTempDir):
450
471
    def test_plugin_help_builtins_unaffected(self):
451
472
        # Check we don't get false positives
452
473
        help_commands = self.split_help_commands()
453
 
        for cmd_name in bzrlib.commands.builtin_command_names():
454
 
            if cmd_name in bzrlib.commands.plugin_command_names():
 
474
        for cmd_name in brzlib.commands.builtin_command_names():
 
475
            if cmd_name in brzlib.commands.plugin_command_names():
455
476
                continue
456
477
            try:
457
 
                help = bzrlib.commands.get_cmd_object(cmd_name).get_help_text()
 
478
                help = brzlib.commands.get_cmd_object(cmd_name).get_help_text()
458
479
            except NotImplementedError:
459
480
                # some commands have no help
460
481
                pass
471
492
        os.mkdir('plugin_test')
472
493
        f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
473
494
        f.write("""\
474
 
from bzrlib import commands
 
495
from brzlib import commands
475
496
class cmd_myplug(commands.Command):
476
497
    __doc__ = '''Just a simple test plugin.'''
477
498
    aliases = ['mplg']
484
505
 
485
506
        try:
486
507
            # Check its help
487
 
            bzrlib.plugin.load_from_path(['plugin_test'])
488
 
            bzrlib.commands.register_command( bzrlib.plugins.myplug.cmd_myplug)
 
508
            brzlib.plugin.load_from_path(['plugin_test'])
 
509
            brzlib.commands.register_command( brzlib.plugins.myplug.cmd_myplug)
489
510
            help = self.run_bzr('help myplug')[0]
490
511
            self.assertContainsRe(help, 'plugin "myplug"')
491
512
            help = self.split_help_commands()['myplug']
492
513
            self.assertContainsRe(help, '\[myplug\]')
493
514
        finally:
494
515
            # unregister command
495
 
            if 'myplug' in bzrlib.commands.plugin_cmds:
496
 
                bzrlib.commands.plugin_cmds.remove('myplug')
 
516
            if 'myplug' in brzlib.commands.plugin_cmds:
 
517
                brzlib.commands.plugin_cmds.remove('myplug')
497
518
            # remove the plugin 'myplug'
498
 
            if getattr(bzrlib.plugins, 'myplug', None):
499
 
                delattr(bzrlib.plugins, 'myplug')
 
519
            if getattr(brzlib.plugins, 'myplug', None):
 
520
                delattr(brzlib.plugins, 'myplug')
500
521
 
501
522
 
502
523
class TestHelpIndex(tests.TestCase):
515
536
        index = plugin.PluginsHelpIndex()
516
537
        # make a new plugin here for this test, even if we're run with
517
538
        # --no-plugins
518
 
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
519
 
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
520
 
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
 
539
        self.assertFalse(sys.modules.has_key('brzlib.plugins.demo_module'))
 
540
        demo_module = FakeModule('', 'brzlib.plugins.demo_module')
 
541
        sys.modules['brzlib.plugins.demo_module'] = demo_module
521
542
        try:
522
543
            topics = index.get_topics('demo_module')
523
544
            self.assertEqual(1, len(topics))
524
545
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
525
546
            self.assertEqual(demo_module, topics[0].module)
526
547
        finally:
527
 
            del sys.modules['bzrlib.plugins.demo_module']
 
548
            del sys.modules['brzlib.plugins.demo_module']
528
549
 
529
550
    def test_get_topics_no_topic(self):
530
551
        """Searching for something that is not a plugin returns []."""
541
562
    def test_get_plugin_topic_with_prefix(self):
542
563
        """Searching for plugins/demo_module returns help."""
543
564
        index = plugin.PluginsHelpIndex()
544
 
        self.assertFalse(sys.modules.has_key('bzrlib.plugins.demo_module'))
545
 
        demo_module = FakeModule('', 'bzrlib.plugins.demo_module')
546
 
        sys.modules['bzrlib.plugins.demo_module'] = demo_module
 
565
        self.assertFalse(sys.modules.has_key('brzlib.plugins.demo_module'))
 
566
        demo_module = FakeModule('', 'brzlib.plugins.demo_module')
 
567
        sys.modules['brzlib.plugins.demo_module'] = demo_module
547
568
        try:
548
569
            topics = index.get_topics('plugins/demo_module')
549
570
            self.assertEqual(1, len(topics))
550
571
            self.assertIsInstance(topics[0], plugin.ModuleHelpTopic)
551
572
            self.assertEqual(demo_module, topics[0].module)
552
573
        finally:
553
 
            del sys.modules['bzrlib.plugins.demo_module']
 
574
            del sys.modules['brzlib.plugins.demo_module']
554
575
 
555
576
 
556
577
class FakeModule(object):
594
615
    def test_get_help_text_with_additional_see_also(self):
595
616
        mod = FakeModule('two lines of help\nand more', 'demo')
596
617
        topic = plugin.ModuleHelpTopic(mod)
597
 
        self.assertEqual("two lines of help\nand more\nSee also: bar, foo\n",
598
 
            topic.get_help_text(['foo', 'bar']))
 
618
        self.assertEqual("two lines of help\nand more\n\n:See also: bar, foo\n",
 
619
                         topic.get_help_text(['foo', 'bar']))
599
620
 
600
621
    def test_get_help_topic(self):
601
622
        """The help topic for a plugin is its module name."""
602
 
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.demo')
 
623
        mod = FakeModule('two lines of help\nand more', 'brzlib.plugins.demo')
603
624
        topic = plugin.ModuleHelpTopic(mod)
604
625
        self.assertEqual('demo', topic.get_help_topic())
605
 
        mod = FakeModule('two lines of help\nand more', 'bzrlib.plugins.foo_bar')
 
626
        mod = FakeModule('two lines of help\nand more',
 
627
                         'brzlib.plugins.foo_bar')
606
628
        topic = plugin.ModuleHelpTopic(mod)
607
629
        self.assertEqual('foo_bar', topic.get_help_topic())
608
630
 
611
633
 
612
634
    def setUp(self):
613
635
        super(TestLoadFromPath, self).setUp()
614
 
        # Change bzrlib.plugin to think no plugins have been loaded yet.
615
 
        self.overrideAttr(bzrlib.plugins, '__path__', [])
 
636
        # Change brzlib.plugin to think no plugins have been loaded yet.
 
637
        self.overrideAttr(brzlib.plugins, '__path__', [])
616
638
        self.overrideAttr(plugin, '_loaded', False)
617
639
 
618
640
        # Monkey-patch load_from_path to stop it from actually loading anything.
620
642
 
621
643
    def test_set_plugins_path_with_args(self):
622
644
        plugin.set_plugins_path(['a', 'b'])
623
 
        self.assertEqual(['a', 'b'], bzrlib.plugins.__path__)
 
645
        self.assertEqual(['a', 'b'], brzlib.plugins.__path__)
624
646
 
625
647
    def test_set_plugins_path_defaults(self):
626
648
        plugin.set_plugins_path()
627
649
        self.assertEqual(plugin.get_standard_plugins_path(),
628
 
                         bzrlib.plugins.__path__)
 
650
                         brzlib.plugins.__path__)
629
651
 
630
652
    def test_get_standard_plugins_path(self):
631
653
        path = plugin.get_standard_plugins_path()
645
667
                    self.fail('No path to global plugins')
646
668
 
647
669
    def test_get_standard_plugins_path_env(self):
648
 
        os.environ['BZR_PLUGIN_PATH'] = 'foo/'
 
670
        self.overrideEnv('BRZ_PLUGIN_PATH', 'foo/')
649
671
        path = plugin.get_standard_plugins_path()
650
672
        for directory in path:
651
673
            self.assertNotContainsRe(directory, r'\\/$')
652
674
 
653
675
    def test_load_plugins(self):
654
676
        plugin.load_plugins(['.'])
655
 
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
677
        self.assertEqual(brzlib.plugins.__path__, ['.'])
656
678
        # subsequent loads are no-ops
657
679
        plugin.load_plugins(['foo'])
658
 
        self.assertEqual(bzrlib.plugins.__path__, ['.'])
 
680
        self.assertEqual(brzlib.plugins.__path__, ['.'])
659
681
 
660
682
    def test_load_plugins_default(self):
661
683
        plugin.load_plugins()
662
684
        path = plugin.get_standard_plugins_path()
663
 
        self.assertEqual(path, bzrlib.plugins.__path__)
 
685
        self.assertEqual(path, brzlib.plugins.__path__)
664
686
 
665
687
 
666
688
class TestEnvPluginPath(tests.TestCase):
681
703
 
682
704
    def _set_path(self, *args):
683
705
        path = os.pathsep.join(self._list2paths(*args))
684
 
        osutils.set_or_unset_env('BZR_PLUGIN_PATH', path)
 
706
        self.overrideEnv('BRZ_PLUGIN_PATH', path)
685
707
 
686
708
    def check_path(self, expected_dirs, setting_dirs):
687
709
        if setting_dirs:
688
710
            self._set_path(*setting_dirs)
689
711
        actual = plugin.get_standard_plugins_path()
690
 
        self.assertEquals(self._list2paths(*expected_dirs), actual)
 
712
        self.assertEqual(self._list2paths(*expected_dirs), actual)
691
713
 
692
714
    def test_default(self):
693
715
        self.check_path([self.user, self.core, self.site],
757
779
                        ['+foo', '-bar'])
758
780
 
759
781
 
760
 
class TestDisablePlugin(tests.TestCaseInTempDir, TestPluginMixin):
 
782
class TestDisablePlugin(BaseTestPlugins):
761
783
 
762
784
    def setUp(self):
763
785
        super(TestDisablePlugin, self).setUp()
768
790
        self.addCleanup(self._unregister_plugin, 'test_foo')
769
791
 
770
792
    def test_cannot_import(self):
771
 
        osutils.set_or_unset_env('BZR_DISABLE_PLUGINS', 'test_foo')
 
793
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'test_foo')
772
794
        plugin.set_plugins_path(['.'])
773
795
        try:
774
 
            import bzrlib.plugins.test_foo
 
796
            import brzlib.plugins.test_foo
775
797
        except ImportError:
776
798
            pass
777
799
        self.assertPluginUnknown('test_foo')
781
803
        plugin.load_plugins(['.'])
782
804
        self.assertPluginKnown('test_foo')
783
805
        self.assertDocstring("This is the doc for test_foo",
784
 
                             bzrlib.plugins.test_foo)
 
806
                             brzlib.plugins.test_foo)
785
807
 
786
808
    def test_not_loaded(self):
787
809
        self.warnings = []
790
812
        self.overrideAttr(trace, 'warning', captured_warning)
791
813
        # Reset the flag that protect against double loading
792
814
        self.overrideAttr(plugin, '_loaded', False)
793
 
        osutils.set_or_unset_env('BZR_DISABLE_PLUGINS', 'test_foo')
 
815
        self.overrideEnv('BRZ_DISABLE_PLUGINS', 'test_foo')
794
816
        plugin.load_plugins(['.'])
795
817
        self.assertPluginUnknown('test_foo')
796
818
        # Make sure we don't warn about the plugin ImportError since this has
798
820
        self.assertLength(0, self.warnings)
799
821
 
800
822
 
801
 
class TestLoadPluginAt(tests.TestCaseInTempDir, TestPluginMixin):
 
823
 
 
824
class TestLoadPluginAtSyntax(tests.TestCase):
 
825
 
 
826
    def _get_paths(self, paths):
 
827
        return plugin._get_specific_plugin_paths(paths)
 
828
 
 
829
    def test_empty(self):
 
830
        self.assertEqual([], self._get_paths(None))
 
831
        self.assertEqual([], self._get_paths(''))
 
832
 
 
833
    def test_one_path(self):
 
834
        self.assertEqual([('b', 'man')], self._get_paths('b@man'))
 
835
 
 
836
    def test_bogus_path(self):
 
837
        # We need a '@'
 
838
        self.assertRaises(errors.BzrCommandError, self._get_paths, 'batman')
 
839
        # Too much '@' isn't good either
 
840
        self.assertRaises(errors.BzrCommandError, self._get_paths,
 
841
                          'batman@mobile@cave')
 
842
        # An empty description probably indicates a problem
 
843
        self.assertRaises(errors.BzrCommandError, self._get_paths,
 
844
                          os.pathsep.join(['batman@cave', '', 'robin@mobile']))
 
845
 
 
846
 
 
847
class TestLoadPluginAt(BaseTestPlugins):
802
848
 
803
849
    def setUp(self):
804
850
        super(TestLoadPluginAt, self).setUp()
805
851
        # Make sure we don't pollute the plugins namespace
806
852
        self.overrideAttr(plugins, '__path__')
807
 
        # Be paranoid in case a test fail
808
 
        self.addCleanup(self._unregister_plugin, 'test_foo')
809
853
        # Reset the flag that protect against double loading
810
854
        self.overrideAttr(plugin, '_loaded', False)
811
855
        # Create the same plugin in two directories
813
857
        # The "normal" directory, we use 'standard' instead of 'plugins' to
814
858
        # avoid depending on the precise naming.
815
859
        self.create_plugin_package('test_foo', dir='standard/test_foo')
 
860
        # All the tests will load the 'test_foo' plugin from various locations
 
861
        self.addCleanup(self._unregister_plugin, 'test_foo')
 
862
        # Unfortunately there's global cached state for the specific
 
863
        # registered paths.
 
864
        self.addCleanup(plugin.PluginImporter.reset)
816
865
 
817
866
    def assertTestFooLoadedFrom(self, path):
818
867
        self.assertPluginKnown('test_foo')
819
868
        self.assertDocstring('This is the doc for test_foo',
820
 
                             bzrlib.plugins.test_foo)
821
 
        self.assertEqual(path, bzrlib.plugins.test_foo.dir_source)
 
869
                             brzlib.plugins.test_foo)
 
870
        self.assertEqual(path, brzlib.plugins.test_foo.dir_source)
822
871
 
823
872
    def test_regular_load(self):
824
873
        plugin.load_plugins(['standard'])
825
874
        self.assertTestFooLoadedFrom('standard/test_foo')
826
875
 
827
876
    def test_import(self):
828
 
        osutils.set_or_unset_env('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
877
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
829
878
        plugin.set_plugins_path(['standard'])
830
879
        try:
831
 
            import bzrlib.plugins.test_foo
 
880
            import brzlib.plugins.test_foo
832
881
        except ImportError:
833
882
            pass
834
883
        self.assertTestFooLoadedFrom('non-standard-dir')
835
884
 
836
885
    def test_loading(self):
837
 
        osutils.set_or_unset_env('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
886
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
838
887
        plugin.load_plugins(['standard'])
839
888
        self.assertTestFooLoadedFrom('non-standard-dir')
840
889
 
841
890
    def test_compiled_loaded(self):
842
 
        osutils.set_or_unset_env('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
891
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
843
892
        plugin.load_plugins(['standard'])
844
893
        self.assertTestFooLoadedFrom('non-standard-dir')
845
 
        self.assertEqual('non-standard-dir/__init__.py',
846
 
                         bzrlib.plugins.test_foo.__file__)
 
894
        self.assertIsSameRealPath('non-standard-dir/__init__.py',
 
895
                                  brzlib.plugins.test_foo.__file__)
847
896
 
848
897
        # Try importing again now that the source has been compiled
849
898
        self._unregister_plugin('test_foo')
854
903
            suffix = 'pyc'
855
904
        else:
856
905
            suffix = 'pyo'
857
 
        self.assertEqual('non-standard-dir/__init__.%s' % suffix,
858
 
                         bzrlib.plugins.test_foo.__file__)
 
906
        self.assertIsSameRealPath('non-standard-dir/__init__.%s' % suffix,
 
907
                                  brzlib.plugins.test_foo.__file__)
859
908
 
860
909
    def test_submodule_loading(self):
861
910
        # We create an additional directory under the one for test_foo
862
911
        self.create_plugin_package('test_bar', dir='non-standard-dir/test_bar')
863
 
        osutils.set_or_unset_env('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
864
 
        plugin.set_plugins_path(['standard'])
865
 
        import bzrlib.plugins.test_foo
866
 
        self.assertEqual('bzrlib.plugins.test_foo',
867
 
                         bzrlib.plugins.test_foo.__package__)
868
 
        import bzrlib.plugins.test_foo.test_bar
869
 
        self.assertEqual('non-standard-dir/test_bar/__init__.py',
870
 
                         bzrlib.plugins.test_foo.test_bar.__file__)
 
912
        self.addCleanup(self._unregister_plugin_submodule,
 
913
                        'test_foo', 'test_bar')
 
914
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
 
915
        plugin.set_plugins_path(['standard'])
 
916
        import brzlib.plugins.test_foo
 
917
        self.assertEqual('brzlib.plugins.test_foo',
 
918
                         brzlib.plugins.test_foo.__package__)
 
919
        import brzlib.plugins.test_foo.test_bar
 
920
        self.assertIsSameRealPath('non-standard-dir/test_bar/__init__.py',
 
921
                                  brzlib.plugins.test_foo.test_bar.__file__)
 
922
 
 
923
    def test_relative_submodule_loading(self):
 
924
        self.create_plugin_package('test_foo', dir='another-dir', source='''
 
925
import test_bar
 
926
''')
 
927
        # We create an additional directory under the one for test_foo
 
928
        self.create_plugin_package('test_bar', dir='another-dir/test_bar')
 
929
        self.addCleanup(self._unregister_plugin_submodule,
 
930
                        'test_foo', 'test_bar')
 
931
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@another-dir')
 
932
        plugin.set_plugins_path(['standard'])
 
933
        import brzlib.plugins.test_foo
 
934
        self.assertEqual('brzlib.plugins.test_foo',
 
935
                         brzlib.plugins.test_foo.__package__)
 
936
        self.assertIsSameRealPath('another-dir/test_bar/__init__.py',
 
937
                                  brzlib.plugins.test_foo.test_bar.__file__)
871
938
 
872
939
    def test_loading_from___init__only(self):
873
940
        # We rename the existing __init__.py file to ensure that we don't load
876
943
        random = 'non-standard-dir/setup.py'
877
944
        os.rename(init, random)
878
945
        self.addCleanup(os.rename, random, init)
879
 
        osutils.set_or_unset_env('BZR_PLUGINS_AT', 'test_foo@non-standard-dir')
 
946
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@non-standard-dir')
880
947
        plugin.load_plugins(['standard'])
881
948
        self.assertPluginUnknown('test_foo')
882
949
 
890
957
''' % ('test_foo', plugin_path)
891
958
        self.create_plugin('test_foo', source=source,
892
959
                           dir=plugin_dir, file_name=plugin_file_name)
893
 
        osutils.set_or_unset_env('BZR_PLUGINS_AT', 'test_foo@%s' % plugin_path)
 
960
        self.overrideEnv('BRZ_PLUGINS_AT', 'test_foo@%s' % plugin_path)
894
961
        plugin.load_plugins(['standard'])
895
962
        self.assertTestFooLoadedFrom(plugin_path)
 
963
 
 
964
 
 
965
class TestDescribePlugins(BaseTestPlugins):
 
966
 
 
967
    def test_describe_plugins(self):
 
968
        class DummyModule(object):
 
969
            __doc__ = 'Hi there'
 
970
        class DummyPlugin(object):
 
971
            __version__ = '0.1.0'
 
972
            module = DummyModule()
 
973
        def dummy_plugins():
 
974
            return { 'good': DummyPlugin() }
 
975
        self.overrideAttr(plugin, 'plugin_warnings',
 
976
            {'bad': ['Failed to load (just testing)']})
 
977
        self.overrideAttr(plugin, 'plugins', dummy_plugins)
 
978
        self.assertEqual("""\
 
979
bad (failed to load)
 
980
  ** Failed to load (just testing)
 
981
 
 
982
good 0.1.0
 
983
  Hi there
 
984
 
 
985
""", ''.join(plugin.describe_plugins()))