/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 bzrlib/tests/test_selftest.py

  • Committer: John Arbash Meinel
  • Date: 2009-12-03 20:34:03 UTC
  • mto: This revision was merged to the branch mainline in revision 4865.
  • Revision ID: john@arbash-meinel.com-20091203203403-cww6ez5nvp616c85
Found the failed-to-unlocked branches in test_remote.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for the test framework."""
 
18
 
 
19
from cStringIO import StringIO
 
20
import os
 
21
import signal
 
22
import sys
 
23
import time
 
24
import unittest
 
25
import warnings
 
26
 
 
27
import bzrlib
 
28
from bzrlib import (
 
29
    branchbuilder,
 
30
    bzrdir,
 
31
    debug,
 
32
    errors,
 
33
    lockdir,
 
34
    memorytree,
 
35
    osutils,
 
36
    progress,
 
37
    remote,
 
38
    repository,
 
39
    symbol_versioning,
 
40
    tests,
 
41
    transport,
 
42
    workingtree,
 
43
    )
 
44
from bzrlib.repofmt import (
 
45
    groupcompress_repo,
 
46
    pack_repo,
 
47
    weaverepo,
 
48
    )
 
49
from bzrlib.symbol_versioning import (
 
50
    deprecated_function,
 
51
    deprecated_in,
 
52
    deprecated_method,
 
53
    )
 
54
from bzrlib.tests import (
 
55
    SubUnitFeature,
 
56
    test_lsprof,
 
57
    test_sftp_transport,
 
58
    TestUtil,
 
59
    )
 
60
from bzrlib.trace import note
 
61
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
62
from bzrlib.version import _get_bzr_source_tree
 
63
 
 
64
 
 
65
def _test_ids(test_suite):
 
66
    """Get the ids for the tests in a test suite."""
 
67
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
68
 
 
69
 
 
70
class SelftestTests(tests.TestCase):
 
71
 
 
72
    def test_import_tests(self):
 
73
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
74
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
75
 
 
76
    def test_import_test_failure(self):
 
77
        self.assertRaises(ImportError,
 
78
                          TestUtil._load_module_by_name,
 
79
                          'bzrlib.no-name-yet')
 
80
 
 
81
class MetaTestLog(tests.TestCase):
 
82
 
 
83
    def test_logging(self):
 
84
        """Test logs are captured when a test fails."""
 
85
        self.log('a test message')
 
86
        self._log_file.flush()
 
87
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
88
                              'a test message\n')
 
89
 
 
90
 
 
91
class TestUnicodeFilename(tests.TestCase):
 
92
 
 
93
    def test_probe_passes(self):
 
94
        """UnicodeFilename._probe passes."""
 
95
        # We can't test much more than that because the behaviour depends
 
96
        # on the platform.
 
97
        tests.UnicodeFilename._probe()
 
98
 
 
99
 
 
100
class TestTreeShape(tests.TestCaseInTempDir):
 
101
 
 
102
    def test_unicode_paths(self):
 
103
        self.requireFeature(tests.UnicodeFilename)
 
104
 
 
105
        filename = u'hell\u00d8'
 
106
        self.build_tree_contents([(filename, 'contents of hello')])
 
107
        self.failUnlessExists(filename)
 
108
 
 
109
 
 
110
class TestTransportScenarios(tests.TestCase):
 
111
    """A group of tests that test the transport implementation adaption core.
 
112
 
 
113
    This is a meta test that the tests are applied to all available
 
114
    transports.
 
115
 
 
116
    This will be generalised in the future which is why it is in this
 
117
    test file even though it is specific to transport tests at the moment.
 
118
    """
 
119
 
 
120
    def test_get_transport_permutations(self):
 
121
        # this checks that get_test_permutations defined by the module is
 
122
        # called by the get_transport_test_permutations function.
 
123
        class MockModule(object):
 
124
            def get_test_permutations(self):
 
125
                return sample_permutation
 
126
        sample_permutation = [(1,2), (3,4)]
 
127
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
128
        self.assertEqual(sample_permutation,
 
129
                         get_transport_test_permutations(MockModule()))
 
130
 
 
131
    def test_scenarios_include_all_modules(self):
 
132
        # this checks that the scenario generator returns as many permutations
 
133
        # as there are in all the registered transport modules - we assume if
 
134
        # this matches its probably doing the right thing especially in
 
135
        # combination with the tests for setting the right classes below.
 
136
        from bzrlib.tests.per_transport import transport_test_permutations
 
137
        from bzrlib.transport import _get_transport_modules
 
138
        modules = _get_transport_modules()
 
139
        permutation_count = 0
 
140
        for module in modules:
 
141
            try:
 
142
                permutation_count += len(reduce(getattr,
 
143
                    (module + ".get_test_permutations").split('.')[1:],
 
144
                     __import__(module))())
 
145
            except errors.DependencyNotPresent:
 
146
                pass
 
147
        scenarios = transport_test_permutations()
 
148
        self.assertEqual(permutation_count, len(scenarios))
 
149
 
 
150
    def test_scenarios_include_transport_class(self):
 
151
        # This test used to know about all the possible transports and the
 
152
        # order they were returned but that seems overly brittle (mbp
 
153
        # 20060307)
 
154
        from bzrlib.tests.per_transport import transport_test_permutations
 
155
        scenarios = transport_test_permutations()
 
156
        # there are at least that many builtin transports
 
157
        self.assertTrue(len(scenarios) > 6)
 
158
        one_scenario = scenarios[0]
 
159
        self.assertIsInstance(one_scenario[0], str)
 
160
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
161
                                   bzrlib.transport.Transport))
 
162
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
163
                                   bzrlib.transport.Server))
 
164
 
 
165
 
 
166
class TestBranchScenarios(tests.TestCase):
 
167
 
 
168
    def test_scenarios(self):
 
169
        # check that constructor parameters are passed through to the adapted
 
170
        # test.
 
171
        from bzrlib.tests.per_branch import make_scenarios
 
172
        server1 = "a"
 
173
        server2 = "b"
 
174
        formats = [("c", "C"), ("d", "D")]
 
175
        scenarios = make_scenarios(server1, server2, formats)
 
176
        self.assertEqual(2, len(scenarios))
 
177
        self.assertEqual([
 
178
            ('str',
 
179
             {'branch_format': 'c',
 
180
              'bzrdir_format': 'C',
 
181
              'transport_readonly_server': 'b',
 
182
              'transport_server': 'a'}),
 
183
            ('str',
 
184
             {'branch_format': 'd',
 
185
              'bzrdir_format': 'D',
 
186
              'transport_readonly_server': 'b',
 
187
              'transport_server': 'a'})],
 
188
            scenarios)
 
189
 
 
190
 
 
191
class TestBzrDirScenarios(tests.TestCase):
 
192
 
 
193
    def test_scenarios(self):
 
194
        # check that constructor parameters are passed through to the adapted
 
195
        # test.
 
196
        from bzrlib.tests.per_bzrdir import make_scenarios
 
197
        vfs_factory = "v"
 
198
        server1 = "a"
 
199
        server2 = "b"
 
200
        formats = ["c", "d"]
 
201
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
 
202
        self.assertEqual([
 
203
            ('str',
 
204
             {'bzrdir_format': 'c',
 
205
              'transport_readonly_server': 'b',
 
206
              'transport_server': 'a',
 
207
              'vfs_transport_factory': 'v'}),
 
208
            ('str',
 
209
             {'bzrdir_format': 'd',
 
210
              'transport_readonly_server': 'b',
 
211
              'transport_server': 'a',
 
212
              'vfs_transport_factory': 'v'})],
 
213
            scenarios)
 
214
 
 
215
 
 
216
class TestRepositoryScenarios(tests.TestCase):
 
217
 
 
218
    def test_formats_to_scenarios(self):
 
219
        from bzrlib.tests.per_repository import formats_to_scenarios
 
220
        formats = [("(c)", remote.RemoteRepositoryFormat()),
 
221
                   ("(d)", repository.format_registry.get(
 
222
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
 
223
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
224
            None)
 
225
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
226
            vfs_transport_factory="vfs")
 
227
        # no_vfs generate scenarios without vfs_transport_factory
 
228
        expected = [
 
229
            ('RemoteRepositoryFormat(c)',
 
230
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
231
              'repository_format': remote.RemoteRepositoryFormat(),
 
232
              'transport_readonly_server': 'readonly',
 
233
              'transport_server': 'server'}),
 
234
            ('RepositoryFormat2a(d)',
 
235
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
236
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
 
237
              'transport_readonly_server': 'readonly',
 
238
              'transport_server': 'server'})]
 
239
        self.assertEqual(expected, no_vfs_scenarios)
 
240
        self.assertEqual([
 
241
            ('RemoteRepositoryFormat(c)',
 
242
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
243
              'repository_format': remote.RemoteRepositoryFormat(),
 
244
              'transport_readonly_server': 'readonly',
 
245
              'transport_server': 'server',
 
246
              'vfs_transport_factory': 'vfs'}),
 
247
            ('RepositoryFormat2a(d)',
 
248
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
249
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
 
250
              'transport_readonly_server': 'readonly',
 
251
              'transport_server': 'server',
 
252
              'vfs_transport_factory': 'vfs'})],
 
253
            vfs_scenarios)
 
254
 
 
255
 
 
256
class TestTestScenarioApplication(tests.TestCase):
 
257
    """Tests for the test adaption facilities."""
 
258
 
 
259
    def test_apply_scenario(self):
 
260
        from bzrlib.tests import apply_scenario
 
261
        input_test = TestTestScenarioApplication("test_apply_scenario")
 
262
        # setup two adapted tests
 
263
        adapted_test1 = apply_scenario(input_test,
 
264
            ("new id",
 
265
            {"bzrdir_format":"bzr_format",
 
266
             "repository_format":"repo_fmt",
 
267
             "transport_server":"transport_server",
 
268
             "transport_readonly_server":"readonly-server"}))
 
269
        adapted_test2 = apply_scenario(input_test,
 
270
            ("new id 2", {"bzrdir_format":None}))
 
271
        # input_test should have been altered.
 
272
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
 
273
        # the new tests are mutually incompatible, ensuring it has
 
274
        # made new ones, and unspecified elements in the scenario
 
275
        # should not have been altered.
 
276
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
 
277
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
 
278
        self.assertEqual("transport_server", adapted_test1.transport_server)
 
279
        self.assertEqual("readonly-server",
 
280
            adapted_test1.transport_readonly_server)
 
281
        self.assertEqual(
 
282
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
283
            "test_apply_scenario(new id)",
 
284
            adapted_test1.id())
 
285
        self.assertEqual(None, adapted_test2.bzrdir_format)
 
286
        self.assertEqual(
 
287
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
288
            "test_apply_scenario(new id 2)",
 
289
            adapted_test2.id())
 
290
 
 
291
 
 
292
class TestInterRepositoryScenarios(tests.TestCase):
 
293
 
 
294
    def test_scenarios(self):
 
295
        # check that constructor parameters are passed through to the adapted
 
296
        # test.
 
297
        from bzrlib.tests.per_interrepository import make_scenarios
 
298
        server1 = "a"
 
299
        server2 = "b"
 
300
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
 
301
        scenarios = make_scenarios(server1, server2, formats)
 
302
        self.assertEqual([
 
303
            ('C0,str,str',
 
304
             {'repository_format': 'C1',
 
305
              'repository_format_to': 'C2',
 
306
              'transport_readonly_server': 'b',
 
307
              'transport_server': 'a'}),
 
308
            ('D0,str,str',
 
309
             {'repository_format': 'D1',
 
310
              'repository_format_to': 'D2',
 
311
              'transport_readonly_server': 'b',
 
312
              'transport_server': 'a'})],
 
313
            scenarios)
 
314
 
 
315
 
 
316
class TestWorkingTreeScenarios(tests.TestCase):
 
317
 
 
318
    def test_scenarios(self):
 
319
        # check that constructor parameters are passed through to the adapted
 
320
        # test.
 
321
        from bzrlib.tests.per_workingtree import make_scenarios
 
322
        server1 = "a"
 
323
        server2 = "b"
 
324
        formats = [workingtree.WorkingTreeFormat2(),
 
325
                   workingtree.WorkingTreeFormat3(),]
 
326
        scenarios = make_scenarios(server1, server2, formats)
 
327
        self.assertEqual([
 
328
            ('WorkingTreeFormat2',
 
329
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
330
              'transport_readonly_server': 'b',
 
331
              'transport_server': 'a',
 
332
              'workingtree_format': formats[0]}),
 
333
            ('WorkingTreeFormat3',
 
334
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
335
              'transport_readonly_server': 'b',
 
336
              'transport_server': 'a',
 
337
              'workingtree_format': formats[1]})],
 
338
            scenarios)
 
339
 
 
340
 
 
341
class TestTreeScenarios(tests.TestCase):
 
342
 
 
343
    def test_scenarios(self):
 
344
        # the tree implementation scenario generator is meant to setup one
 
345
        # instance for each working tree format, and one additional instance
 
346
        # that will use the default wt format, but create a revision tree for
 
347
        # the tests.  this means that the wt ones should have the
 
348
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
 
349
        # revision one set to revision_tree_from_workingtree.
 
350
 
 
351
        from bzrlib.tests.per_tree import (
 
352
            _dirstate_tree_from_workingtree,
 
353
            make_scenarios,
 
354
            preview_tree_pre,
 
355
            preview_tree_post,
 
356
            return_parameter,
 
357
            revision_tree_from_workingtree
 
358
            )
 
359
        server1 = "a"
 
360
        server2 = "b"
 
361
        formats = [workingtree.WorkingTreeFormat2(),
 
362
                   workingtree.WorkingTreeFormat3(),]
 
363
        scenarios = make_scenarios(server1, server2, formats)
 
364
        self.assertEqual(7, len(scenarios))
 
365
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
366
        wt4_format = workingtree.WorkingTreeFormat4()
 
367
        wt5_format = workingtree.WorkingTreeFormat5()
 
368
        expected_scenarios = [
 
369
            ('WorkingTreeFormat2',
 
370
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
371
              'transport_readonly_server': 'b',
 
372
              'transport_server': 'a',
 
373
              'workingtree_format': formats[0],
 
374
              '_workingtree_to_test_tree': return_parameter,
 
375
              }),
 
376
            ('WorkingTreeFormat3',
 
377
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
378
              'transport_readonly_server': 'b',
 
379
              'transport_server': 'a',
 
380
              'workingtree_format': formats[1],
 
381
              '_workingtree_to_test_tree': return_parameter,
 
382
             }),
 
383
            ('RevisionTree',
 
384
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
 
385
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
386
              'transport_readonly_server': 'b',
 
387
              'transport_server': 'a',
 
388
              'workingtree_format': default_wt_format,
 
389
             }),
 
390
            ('DirStateRevisionTree,WT4',
 
391
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
392
              'bzrdir_format': wt4_format._matchingbzrdir,
 
393
              'transport_readonly_server': 'b',
 
394
              'transport_server': 'a',
 
395
              'workingtree_format': wt4_format,
 
396
             }),
 
397
            ('DirStateRevisionTree,WT5',
 
398
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
399
              'bzrdir_format': wt5_format._matchingbzrdir,
 
400
              'transport_readonly_server': 'b',
 
401
              'transport_server': 'a',
 
402
              'workingtree_format': wt5_format,
 
403
             }),
 
404
            ('PreviewTree',
 
405
             {'_workingtree_to_test_tree': preview_tree_pre,
 
406
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
407
              'transport_readonly_server': 'b',
 
408
              'transport_server': 'a',
 
409
              'workingtree_format': default_wt_format}),
 
410
            ('PreviewTreePost',
 
411
             {'_workingtree_to_test_tree': preview_tree_post,
 
412
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
413
              'transport_readonly_server': 'b',
 
414
              'transport_server': 'a',
 
415
              'workingtree_format': default_wt_format}),
 
416
             ]
 
417
        self.assertEqual(expected_scenarios, scenarios)
 
418
 
 
419
 
 
420
class TestInterTreeScenarios(tests.TestCase):
 
421
    """A group of tests that test the InterTreeTestAdapter."""
 
422
 
 
423
    def test_scenarios(self):
 
424
        # check that constructor parameters are passed through to the adapted
 
425
        # test.
 
426
        # for InterTree tests we want the machinery to bring up two trees in
 
427
        # each instance: the base one, and the one we are interacting with.
 
428
        # because each optimiser can be direction specific, we need to test
 
429
        # each optimiser in its chosen direction.
 
430
        # unlike the TestProviderAdapter we dont want to automatically add a
 
431
        # parameterized one for WorkingTree - the optimisers will tell us what
 
432
        # ones to add.
 
433
        from bzrlib.tests.per_tree import (
 
434
            return_parameter,
 
435
            revision_tree_from_workingtree
 
436
            )
 
437
        from bzrlib.tests.per_intertree import (
 
438
            make_scenarios,
 
439
            )
 
440
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
441
        input_test = TestInterTreeScenarios(
 
442
            "test_scenarios")
 
443
        server1 = "a"
 
444
        server2 = "b"
 
445
        format1 = WorkingTreeFormat2()
 
446
        format2 = WorkingTreeFormat3()
 
447
        formats = [("1", str, format1, format2, "converter1"),
 
448
            ("2", int, format2, format1, "converter2")]
 
449
        scenarios = make_scenarios(server1, server2, formats)
 
450
        self.assertEqual(2, len(scenarios))
 
451
        expected_scenarios = [
 
452
            ("1", {
 
453
                "bzrdir_format": format1._matchingbzrdir,
 
454
                "intertree_class": formats[0][1],
 
455
                "workingtree_format": formats[0][2],
 
456
                "workingtree_format_to": formats[0][3],
 
457
                "mutable_trees_to_test_trees": formats[0][4],
 
458
                "_workingtree_to_test_tree": return_parameter,
 
459
                "transport_server": server1,
 
460
                "transport_readonly_server": server2,
 
461
                }),
 
462
            ("2", {
 
463
                "bzrdir_format": format2._matchingbzrdir,
 
464
                "intertree_class": formats[1][1],
 
465
                "workingtree_format": formats[1][2],
 
466
                "workingtree_format_to": formats[1][3],
 
467
                "mutable_trees_to_test_trees": formats[1][4],
 
468
                "_workingtree_to_test_tree": return_parameter,
 
469
                "transport_server": server1,
 
470
                "transport_readonly_server": server2,
 
471
                }),
 
472
            ]
 
473
        self.assertEqual(scenarios, expected_scenarios)
 
474
 
 
475
 
 
476
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
 
477
 
 
478
    def test_home_is_not_working(self):
 
479
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
480
        cwd = osutils.getcwd()
 
481
        self.assertIsSameRealPath(self.test_dir, cwd)
 
482
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
483
 
 
484
    def test_assertEqualStat_equal(self):
 
485
        from bzrlib.tests.test_dirstate import _FakeStat
 
486
        self.build_tree(["foo"])
 
487
        real = os.lstat("foo")
 
488
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
 
489
            real.st_dev, real.st_ino, real.st_mode)
 
490
        self.assertEqualStat(real, fake)
 
491
 
 
492
    def test_assertEqualStat_notequal(self):
 
493
        self.build_tree(["foo", "longname"])
 
494
        self.assertRaises(AssertionError, self.assertEqualStat,
 
495
            os.lstat("foo"), os.lstat("longname"))
 
496
 
 
497
 
 
498
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
 
499
 
 
500
    def test_home_is_non_existant_dir_under_root(self):
 
501
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
502
 
 
503
        This is because TestCaseWithMemoryTransport is for tests that do not
 
504
        need any disk resources: they should be hooked into bzrlib in such a
 
505
        way that no global settings are being changed by the test (only a
 
506
        few tests should need to do that), and having a missing dir as home is
 
507
        an effective way to ensure that this is the case.
 
508
        """
 
509
        self.assertIsSameRealPath(
 
510
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
511
            self.test_home_dir)
 
512
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
513
 
 
514
    def test_cwd_is_TEST_ROOT(self):
 
515
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
516
        cwd = osutils.getcwd()
 
517
        self.assertIsSameRealPath(self.test_dir, cwd)
 
518
 
 
519
    def test_BZR_HOME_and_HOME_are_bytestrings(self):
 
520
        """The $BZR_HOME and $HOME environment variables should not be unicode.
 
521
 
 
522
        See https://bugs.launchpad.net/bzr/+bug/464174
 
523
        """
 
524
        self.assertIsInstance(os.environ['BZR_HOME'], str)
 
525
        self.assertIsInstance(os.environ['HOME'], str)
 
526
 
 
527
    def test_make_branch_and_memory_tree(self):
 
528
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
529
 
 
530
        This is hard to comprehensively robustly test, so we settle for making
 
531
        a branch and checking no directory was created at its relpath.
 
532
        """
 
533
        tree = self.make_branch_and_memory_tree('dir')
 
534
        # Guard against regression into MemoryTransport leaking
 
535
        # files to disk instead of keeping them in memory.
 
536
        self.failIf(osutils.lexists('dir'))
 
537
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
538
 
 
539
    def test_make_branch_and_memory_tree_with_format(self):
 
540
        """make_branch_and_memory_tree should accept a format option."""
 
541
        format = bzrdir.BzrDirMetaFormat1()
 
542
        format.repository_format = weaverepo.RepositoryFormat7()
 
543
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
544
        # Guard against regression into MemoryTransport leaking
 
545
        # files to disk instead of keeping them in memory.
 
546
        self.failIf(osutils.lexists('dir'))
 
547
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
548
        self.assertEqual(format.repository_format.__class__,
 
549
            tree.branch.repository._format.__class__)
 
550
 
 
551
    def test_make_branch_builder(self):
 
552
        builder = self.make_branch_builder('dir')
 
553
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
 
554
        # Guard against regression into MemoryTransport leaking
 
555
        # files to disk instead of keeping them in memory.
 
556
        self.failIf(osutils.lexists('dir'))
 
557
 
 
558
    def test_make_branch_builder_with_format(self):
 
559
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
 
560
        # that the format objects are used.
 
561
        format = bzrdir.BzrDirMetaFormat1()
 
562
        repo_format = weaverepo.RepositoryFormat7()
 
563
        format.repository_format = repo_format
 
564
        builder = self.make_branch_builder('dir', format=format)
 
565
        the_branch = builder.get_branch()
 
566
        # Guard against regression into MemoryTransport leaking
 
567
        # files to disk instead of keeping them in memory.
 
568
        self.failIf(osutils.lexists('dir'))
 
569
        self.assertEqual(format.repository_format.__class__,
 
570
                         the_branch.repository._format.__class__)
 
571
        self.assertEqual(repo_format.get_format_string(),
 
572
                         self.get_transport().get_bytes(
 
573
                            'dir/.bzr/repository/format'))
 
574
 
 
575
    def test_make_branch_builder_with_format_name(self):
 
576
        builder = self.make_branch_builder('dir', format='knit')
 
577
        the_branch = builder.get_branch()
 
578
        # Guard against regression into MemoryTransport leaking
 
579
        # files to disk instead of keeping them in memory.
 
580
        self.failIf(osutils.lexists('dir'))
 
581
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
582
        self.assertEqual(dir_format.repository_format.__class__,
 
583
                         the_branch.repository._format.__class__)
 
584
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
585
                         self.get_transport().get_bytes(
 
586
                            'dir/.bzr/repository/format'))
 
587
 
 
588
    def test_dangling_locks_cause_failures(self):
 
589
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
 
590
            def test_function(self):
 
591
                t = self.get_transport('.')
 
592
                l = lockdir.LockDir(t, 'lock')
 
593
                l.create()
 
594
                l.attempt_lock()
 
595
        test = TestDanglingLock('test_function')
 
596
        result = test.run()
 
597
        if self._lock_check_thorough:
 
598
            self.assertEqual(1, len(result.errors))
 
599
        else:
 
600
            # When _lock_check_thorough is disabled, then we don't trigger a
 
601
            # failure
 
602
            self.assertEqual(0, len(result.errors))
 
603
 
 
604
 
 
605
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
 
606
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
607
 
 
608
    def test_get_readonly_url_none(self):
 
609
        from bzrlib.transport import get_transport
 
610
        from bzrlib.transport.memory import MemoryServer
 
611
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
612
        self.vfs_transport_factory = MemoryServer
 
613
        self.transport_readonly_server = None
 
614
        # calling get_readonly_transport() constructs a decorator on the url
 
615
        # for the server
 
616
        url = self.get_readonly_url()
 
617
        url2 = self.get_readonly_url('foo/bar')
 
618
        t = get_transport(url)
 
619
        t2 = get_transport(url2)
 
620
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
621
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
622
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
623
 
 
624
    def test_get_readonly_url_http(self):
 
625
        from bzrlib.tests.http_server import HttpServer
 
626
        from bzrlib.transport import get_transport
 
627
        from bzrlib.transport.local import LocalURLServer
 
628
        from bzrlib.transport.http import HttpTransportBase
 
629
        self.transport_server = LocalURLServer
 
630
        self.transport_readonly_server = HttpServer
 
631
        # calling get_readonly_transport() gives us a HTTP server instance.
 
632
        url = self.get_readonly_url()
 
633
        url2 = self.get_readonly_url('foo/bar')
 
634
        # the transport returned may be any HttpTransportBase subclass
 
635
        t = get_transport(url)
 
636
        t2 = get_transport(url2)
 
637
        self.failUnless(isinstance(t, HttpTransportBase))
 
638
        self.failUnless(isinstance(t2, HttpTransportBase))
 
639
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
640
 
 
641
    def test_is_directory(self):
 
642
        """Test assertIsDirectory assertion"""
 
643
        t = self.get_transport()
 
644
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
645
        self.assertIsDirectory('a_dir', t)
 
646
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
647
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
648
 
 
649
    def test_make_branch_builder(self):
 
650
        builder = self.make_branch_builder('dir')
 
651
        rev_id = builder.build_commit()
 
652
        self.failUnlessExists('dir')
 
653
        a_dir = bzrdir.BzrDir.open('dir')
 
654
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
 
655
        a_branch = a_dir.open_branch()
 
656
        builder_branch = builder.get_branch()
 
657
        self.assertEqual(a_branch.base, builder_branch.base)
 
658
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
 
659
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
 
660
 
 
661
 
 
662
class TestTestCaseTransports(tests.TestCaseWithTransport):
 
663
 
 
664
    def setUp(self):
 
665
        super(TestTestCaseTransports, self).setUp()
 
666
        self.vfs_transport_factory = MemoryServer
 
667
 
 
668
    def test_make_bzrdir_preserves_transport(self):
 
669
        t = self.get_transport()
 
670
        result_bzrdir = self.make_bzrdir('subdir')
 
671
        self.assertIsInstance(result_bzrdir.transport,
 
672
                              MemoryTransport)
 
673
        # should not be on disk, should only be in memory
 
674
        self.failIfExists('subdir')
 
675
 
 
676
 
 
677
class TestChrootedTest(tests.ChrootedTestCase):
 
678
 
 
679
    def test_root_is_root(self):
 
680
        from bzrlib.transport import get_transport
 
681
        t = get_transport(self.get_readonly_url())
 
682
        url = t.base
 
683
        self.assertEqual(url, t.clone('..').base)
 
684
 
 
685
 
 
686
class TestProfileResult(tests.TestCase):
 
687
 
 
688
    def test_profiles_tests(self):
 
689
        self.requireFeature(test_lsprof.LSProfFeature)
 
690
        terminal = unittest.TestResult()
 
691
        result = tests.ProfileResult(terminal)
 
692
        class Sample(tests.TestCase):
 
693
            def a(self):
 
694
                self.sample_function()
 
695
            def sample_function(self):
 
696
                pass
 
697
        test = Sample("a")
 
698
        test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
 
699
        test.run(result)
 
700
        self.assertLength(1, test._benchcalls)
 
701
        # We must be able to unpack it as the test reporting code wants
 
702
        (_, _, _), stats = test._benchcalls[0]
 
703
        self.assertTrue(callable(stats.pprint))
 
704
 
 
705
 
 
706
class TestTestResult(tests.TestCase):
 
707
 
 
708
    def check_timing(self, test_case, expected_re):
 
709
        result = bzrlib.tests.TextTestResult(self._log_file,
 
710
                descriptions=0,
 
711
                verbosity=1,
 
712
                )
 
713
        test_case.run(result)
 
714
        timed_string = result._testTimeString(test_case)
 
715
        self.assertContainsRe(timed_string, expected_re)
 
716
 
 
717
    def test_test_reporting(self):
 
718
        class ShortDelayTestCase(tests.TestCase):
 
719
            def test_short_delay(self):
 
720
                time.sleep(0.003)
 
721
            def test_short_benchmark(self):
 
722
                self.time(time.sleep, 0.003)
 
723
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
724
                          r"^ +[0-9]+ms$")
 
725
        # if a benchmark time is given, we now show just that time followed by
 
726
        # a star
 
727
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
 
728
                          r"^ +[0-9]+ms\*$")
 
729
 
 
730
    def test_unittest_reporting_unittest_class(self):
 
731
        # getting the time from a non-bzrlib test works ok
 
732
        class ShortDelayTestCase(unittest.TestCase):
 
733
            def test_short_delay(self):
 
734
                time.sleep(0.003)
 
735
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
736
                          r"^ +[0-9]+ms$")
 
737
 
 
738
    def _patch_get_bzr_source_tree(self):
 
739
        # Reading from the actual source tree breaks isolation, but we don't
 
740
        # want to assume that thats *all* that would happen.
 
741
        def _get_bzr_source_tree():
 
742
            return None
 
743
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
 
744
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
 
745
        def restore():
 
746
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
 
747
        self.addCleanup(restore)
 
748
 
 
749
    def test_assigned_benchmark_file_stores_date(self):
 
750
        self._patch_get_bzr_source_tree()
 
751
        output = StringIO()
 
752
        result = bzrlib.tests.TextTestResult(self._log_file,
 
753
                                        descriptions=0,
 
754
                                        verbosity=1,
 
755
                                        bench_history=output
 
756
                                        )
 
757
        output_string = output.getvalue()
 
758
        # if you are wondering about the regexp please read the comment in
 
759
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
760
        # XXX: what comment?  -- Andrew Bennetts
 
761
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
762
 
 
763
    def test_benchhistory_records_test_times(self):
 
764
        self._patch_get_bzr_source_tree()
 
765
        result_stream = StringIO()
 
766
        result = bzrlib.tests.TextTestResult(
 
767
            self._log_file,
 
768
            descriptions=0,
 
769
            verbosity=1,
 
770
            bench_history=result_stream
 
771
            )
 
772
 
 
773
        # we want profile a call and check that its test duration is recorded
 
774
        # make a new test instance that when run will generate a benchmark
 
775
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
776
        # execute the test, which should succeed and record times
 
777
        example_test_case.run(result)
 
778
        lines = result_stream.getvalue().splitlines()
 
779
        self.assertEqual(2, len(lines))
 
780
        self.assertContainsRe(lines[1],
 
781
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
782
            "._time_hello_world_encoding")
 
783
 
 
784
    def _time_hello_world_encoding(self):
 
785
        """Profile two sleep calls
 
786
 
 
787
        This is used to exercise the test framework.
 
788
        """
 
789
        self.time(unicode, 'hello', errors='replace')
 
790
        self.time(unicode, 'world', errors='replace')
 
791
 
 
792
    def test_lsprofiling(self):
 
793
        """Verbose test result prints lsprof statistics from test cases."""
 
794
        self.requireFeature(test_lsprof.LSProfFeature)
 
795
        result_stream = StringIO()
 
796
        result = bzrlib.tests.VerboseTestResult(
 
797
            unittest._WritelnDecorator(result_stream),
 
798
            descriptions=0,
 
799
            verbosity=2,
 
800
            )
 
801
        # we want profile a call of some sort and check it is output by
 
802
        # addSuccess. We dont care about addError or addFailure as they
 
803
        # are not that interesting for performance tuning.
 
804
        # make a new test instance that when run will generate a profile
 
805
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
806
        example_test_case._gather_lsprof_in_benchmarks = True
 
807
        # execute the test, which should succeed and record profiles
 
808
        example_test_case.run(result)
 
809
        # lsprofile_something()
 
810
        # if this worked we want
 
811
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
812
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
813
        # (the lsprof header)
 
814
        # ... an arbitrary number of lines
 
815
        # and the function call which is time.sleep.
 
816
        #           1        0            ???         ???       ???(sleep)
 
817
        # and then repeated but with 'world', rather than 'hello'.
 
818
        # this should appear in the output stream of our test result.
 
819
        output = result_stream.getvalue()
 
820
        self.assertContainsRe(output,
 
821
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
822
        self.assertContainsRe(output,
 
823
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
824
        self.assertContainsRe(output,
 
825
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
826
        self.assertContainsRe(output,
 
827
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
828
 
 
829
    def test_known_failure(self):
 
830
        """A KnownFailure being raised should trigger several result actions."""
 
831
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
832
            def stopTestRun(self): pass
 
833
            def startTests(self): pass
 
834
            def report_test_start(self, test): pass
 
835
            def report_known_failure(self, test, err):
 
836
                self._call = test, err
 
837
        result = InstrumentedTestResult(None, None, None, None)
 
838
        class Test(tests.TestCase):
 
839
            def test_function(self):
 
840
                raise tests.KnownFailure('failed!')
 
841
        test = Test("test_function")
 
842
        test.run(result)
 
843
        # it should invoke 'report_known_failure'.
 
844
        self.assertEqual(2, len(result._call))
 
845
        self.assertEqual(test, result._call[0])
 
846
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
847
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
848
        # we dont introspec the traceback, if the rest is ok, it would be
 
849
        # exceptional for it not to be.
 
850
        # it should update the known_failure_count on the object.
 
851
        self.assertEqual(1, result.known_failure_count)
 
852
        # the result should be successful.
 
853
        self.assertTrue(result.wasSuccessful())
 
854
 
 
855
    def test_verbose_report_known_failure(self):
 
856
        # verbose test output formatting
 
857
        result_stream = StringIO()
 
858
        result = bzrlib.tests.VerboseTestResult(
 
859
            unittest._WritelnDecorator(result_stream),
 
860
            descriptions=0,
 
861
            verbosity=2,
 
862
            )
 
863
        test = self.get_passing_test()
 
864
        result.startTest(test)
 
865
        prefix = len(result_stream.getvalue())
 
866
        # the err parameter has the shape:
 
867
        # (class, exception object, traceback)
 
868
        # KnownFailures dont get their tracebacks shown though, so we
 
869
        # can skip that.
 
870
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
871
        result.report_known_failure(test, err)
 
872
        output = result_stream.getvalue()[prefix:]
 
873
        lines = output.splitlines()
 
874
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
875
        self.assertEqual(lines[1], '    foo')
 
876
        self.assertEqual(2, len(lines))
 
877
 
 
878
    def get_passing_test(self):
 
879
        """Return a test object that can't be run usefully."""
 
880
        def passing_test():
 
881
            pass
 
882
        return unittest.FunctionTestCase(passing_test)
 
883
 
 
884
    def test_add_not_supported(self):
 
885
        """Test the behaviour of invoking addNotSupported."""
 
886
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
887
            def stopTestRun(self): pass
 
888
            def startTests(self): pass
 
889
            def report_test_start(self, test): pass
 
890
            def report_unsupported(self, test, feature):
 
891
                self._call = test, feature
 
892
        result = InstrumentedTestResult(None, None, None, None)
 
893
        test = SampleTestCase('_test_pass')
 
894
        feature = tests.Feature()
 
895
        result.startTest(test)
 
896
        result.addNotSupported(test, feature)
 
897
        # it should invoke 'report_unsupported'.
 
898
        self.assertEqual(2, len(result._call))
 
899
        self.assertEqual(test, result._call[0])
 
900
        self.assertEqual(feature, result._call[1])
 
901
        # the result should be successful.
 
902
        self.assertTrue(result.wasSuccessful())
 
903
        # it should record the test against a count of tests not run due to
 
904
        # this feature.
 
905
        self.assertEqual(1, result.unsupported['Feature'])
 
906
        # and invoking it again should increment that counter
 
907
        result.addNotSupported(test, feature)
 
908
        self.assertEqual(2, result.unsupported['Feature'])
 
909
 
 
910
    def test_verbose_report_unsupported(self):
 
911
        # verbose test output formatting
 
912
        result_stream = StringIO()
 
913
        result = bzrlib.tests.VerboseTestResult(
 
914
            unittest._WritelnDecorator(result_stream),
 
915
            descriptions=0,
 
916
            verbosity=2,
 
917
            )
 
918
        test = self.get_passing_test()
 
919
        feature = tests.Feature()
 
920
        result.startTest(test)
 
921
        prefix = len(result_stream.getvalue())
 
922
        result.report_unsupported(test, feature)
 
923
        output = result_stream.getvalue()[prefix:]
 
924
        lines = output.splitlines()
 
925
        self.assertEqual(lines, ['NODEP        0ms',
 
926
                                 "    The feature 'Feature' is not available."])
 
927
 
 
928
    def test_unavailable_exception(self):
 
929
        """An UnavailableFeature being raised should invoke addNotSupported."""
 
930
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
931
            def stopTestRun(self): pass
 
932
            def startTests(self): pass
 
933
            def report_test_start(self, test): pass
 
934
            def addNotSupported(self, test, feature):
 
935
                self._call = test, feature
 
936
        result = InstrumentedTestResult(None, None, None, None)
 
937
        feature = tests.Feature()
 
938
        class Test(tests.TestCase):
 
939
            def test_function(self):
 
940
                raise tests.UnavailableFeature(feature)
 
941
        test = Test("test_function")
 
942
        test.run(result)
 
943
        # it should invoke 'addNotSupported'.
 
944
        self.assertEqual(2, len(result._call))
 
945
        self.assertEqual(test, result._call[0])
 
946
        self.assertEqual(feature, result._call[1])
 
947
        # and not count as an error
 
948
        self.assertEqual(0, result.error_count)
 
949
 
 
950
    def test_strict_with_unsupported_feature(self):
 
951
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
952
                                             verbosity=1)
 
953
        test = self.get_passing_test()
 
954
        feature = "Unsupported Feature"
 
955
        result.addNotSupported(test, feature)
 
956
        self.assertFalse(result.wasStrictlySuccessful())
 
957
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
958
 
 
959
    def test_strict_with_known_failure(self):
 
960
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
961
                                             verbosity=1)
 
962
        test = self.get_passing_test()
 
963
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
964
        result.addExpectedFailure(test, err)
 
965
        self.assertFalse(result.wasStrictlySuccessful())
 
966
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
967
 
 
968
    def test_strict_with_success(self):
 
969
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
970
                                             verbosity=1)
 
971
        test = self.get_passing_test()
 
972
        result.addSuccess(test)
 
973
        self.assertTrue(result.wasStrictlySuccessful())
 
974
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
975
 
 
976
    def test_startTests(self):
 
977
        """Starting the first test should trigger startTests."""
 
978
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
979
            calls = 0
 
980
            def startTests(self): self.calls += 1
 
981
            def report_test_start(self, test): pass
 
982
        result = InstrumentedTestResult(None, None, None, None)
 
983
        def test_function():
 
984
            pass
 
985
        test = unittest.FunctionTestCase(test_function)
 
986
        test.run(result)
 
987
        self.assertEquals(1, result.calls)
 
988
 
 
989
 
 
990
class TestUnicodeFilenameFeature(tests.TestCase):
 
991
 
 
992
    def test_probe_passes(self):
 
993
        """UnicodeFilenameFeature._probe passes."""
 
994
        # We can't test much more than that because the behaviour depends
 
995
        # on the platform.
 
996
        tests.UnicodeFilenameFeature._probe()
 
997
 
 
998
 
 
999
class TestRunner(tests.TestCase):
 
1000
 
 
1001
    def dummy_test(self):
 
1002
        pass
 
1003
 
 
1004
    def run_test_runner(self, testrunner, test):
 
1005
        """Run suite in testrunner, saving global state and restoring it.
 
1006
 
 
1007
        This current saves and restores:
 
1008
        TestCaseInTempDir.TEST_ROOT
 
1009
 
 
1010
        There should be no tests in this file that use
 
1011
        bzrlib.tests.TextTestRunner without using this convenience method,
 
1012
        because of our use of global state.
 
1013
        """
 
1014
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1015
        old_leak = tests.TestCase._first_thread_leaker_id
 
1016
        try:
 
1017
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1018
            tests.TestCase._first_thread_leaker_id = None
 
1019
            return testrunner.run(test)
 
1020
        finally:
 
1021
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1022
            tests.TestCase._first_thread_leaker_id = old_leak
 
1023
 
 
1024
    def test_known_failure_failed_run(self):
 
1025
        # run a test that generates a known failure which should be printed in
 
1026
        # the final output when real failures occur.
 
1027
        class Test(tests.TestCase):
 
1028
            def known_failure_test(self):
 
1029
                raise tests.KnownFailure('failed')
 
1030
        test = unittest.TestSuite()
 
1031
        test.addTest(Test("known_failure_test"))
 
1032
        def failing_test():
 
1033
            raise AssertionError('foo')
 
1034
        test.addTest(unittest.FunctionTestCase(failing_test))
 
1035
        stream = StringIO()
 
1036
        runner = tests.TextTestRunner(stream=stream)
 
1037
        result = self.run_test_runner(runner, test)
 
1038
        lines = stream.getvalue().splitlines()
 
1039
        self.assertContainsRe(stream.getvalue(),
 
1040
            '(?sm)^testing.*$'
 
1041
            '.*'
 
1042
            '^======================================================================\n'
 
1043
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
 
1044
            '^----------------------------------------------------------------------\n'
 
1045
            'Traceback \\(most recent call last\\):\n'
 
1046
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
 
1047
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1048
            '.*'
 
1049
            '^----------------------------------------------------------------------\n'
 
1050
            '.*'
 
1051
            'FAILED \\(failures=1, known_failure_count=1\\)'
 
1052
            )
 
1053
 
 
1054
    def test_known_failure_ok_run(self):
 
1055
        # run a test that generates a known failure which should be printed in
 
1056
        # the final output.
 
1057
        class Test(tests.TestCase):
 
1058
            def known_failure_test(self):
 
1059
                raise tests.KnownFailure('failed')
 
1060
        test = Test("known_failure_test")
 
1061
        stream = StringIO()
 
1062
        runner = tests.TextTestRunner(stream=stream)
 
1063
        result = self.run_test_runner(runner, test)
 
1064
        self.assertContainsRe(stream.getvalue(),
 
1065
            '\n'
 
1066
            '-*\n'
 
1067
            'Ran 1 test in .*\n'
 
1068
            '\n'
 
1069
            'OK \\(known_failures=1\\)\n')
 
1070
 
 
1071
    def test_result_decorator(self):
 
1072
        # decorate results
 
1073
        calls = []
 
1074
        class LoggingDecorator(tests.ForwardingResult):
 
1075
            def startTest(self, test):
 
1076
                tests.ForwardingResult.startTest(self, test)
 
1077
                calls.append('start')
 
1078
        test = unittest.FunctionTestCase(lambda:None)
 
1079
        stream = StringIO()
 
1080
        runner = tests.TextTestRunner(stream=stream,
 
1081
            result_decorators=[LoggingDecorator])
 
1082
        result = self.run_test_runner(runner, test)
 
1083
        self.assertLength(1, calls)
 
1084
 
 
1085
    def test_skipped_test(self):
 
1086
        # run a test that is skipped, and check the suite as a whole still
 
1087
        # succeeds.
 
1088
        # skipping_test must be hidden in here so it's not run as a real test
 
1089
        class SkippingTest(tests.TestCase):
 
1090
            def skipping_test(self):
 
1091
                raise tests.TestSkipped('test intentionally skipped')
 
1092
        runner = tests.TextTestRunner(stream=self._log_file)
 
1093
        test = SkippingTest("skipping_test")
 
1094
        result = self.run_test_runner(runner, test)
 
1095
        self.assertTrue(result.wasSuccessful())
 
1096
 
 
1097
    def test_skipped_from_setup(self):
 
1098
        calls = []
 
1099
        class SkippedSetupTest(tests.TestCase):
 
1100
 
 
1101
            def setUp(self):
 
1102
                calls.append('setUp')
 
1103
                self.addCleanup(self.cleanup)
 
1104
                raise tests.TestSkipped('skipped setup')
 
1105
 
 
1106
            def test_skip(self):
 
1107
                self.fail('test reached')
 
1108
 
 
1109
            def cleanup(self):
 
1110
                calls.append('cleanup')
 
1111
 
 
1112
        runner = tests.TextTestRunner(stream=self._log_file)
 
1113
        test = SkippedSetupTest('test_skip')
 
1114
        result = self.run_test_runner(runner, test)
 
1115
        self.assertTrue(result.wasSuccessful())
 
1116
        # Check if cleanup was called the right number of times.
 
1117
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1118
 
 
1119
    def test_skipped_from_test(self):
 
1120
        calls = []
 
1121
        class SkippedTest(tests.TestCase):
 
1122
 
 
1123
            def setUp(self):
 
1124
                tests.TestCase.setUp(self)
 
1125
                calls.append('setUp')
 
1126
                self.addCleanup(self.cleanup)
 
1127
 
 
1128
            def test_skip(self):
 
1129
                raise tests.TestSkipped('skipped test')
 
1130
 
 
1131
            def cleanup(self):
 
1132
                calls.append('cleanup')
 
1133
 
 
1134
        runner = tests.TextTestRunner(stream=self._log_file)
 
1135
        test = SkippedTest('test_skip')
 
1136
        result = self.run_test_runner(runner, test)
 
1137
        self.assertTrue(result.wasSuccessful())
 
1138
        # Check if cleanup was called the right number of times.
 
1139
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1140
 
 
1141
    def test_not_applicable(self):
 
1142
        # run a test that is skipped because it's not applicable
 
1143
        class Test(tests.TestCase):
 
1144
            def not_applicable_test(self):
 
1145
                raise tests.TestNotApplicable('this test never runs')
 
1146
        out = StringIO()
 
1147
        runner = tests.TextTestRunner(stream=out, verbosity=2)
 
1148
        test = Test("not_applicable_test")
 
1149
        result = self.run_test_runner(runner, test)
 
1150
        self._log_file.write(out.getvalue())
 
1151
        self.assertTrue(result.wasSuccessful())
 
1152
        self.assertTrue(result.wasStrictlySuccessful())
 
1153
        self.assertContainsRe(out.getvalue(),
 
1154
                r'(?m)not_applicable_test   * N/A')
 
1155
        self.assertContainsRe(out.getvalue(),
 
1156
                r'(?m)^    this test never runs')
 
1157
 
 
1158
    def test_unsupported_features_listed(self):
 
1159
        """When unsupported features are encountered they are detailed."""
 
1160
        class Feature1(tests.Feature):
 
1161
            def _probe(self): return False
 
1162
        class Feature2(tests.Feature):
 
1163
            def _probe(self): return False
 
1164
        # create sample tests
 
1165
        test1 = SampleTestCase('_test_pass')
 
1166
        test1._test_needs_features = [Feature1()]
 
1167
        test2 = SampleTestCase('_test_pass')
 
1168
        test2._test_needs_features = [Feature2()]
 
1169
        test = unittest.TestSuite()
 
1170
        test.addTest(test1)
 
1171
        test.addTest(test2)
 
1172
        stream = StringIO()
 
1173
        runner = tests.TextTestRunner(stream=stream)
 
1174
        result = self.run_test_runner(runner, test)
 
1175
        lines = stream.getvalue().splitlines()
 
1176
        self.assertEqual([
 
1177
            'OK',
 
1178
            "Missing feature 'Feature1' skipped 1 tests.",
 
1179
            "Missing feature 'Feature2' skipped 1 tests.",
 
1180
            ],
 
1181
            lines[-3:])
 
1182
 
 
1183
    def _patch_get_bzr_source_tree(self):
 
1184
        # Reading from the actual source tree breaks isolation, but we don't
 
1185
        # want to assume that thats *all* that would happen.
 
1186
        self._get_source_tree_calls = []
 
1187
        def _get_bzr_source_tree():
 
1188
            self._get_source_tree_calls.append("called")
 
1189
            return None
 
1190
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
 
1191
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
 
1192
        def restore():
 
1193
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
 
1194
        self.addCleanup(restore)
 
1195
 
 
1196
    def test_bench_history(self):
 
1197
        # tests that the running the benchmark passes bench_history into
 
1198
        # the test result object. We can tell that happens if
 
1199
        # _get_bzr_source_tree is called.
 
1200
        self._patch_get_bzr_source_tree()
 
1201
        test = TestRunner('dummy_test')
 
1202
        output = StringIO()
 
1203
        runner = tests.TextTestRunner(stream=self._log_file,
 
1204
                                      bench_history=output)
 
1205
        result = self.run_test_runner(runner, test)
 
1206
        output_string = output.getvalue()
 
1207
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1208
        self.assertLength(1, self._get_source_tree_calls)
 
1209
 
 
1210
    def assertLogDeleted(self, test):
 
1211
        log = test._get_log()
 
1212
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1213
        self.assertEqual('', test._log_contents)
 
1214
        self.assertIs(None, test._log_file_name)
 
1215
 
 
1216
    def test_success_log_deleted(self):
 
1217
        """Successful tests have their log deleted"""
 
1218
 
 
1219
        class LogTester(tests.TestCase):
 
1220
 
 
1221
            def test_success(self):
 
1222
                self.log('this will be removed\n')
 
1223
 
 
1224
        sio = StringIO()
 
1225
        runner = tests.TextTestRunner(stream=sio)
 
1226
        test = LogTester('test_success')
 
1227
        result = self.run_test_runner(runner, test)
 
1228
 
 
1229
        self.assertLogDeleted(test)
 
1230
 
 
1231
    def test_skipped_log_deleted(self):
 
1232
        """Skipped tests have their log deleted"""
 
1233
 
 
1234
        class LogTester(tests.TestCase):
 
1235
 
 
1236
            def test_skipped(self):
 
1237
                self.log('this will be removed\n')
 
1238
                raise tests.TestSkipped()
 
1239
 
 
1240
        sio = StringIO()
 
1241
        runner = tests.TextTestRunner(stream=sio)
 
1242
        test = LogTester('test_skipped')
 
1243
        result = self.run_test_runner(runner, test)
 
1244
 
 
1245
        self.assertLogDeleted(test)
 
1246
 
 
1247
    def test_not_aplicable_log_deleted(self):
 
1248
        """Not applicable tests have their log deleted"""
 
1249
 
 
1250
        class LogTester(tests.TestCase):
 
1251
 
 
1252
            def test_not_applicable(self):
 
1253
                self.log('this will be removed\n')
 
1254
                raise tests.TestNotApplicable()
 
1255
 
 
1256
        sio = StringIO()
 
1257
        runner = tests.TextTestRunner(stream=sio)
 
1258
        test = LogTester('test_not_applicable')
 
1259
        result = self.run_test_runner(runner, test)
 
1260
 
 
1261
        self.assertLogDeleted(test)
 
1262
 
 
1263
    def test_known_failure_log_deleted(self):
 
1264
        """Know failure tests have their log deleted"""
 
1265
 
 
1266
        class LogTester(tests.TestCase):
 
1267
 
 
1268
            def test_known_failure(self):
 
1269
                self.log('this will be removed\n')
 
1270
                raise tests.KnownFailure()
 
1271
 
 
1272
        sio = StringIO()
 
1273
        runner = tests.TextTestRunner(stream=sio)
 
1274
        test = LogTester('test_known_failure')
 
1275
        result = self.run_test_runner(runner, test)
 
1276
 
 
1277
        self.assertLogDeleted(test)
 
1278
 
 
1279
    def test_fail_log_kept(self):
 
1280
        """Failed tests have their log kept"""
 
1281
 
 
1282
        class LogTester(tests.TestCase):
 
1283
 
 
1284
            def test_fail(self):
 
1285
                self.log('this will be kept\n')
 
1286
                self.fail('this test fails')
 
1287
 
 
1288
        sio = StringIO()
 
1289
        runner = tests.TextTestRunner(stream=sio)
 
1290
        test = LogTester('test_fail')
 
1291
        result = self.run_test_runner(runner, test)
 
1292
 
 
1293
        text = sio.getvalue()
 
1294
        self.assertContainsRe(text, 'this will be kept')
 
1295
        self.assertContainsRe(text, 'this test fails')
 
1296
 
 
1297
        log = test._get_log()
 
1298
        self.assertContainsRe(log, 'this will be kept')
 
1299
        self.assertEqual(log, test._log_contents)
 
1300
 
 
1301
    def test_error_log_kept(self):
 
1302
        """Tests with errors have their log kept"""
 
1303
 
 
1304
        class LogTester(tests.TestCase):
 
1305
 
 
1306
            def test_error(self):
 
1307
                self.log('this will be kept\n')
 
1308
                raise ValueError('random exception raised')
 
1309
 
 
1310
        sio = StringIO()
 
1311
        runner = tests.TextTestRunner(stream=sio)
 
1312
        test = LogTester('test_error')
 
1313
        result = self.run_test_runner(runner, test)
 
1314
 
 
1315
        text = sio.getvalue()
 
1316
        self.assertContainsRe(text, 'this will be kept')
 
1317
        self.assertContainsRe(text, 'random exception raised')
 
1318
 
 
1319
        log = test._get_log()
 
1320
        self.assertContainsRe(log, 'this will be kept')
 
1321
        self.assertEqual(log, test._log_contents)
 
1322
 
 
1323
    def test_startTestRun(self):
 
1324
        """run should call result.startTestRun()"""
 
1325
        calls = []
 
1326
        class LoggingDecorator(tests.ForwardingResult):
 
1327
            def startTestRun(self):
 
1328
                tests.ForwardingResult.startTestRun(self)
 
1329
                calls.append('startTestRun')
 
1330
        test = unittest.FunctionTestCase(lambda:None)
 
1331
        stream = StringIO()
 
1332
        runner = tests.TextTestRunner(stream=stream,
 
1333
            result_decorators=[LoggingDecorator])
 
1334
        result = self.run_test_runner(runner, test)
 
1335
        self.assertLength(1, calls)
 
1336
 
 
1337
    def test_stopTestRun(self):
 
1338
        """run should call result.stopTestRun()"""
 
1339
        calls = []
 
1340
        class LoggingDecorator(tests.ForwardingResult):
 
1341
            def stopTestRun(self):
 
1342
                tests.ForwardingResult.stopTestRun(self)
 
1343
                calls.append('stopTestRun')
 
1344
        test = unittest.FunctionTestCase(lambda:None)
 
1345
        stream = StringIO()
 
1346
        runner = tests.TextTestRunner(stream=stream,
 
1347
            result_decorators=[LoggingDecorator])
 
1348
        result = self.run_test_runner(runner, test)
 
1349
        self.assertLength(1, calls)
 
1350
 
 
1351
 
 
1352
class SampleTestCase(tests.TestCase):
 
1353
 
 
1354
    def _test_pass(self):
 
1355
        pass
 
1356
 
 
1357
class _TestException(Exception):
 
1358
    pass
 
1359
 
 
1360
 
 
1361
class TestTestCase(tests.TestCase):
 
1362
    """Tests that test the core bzrlib TestCase."""
 
1363
 
 
1364
    def test_assertLength_matches_empty(self):
 
1365
        a_list = []
 
1366
        self.assertLength(0, a_list)
 
1367
 
 
1368
    def test_assertLength_matches_nonempty(self):
 
1369
        a_list = [1, 2, 3]
 
1370
        self.assertLength(3, a_list)
 
1371
 
 
1372
    def test_assertLength_fails_different(self):
 
1373
        a_list = []
 
1374
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
 
1375
 
 
1376
    def test_assertLength_shows_sequence_in_failure(self):
 
1377
        a_list = [1, 2, 3]
 
1378
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
 
1379
            a_list)
 
1380
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
 
1381
            exception.args[0])
 
1382
 
 
1383
    def test_base_setUp_not_called_causes_failure(self):
 
1384
        class TestCaseWithBrokenSetUp(tests.TestCase):
 
1385
            def setUp(self):
 
1386
                pass # does not call TestCase.setUp
 
1387
            def test_foo(self):
 
1388
                pass
 
1389
        test = TestCaseWithBrokenSetUp('test_foo')
 
1390
        result = unittest.TestResult()
 
1391
        test.run(result)
 
1392
        self.assertFalse(result.wasSuccessful())
 
1393
        self.assertEqual(1, result.testsRun)
 
1394
 
 
1395
    def test_base_tearDown_not_called_causes_failure(self):
 
1396
        class TestCaseWithBrokenTearDown(tests.TestCase):
 
1397
            def tearDown(self):
 
1398
                pass # does not call TestCase.tearDown
 
1399
            def test_foo(self):
 
1400
                pass
 
1401
        test = TestCaseWithBrokenTearDown('test_foo')
 
1402
        result = unittest.TestResult()
 
1403
        test.run(result)
 
1404
        self.assertFalse(result.wasSuccessful())
 
1405
        self.assertEqual(1, result.testsRun)
 
1406
 
 
1407
    def test_debug_flags_sanitised(self):
 
1408
        """The bzrlib debug flags should be sanitised by setUp."""
 
1409
        if 'allow_debug' in tests.selftest_debug_flags:
 
1410
            raise tests.TestNotApplicable(
 
1411
                '-Eallow_debug option prevents debug flag sanitisation')
 
1412
        # we could set something and run a test that will check
 
1413
        # it gets santised, but this is probably sufficient for now:
 
1414
        # if someone runs the test with -Dsomething it will error.
 
1415
        flags = set()
 
1416
        if self._lock_check_thorough:
 
1417
            flags.add('strict_locks')
 
1418
        self.assertEqual(flags, bzrlib.debug.debug_flags)
 
1419
 
 
1420
    def change_selftest_debug_flags(self, new_flags):
 
1421
        orig_selftest_flags = tests.selftest_debug_flags
 
1422
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1423
        tests.selftest_debug_flags = set(new_flags)
 
1424
 
 
1425
    def _restore_selftest_debug_flags(self, flags):
 
1426
        tests.selftest_debug_flags = flags
 
1427
 
 
1428
    def test_allow_debug_flag(self):
 
1429
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1430
        sanitised (i.e. cleared) before running a test.
 
1431
        """
 
1432
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1433
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1434
        class TestThatRecordsFlags(tests.TestCase):
 
1435
            def test_foo(nested_self):
 
1436
                self.flags = set(bzrlib.debug.debug_flags)
 
1437
        test = TestThatRecordsFlags('test_foo')
 
1438
        test.run(self.make_test_result())
 
1439
        flags = set(['a-flag'])
 
1440
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
 
1441
            flags.add('strict_locks')
 
1442
        self.assertEqual(flags, self.flags)
 
1443
 
 
1444
    def test_disable_lock_checks(self):
 
1445
        """The -Edisable_lock_checks flag disables thorough checks."""
 
1446
        class TestThatRecordsFlags(tests.TestCase):
 
1447
            def test_foo(nested_self):
 
1448
                self.flags = set(bzrlib.debug.debug_flags)
 
1449
                self.test_lock_check_thorough = nested_self._lock_check_thorough
 
1450
        self.change_selftest_debug_flags(set())
 
1451
        test = TestThatRecordsFlags('test_foo')
 
1452
        test.run(self.make_test_result())
 
1453
        # By default we do strict lock checking and thorough lock/unlock
 
1454
        # tracking.
 
1455
        self.assertTrue(self.test_lock_check_thorough)
 
1456
        self.assertEqual(set(['strict_locks']), self.flags)
 
1457
        # Now set the disable_lock_checks flag, and show that this changed.
 
1458
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
 
1459
        test = TestThatRecordsFlags('test_foo')
 
1460
        test.run(self.make_test_result())
 
1461
        self.assertFalse(self.test_lock_check_thorough)
 
1462
        self.assertEqual(set(), self.flags)
 
1463
 
 
1464
    def test_this_fails_strict_lock_check(self):
 
1465
        class TestThatRecordsFlags(tests.TestCase):
 
1466
            def test_foo(nested_self):
 
1467
                self.flags1 = set(bzrlib.debug.debug_flags)
 
1468
                self.thisFailsStrictLockCheck()
 
1469
                self.flags2 = set(bzrlib.debug.debug_flags)
 
1470
        # Make sure lock checking is active
 
1471
        self.change_selftest_debug_flags(set())
 
1472
        test = TestThatRecordsFlags('test_foo')
 
1473
        test.run(self.make_test_result())
 
1474
        self.assertEqual(set(['strict_locks']), self.flags1)
 
1475
        self.assertEqual(set(), self.flags2)
 
1476
 
 
1477
    def test_debug_flags_restored(self):
 
1478
        """The bzrlib debug flags should be restored to their original state
 
1479
        after the test was run, even if allow_debug is set.
 
1480
        """
 
1481
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1482
        # Now run a test that modifies debug.debug_flags.
 
1483
        bzrlib.debug.debug_flags = set(['original-state'])
 
1484
        class TestThatModifiesFlags(tests.TestCase):
 
1485
            def test_foo(self):
 
1486
                bzrlib.debug.debug_flags = set(['modified'])
 
1487
        test = TestThatModifiesFlags('test_foo')
 
1488
        test.run(self.make_test_result())
 
1489
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1490
 
 
1491
    def make_test_result(self):
 
1492
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
 
1493
 
 
1494
    def inner_test(self):
 
1495
        # the inner child test
 
1496
        note("inner_test")
 
1497
 
 
1498
    def outer_child(self):
 
1499
        # the outer child test
 
1500
        note("outer_start")
 
1501
        self.inner_test = TestTestCase("inner_child")
 
1502
        result = self.make_test_result()
 
1503
        self.inner_test.run(result)
 
1504
        note("outer finish")
 
1505
 
 
1506
    def test_trace_nesting(self):
 
1507
        # this tests that each test case nests its trace facility correctly.
 
1508
        # we do this by running a test case manually. That test case (A)
 
1509
        # should setup a new log, log content to it, setup a child case (B),
 
1510
        # which should log independently, then case (A) should log a trailer
 
1511
        # and return.
 
1512
        # we do two nested children so that we can verify the state of the
 
1513
        # logs after the outer child finishes is correct, which a bad clean
 
1514
        # up routine in tearDown might trigger a fault in our test with only
 
1515
        # one child, we should instead see the bad result inside our test with
 
1516
        # the two children.
 
1517
        # the outer child test
 
1518
        original_trace = bzrlib.trace._trace_file
 
1519
        outer_test = TestTestCase("outer_child")
 
1520
        result = self.make_test_result()
 
1521
        outer_test.run(result)
 
1522
        self.addCleanup(osutils.delete_any, outer_test._log_file_name)
 
1523
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1524
 
 
1525
    def method_that_times_a_bit_twice(self):
 
1526
        # call self.time twice to ensure it aggregates
 
1527
        self.time(time.sleep, 0.007)
 
1528
        self.time(time.sleep, 0.007)
 
1529
 
 
1530
    def test_time_creates_benchmark_in_result(self):
 
1531
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1532
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1533
        output_stream = StringIO()
 
1534
        result = bzrlib.tests.VerboseTestResult(
 
1535
            unittest._WritelnDecorator(output_stream),
 
1536
            descriptions=0,
 
1537
            verbosity=2)
 
1538
        sample_test.run(result)
 
1539
        self.assertContainsRe(
 
1540
            output_stream.getvalue(),
 
1541
            r"\d+ms\*\n$")
 
1542
 
 
1543
    def test_hooks_sanitised(self):
 
1544
        """The bzrlib hooks should be sanitised by setUp."""
 
1545
        # Note this test won't fail with hooks that the core library doesn't
 
1546
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1547
        # useful warning in that case.
 
1548
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1549
            bzrlib.branch.Branch.hooks)
 
1550
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1551
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1552
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1553
            bzrlib.commands.Command.hooks)
 
1554
 
 
1555
    def test__gather_lsprof_in_benchmarks(self):
 
1556
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1557
 
 
1558
        Each self.time() call is individually and separately profiled.
 
1559
        """
 
1560
        self.requireFeature(test_lsprof.LSProfFeature)
 
1561
        # overrides the class member with an instance member so no cleanup
 
1562
        # needed.
 
1563
        self._gather_lsprof_in_benchmarks = True
 
1564
        self.time(time.sleep, 0.000)
 
1565
        self.time(time.sleep, 0.003)
 
1566
        self.assertEqual(2, len(self._benchcalls))
 
1567
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1568
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1569
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
1570
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1571
        del self._benchcalls[:]
 
1572
 
 
1573
    def test_knownFailure(self):
 
1574
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1575
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1576
 
 
1577
    def test_open_bzrdir_safe_roots(self):
 
1578
        # even a memory transport should fail to open when its url isn't 
 
1579
        # permitted.
 
1580
        # Manually set one up (TestCase doesn't and shouldn't provide magic
 
1581
        # machinery)
 
1582
        transport_server = MemoryServer()
 
1583
        transport_server.setUp()
 
1584
        self.addCleanup(transport_server.tearDown)
 
1585
        t = transport.get_transport(transport_server.get_url())
 
1586
        bzrdir.BzrDir.create(t.base)
 
1587
        self.assertRaises(errors.BzrError,
 
1588
            bzrdir.BzrDir.open_from_transport, t)
 
1589
        # But if we declare this as safe, we can open the bzrdir.
 
1590
        self.permit_url(t.base)
 
1591
        self._bzr_selftest_roots.append(t.base)
 
1592
        bzrdir.BzrDir.open_from_transport(t)
 
1593
 
 
1594
    def test_requireFeature_available(self):
 
1595
        """self.requireFeature(available) is a no-op."""
 
1596
        class Available(tests.Feature):
 
1597
            def _probe(self):return True
 
1598
        feature = Available()
 
1599
        self.requireFeature(feature)
 
1600
 
 
1601
    def test_requireFeature_unavailable(self):
 
1602
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1603
        class Unavailable(tests.Feature):
 
1604
            def _probe(self):return False
 
1605
        feature = Unavailable()
 
1606
        self.assertRaises(tests.UnavailableFeature,
 
1607
                          self.requireFeature, feature)
 
1608
 
 
1609
    def test_run_no_parameters(self):
 
1610
        test = SampleTestCase('_test_pass')
 
1611
        test.run()
 
1612
 
 
1613
    def test_run_enabled_unittest_result(self):
 
1614
        """Test we revert to regular behaviour when the test is enabled."""
 
1615
        test = SampleTestCase('_test_pass')
 
1616
        class EnabledFeature(object):
 
1617
            def available(self):
 
1618
                return True
 
1619
        test._test_needs_features = [EnabledFeature()]
 
1620
        result = unittest.TestResult()
 
1621
        test.run(result)
 
1622
        self.assertEqual(1, result.testsRun)
 
1623
        self.assertEqual([], result.errors)
 
1624
        self.assertEqual([], result.failures)
 
1625
 
 
1626
    def test_run_disabled_unittest_result(self):
 
1627
        """Test our compatability for disabled tests with unittest results."""
 
1628
        test = SampleTestCase('_test_pass')
 
1629
        class DisabledFeature(object):
 
1630
            def available(self):
 
1631
                return False
 
1632
        test._test_needs_features = [DisabledFeature()]
 
1633
        result = unittest.TestResult()
 
1634
        test.run(result)
 
1635
        self.assertEqual(1, result.testsRun)
 
1636
        self.assertEqual([], result.errors)
 
1637
        self.assertEqual([], result.failures)
 
1638
 
 
1639
    def test_run_disabled_supporting_result(self):
 
1640
        """Test disabled tests behaviour with support aware results."""
 
1641
        test = SampleTestCase('_test_pass')
 
1642
        class DisabledFeature(object):
 
1643
            def available(self):
 
1644
                return False
 
1645
        the_feature = DisabledFeature()
 
1646
        test._test_needs_features = [the_feature]
 
1647
        class InstrumentedTestResult(unittest.TestResult):
 
1648
            def __init__(self):
 
1649
                unittest.TestResult.__init__(self)
 
1650
                self.calls = []
 
1651
            def startTest(self, test):
 
1652
                self.calls.append(('startTest', test))
 
1653
            def stopTest(self, test):
 
1654
                self.calls.append(('stopTest', test))
 
1655
            def addNotSupported(self, test, feature):
 
1656
                self.calls.append(('addNotSupported', test, feature))
 
1657
        result = InstrumentedTestResult()
 
1658
        test.run(result)
 
1659
        self.assertEqual([
 
1660
            ('startTest', test),
 
1661
            ('addNotSupported', test, the_feature),
 
1662
            ('stopTest', test),
 
1663
            ],
 
1664
            result.calls)
 
1665
 
 
1666
    def test_start_server_registers_url(self):
 
1667
        transport_server = MemoryServer()
 
1668
        # A little strict, but unlikely to be changed soon.
 
1669
        self.assertEqual([], self._bzr_selftest_roots)
 
1670
        self.start_server(transport_server)
 
1671
        self.assertSubset([transport_server.get_url()],
 
1672
            self._bzr_selftest_roots)
 
1673
 
 
1674
    def test_assert_list_raises_on_generator(self):
 
1675
        def generator_which_will_raise():
 
1676
            # This will not raise until after the first yield
 
1677
            yield 1
 
1678
            raise _TestException()
 
1679
 
 
1680
        e = self.assertListRaises(_TestException, generator_which_will_raise)
 
1681
        self.assertIsInstance(e, _TestException)
 
1682
 
 
1683
        e = self.assertListRaises(Exception, generator_which_will_raise)
 
1684
        self.assertIsInstance(e, _TestException)
 
1685
 
 
1686
    def test_assert_list_raises_on_plain(self):
 
1687
        def plain_exception():
 
1688
            raise _TestException()
 
1689
            return []
 
1690
 
 
1691
        e = self.assertListRaises(_TestException, plain_exception)
 
1692
        self.assertIsInstance(e, _TestException)
 
1693
 
 
1694
        e = self.assertListRaises(Exception, plain_exception)
 
1695
        self.assertIsInstance(e, _TestException)
 
1696
 
 
1697
    def test_assert_list_raises_assert_wrong_exception(self):
 
1698
        class _NotTestException(Exception):
 
1699
            pass
 
1700
 
 
1701
        def wrong_exception():
 
1702
            raise _NotTestException()
 
1703
 
 
1704
        def wrong_exception_generator():
 
1705
            yield 1
 
1706
            yield 2
 
1707
            raise _NotTestException()
 
1708
 
 
1709
        # Wrong exceptions are not intercepted
 
1710
        self.assertRaises(_NotTestException,
 
1711
            self.assertListRaises, _TestException, wrong_exception)
 
1712
        self.assertRaises(_NotTestException,
 
1713
            self.assertListRaises, _TestException, wrong_exception_generator)
 
1714
 
 
1715
    def test_assert_list_raises_no_exception(self):
 
1716
        def success():
 
1717
            return []
 
1718
 
 
1719
        def success_generator():
 
1720
            yield 1
 
1721
            yield 2
 
1722
 
 
1723
        self.assertRaises(AssertionError,
 
1724
            self.assertListRaises, _TestException, success)
 
1725
 
 
1726
        self.assertRaises(AssertionError,
 
1727
            self.assertListRaises, _TestException, success_generator)
 
1728
 
 
1729
 
 
1730
# NB: Don't delete this; it's not actually from 0.11!
 
1731
@deprecated_function(deprecated_in((0, 11, 0)))
 
1732
def sample_deprecated_function():
 
1733
    """A deprecated function to test applyDeprecated with."""
 
1734
    return 2
 
1735
 
 
1736
 
 
1737
def sample_undeprecated_function(a_param):
 
1738
    """A undeprecated function to test applyDeprecated with."""
 
1739
 
 
1740
 
 
1741
class ApplyDeprecatedHelper(object):
 
1742
    """A helper class for ApplyDeprecated tests."""
 
1743
 
 
1744
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1745
    def sample_deprecated_method(self, param_one):
 
1746
        """A deprecated method for testing with."""
 
1747
        return param_one
 
1748
 
 
1749
    def sample_normal_method(self):
 
1750
        """A undeprecated method."""
 
1751
 
 
1752
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1753
    def sample_nested_deprecation(self):
 
1754
        return sample_deprecated_function()
 
1755
 
 
1756
 
 
1757
class TestExtraAssertions(tests.TestCase):
 
1758
    """Tests for new test assertions in bzrlib test suite"""
 
1759
 
 
1760
    def test_assert_isinstance(self):
 
1761
        self.assertIsInstance(2, int)
 
1762
        self.assertIsInstance(u'', basestring)
 
1763
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1764
        self.assertEquals(str(e),
 
1765
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
 
1766
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1767
        e = self.assertRaises(AssertionError,
 
1768
            self.assertIsInstance, None, int, "it's just not")
 
1769
        self.assertEquals(str(e),
 
1770
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
 
1771
            ": it's just not")
 
1772
 
 
1773
    def test_assertEndsWith(self):
 
1774
        self.assertEndsWith('foo', 'oo')
 
1775
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1776
 
 
1777
    def test_assertEqualDiff(self):
 
1778
        e = self.assertRaises(AssertionError,
 
1779
                              self.assertEqualDiff, '', '\n')
 
1780
        self.assertEquals(str(e),
 
1781
                          # Don't blink ! The '+' applies to the second string
 
1782
                          'first string is missing a final newline.\n+ \n')
 
1783
        e = self.assertRaises(AssertionError,
 
1784
                              self.assertEqualDiff, '\n', '')
 
1785
        self.assertEquals(str(e),
 
1786
                          # Don't blink ! The '-' applies to the second string
 
1787
                          'second string is missing a final newline.\n- \n')
 
1788
 
 
1789
 
 
1790
class TestDeprecations(tests.TestCase):
 
1791
 
 
1792
    def test_applyDeprecated_not_deprecated(self):
 
1793
        sample_object = ApplyDeprecatedHelper()
 
1794
        # calling an undeprecated callable raises an assertion
 
1795
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1796
            deprecated_in((0, 11, 0)),
 
1797
            sample_object.sample_normal_method)
 
1798
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1799
            deprecated_in((0, 11, 0)),
 
1800
            sample_undeprecated_function, "a param value")
 
1801
        # calling a deprecated callable (function or method) with the wrong
 
1802
        # expected deprecation fails.
 
1803
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1804
            deprecated_in((0, 10, 0)),
 
1805
            sample_object.sample_deprecated_method, "a param value")
 
1806
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1807
            deprecated_in((0, 10, 0)),
 
1808
            sample_deprecated_function)
 
1809
        # calling a deprecated callable (function or method) with the right
 
1810
        # expected deprecation returns the functions result.
 
1811
        self.assertEqual("a param value",
 
1812
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1813
            sample_object.sample_deprecated_method, "a param value"))
 
1814
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1815
            sample_deprecated_function))
 
1816
        # calling a nested deprecation with the wrong deprecation version
 
1817
        # fails even if a deeper nested function was deprecated with the
 
1818
        # supplied version.
 
1819
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1820
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1821
        # calling a nested deprecation with the right deprecation value
 
1822
        # returns the calls result.
 
1823
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1824
            sample_object.sample_nested_deprecation))
 
1825
 
 
1826
    def test_callDeprecated(self):
 
1827
        def testfunc(be_deprecated, result=None):
 
1828
            if be_deprecated is True:
 
1829
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1830
                                       stacklevel=1)
 
1831
            return result
 
1832
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1833
        self.assertIs(None, result)
 
1834
        result = self.callDeprecated([], testfunc, False, 'result')
 
1835
        self.assertEqual('result', result)
 
1836
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1837
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1838
 
 
1839
 
 
1840
class TestWarningTests(tests.TestCase):
 
1841
    """Tests for calling methods that raise warnings."""
 
1842
 
 
1843
    def test_callCatchWarnings(self):
 
1844
        def meth(a, b):
 
1845
            warnings.warn("this is your last warning")
 
1846
            return a + b
 
1847
        wlist, result = self.callCatchWarnings(meth, 1, 2)
 
1848
        self.assertEquals(3, result)
 
1849
        # would like just to compare them, but UserWarning doesn't implement
 
1850
        # eq well
 
1851
        w0, = wlist
 
1852
        self.assertIsInstance(w0, UserWarning)
 
1853
        self.assertEquals("this is your last warning", str(w0))
 
1854
 
 
1855
 
 
1856
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1857
    """Test for the make_* convenience functions."""
 
1858
 
 
1859
    def test_make_branch_and_tree_with_format(self):
 
1860
        # we should be able to supply a format to make_branch_and_tree
 
1861
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1862
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
1863
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
1864
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1865
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1866
                              bzrlib.bzrdir.BzrDirFormat6)
 
1867
 
 
1868
    def test_make_branch_and_memory_tree(self):
 
1869
        # we should be able to get a new branch and a mutable tree from
 
1870
        # TestCaseWithTransport
 
1871
        tree = self.make_branch_and_memory_tree('a')
 
1872
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1873
 
 
1874
    def test_make_tree_for_local_vfs_backed_transport(self):
 
1875
        # make_branch_and_tree has to use local branch and repositories
 
1876
        # when the vfs transport and local disk are colocated, even if
 
1877
        # a different transport is in use for url generation.
 
1878
        from bzrlib.transport.fakevfat import FakeVFATServer
 
1879
        self.transport_server = FakeVFATServer
 
1880
        self.assertFalse(self.get_url('t1').startswith('file://'))
 
1881
        tree = self.make_branch_and_tree('t1')
 
1882
        base = tree.bzrdir.root_transport.base
 
1883
        self.assertStartsWith(base, 'file://')
 
1884
        self.assertEquals(tree.bzrdir.root_transport,
 
1885
                tree.branch.bzrdir.root_transport)
 
1886
        self.assertEquals(tree.bzrdir.root_transport,
 
1887
                tree.branch.repository.bzrdir.root_transport)
 
1888
 
 
1889
 
 
1890
class SelfTestHelper:
 
1891
 
 
1892
    def run_selftest(self, **kwargs):
 
1893
        """Run selftest returning its output."""
 
1894
        output = StringIO()
 
1895
        old_transport = bzrlib.tests.default_transport
 
1896
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
 
1897
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
 
1898
        try:
 
1899
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
 
1900
        finally:
 
1901
            bzrlib.tests.default_transport = old_transport
 
1902
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
1903
        output.seek(0)
 
1904
        return output
 
1905
 
 
1906
 
 
1907
class TestSelftest(tests.TestCase, SelfTestHelper):
 
1908
    """Tests of bzrlib.tests.selftest."""
 
1909
 
 
1910
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
1911
        factory_called = []
 
1912
        def factory():
 
1913
            factory_called.append(True)
 
1914
            return TestUtil.TestSuite()
 
1915
        out = StringIO()
 
1916
        err = StringIO()
 
1917
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1918
            test_suite_factory=factory)
 
1919
        self.assertEqual([True], factory_called)
 
1920
 
 
1921
    def factory(self):
 
1922
        """A test suite factory."""
 
1923
        class Test(tests.TestCase):
 
1924
            def a(self):
 
1925
                pass
 
1926
            def b(self):
 
1927
                pass
 
1928
            def c(self):
 
1929
                pass
 
1930
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
1931
 
 
1932
    def test_list_only(self):
 
1933
        output = self.run_selftest(test_suite_factory=self.factory,
 
1934
            list_only=True)
 
1935
        self.assertEqual(3, len(output.readlines()))
 
1936
 
 
1937
    def test_list_only_filtered(self):
 
1938
        output = self.run_selftest(test_suite_factory=self.factory,
 
1939
            list_only=True, pattern="Test.b")
 
1940
        self.assertEndsWith(output.getvalue(), "Test.b\n")
 
1941
        self.assertLength(1, output.readlines())
 
1942
 
 
1943
    def test_list_only_excludes(self):
 
1944
        output = self.run_selftest(test_suite_factory=self.factory,
 
1945
            list_only=True, exclude_pattern="Test.b")
 
1946
        self.assertNotContainsRe("Test.b", output.getvalue())
 
1947
        self.assertLength(2, output.readlines())
 
1948
 
 
1949
    def test_lsprof_tests(self):
 
1950
        self.requireFeature(test_lsprof.LSProfFeature)
 
1951
        calls = []
 
1952
        class Test(object):
 
1953
            def __call__(test, result):
 
1954
                test.run(result)
 
1955
            def run(test, result):
 
1956
                self.assertIsInstance(result, tests.ForwardingResult)
 
1957
                calls.append("called")
 
1958
            def countTestCases(self):
 
1959
                return 1
 
1960
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
 
1961
        self.assertLength(1, calls)
 
1962
 
 
1963
    def test_random(self):
 
1964
        # test randomising by listing a number of tests.
 
1965
        output_123 = self.run_selftest(test_suite_factory=self.factory,
 
1966
            list_only=True, random_seed="123")
 
1967
        output_234 = self.run_selftest(test_suite_factory=self.factory,
 
1968
            list_only=True, random_seed="234")
 
1969
        self.assertNotEqual(output_123, output_234)
 
1970
        # "Randominzing test order..\n\n
 
1971
        self.assertLength(5, output_123.readlines())
 
1972
        self.assertLength(5, output_234.readlines())
 
1973
 
 
1974
    def test_random_reuse_is_same_order(self):
 
1975
        # test randomising by listing a number of tests.
 
1976
        expected = self.run_selftest(test_suite_factory=self.factory,
 
1977
            list_only=True, random_seed="123")
 
1978
        repeated = self.run_selftest(test_suite_factory=self.factory,
 
1979
            list_only=True, random_seed="123")
 
1980
        self.assertEqual(expected.getvalue(), repeated.getvalue())
 
1981
 
 
1982
    def test_runner_class(self):
 
1983
        self.requireFeature(SubUnitFeature)
 
1984
        from subunit import ProtocolTestCase
 
1985
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
1986
            test_suite_factory=self.factory)
 
1987
        test = ProtocolTestCase(stream)
 
1988
        result = unittest.TestResult()
 
1989
        test.run(result)
 
1990
        self.assertEqual(3, result.testsRun)
 
1991
 
 
1992
    def test_starting_with_single_argument(self):
 
1993
        output = self.run_selftest(test_suite_factory=self.factory,
 
1994
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
 
1995
            list_only=True)
 
1996
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
 
1997
            output.getvalue())
 
1998
 
 
1999
    def test_starting_with_multiple_argument(self):
 
2000
        output = self.run_selftest(test_suite_factory=self.factory,
 
2001
            starting_with=['bzrlib.tests.test_selftest.Test.a',
 
2002
                'bzrlib.tests.test_selftest.Test.b'],
 
2003
            list_only=True)
 
2004
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
 
2005
            'bzrlib.tests.test_selftest.Test.b\n',
 
2006
            output.getvalue())
 
2007
 
 
2008
    def check_transport_set(self, transport_server):
 
2009
        captured_transport = []
 
2010
        def seen_transport(a_transport):
 
2011
            captured_transport.append(a_transport)
 
2012
        class Capture(tests.TestCase):
 
2013
            def a(self):
 
2014
                seen_transport(bzrlib.tests.default_transport)
 
2015
        def factory():
 
2016
            return TestUtil.TestSuite([Capture("a")])
 
2017
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
 
2018
        self.assertEqual(transport_server, captured_transport[0])
 
2019
 
 
2020
    def test_transport_sftp(self):
 
2021
        try:
 
2022
            import bzrlib.transport.sftp
 
2023
        except errors.ParamikoNotPresent:
 
2024
            raise tests.TestSkipped("Paramiko not present")
 
2025
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
 
2026
 
 
2027
    def test_transport_memory(self):
 
2028
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
 
2029
 
 
2030
 
 
2031
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
 
2032
    # Does IO: reads test.list
 
2033
 
 
2034
    def test_load_list(self):
 
2035
        # Provide a list with one test - this test.
 
2036
        test_id_line = '%s\n' % self.id()
 
2037
        self.build_tree_contents([('test.list', test_id_line)])
 
2038
        # And generate a list of the tests in  the suite.
 
2039
        stream = self.run_selftest(load_list='test.list', list_only=True)
 
2040
        self.assertEqual(test_id_line, stream.getvalue())
 
2041
 
 
2042
    def test_load_unknown(self):
 
2043
        # Provide a list with one test - this test.
 
2044
        # And generate a list of the tests in  the suite.
 
2045
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
 
2046
            load_list='missing file name', list_only=True)
 
2047
 
 
2048
 
 
2049
class TestRunBzr(tests.TestCase):
 
2050
 
 
2051
    out = ''
 
2052
    err = ''
 
2053
 
 
2054
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
 
2055
                         working_dir=None):
 
2056
        """Override _run_bzr_core to test how it is invoked by run_bzr.
 
2057
 
 
2058
        Attempts to run bzr from inside this class don't actually run it.
 
2059
 
 
2060
        We test how run_bzr actually invokes bzr in another location.  Here we
 
2061
        only need to test that it passes the right parameters to run_bzr.
 
2062
        """
 
2063
        self.argv = list(argv)
 
2064
        self.retcode = retcode
 
2065
        self.encoding = encoding
 
2066
        self.stdin = stdin
 
2067
        self.working_dir = working_dir
 
2068
        return self.retcode, self.out, self.err
 
2069
 
 
2070
    def test_run_bzr_error(self):
 
2071
        self.out = "It sure does!\n"
 
2072
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
 
2073
        self.assertEqual(['rocks'], self.argv)
 
2074
        self.assertEqual(34, self.retcode)
 
2075
        self.assertEqual('It sure does!\n', out)
 
2076
        self.assertEquals(out, self.out)
 
2077
        self.assertEqual('', err)
 
2078
        self.assertEquals(err, self.err)
 
2079
 
 
2080
    def test_run_bzr_error_regexes(self):
 
2081
        self.out = ''
 
2082
        self.err = "bzr: ERROR: foobarbaz is not versioned"
 
2083
        out, err = self.run_bzr_error(
 
2084
            ["bzr: ERROR: foobarbaz is not versioned"],
 
2085
            ['file-id', 'foobarbaz'])
 
2086
 
 
2087
    def test_encoding(self):
 
2088
        """Test that run_bzr passes encoding to _run_bzr_core"""
 
2089
        self.run_bzr('foo bar')
 
2090
        self.assertEqual(None, self.encoding)
 
2091
        self.assertEqual(['foo', 'bar'], self.argv)
 
2092
 
 
2093
        self.run_bzr('foo bar', encoding='baz')
 
2094
        self.assertEqual('baz', self.encoding)
 
2095
        self.assertEqual(['foo', 'bar'], self.argv)
 
2096
 
 
2097
    def test_retcode(self):
 
2098
        """Test that run_bzr passes retcode to _run_bzr_core"""
 
2099
        # Default is retcode == 0
 
2100
        self.run_bzr('foo bar')
 
2101
        self.assertEqual(0, self.retcode)
 
2102
        self.assertEqual(['foo', 'bar'], self.argv)
 
2103
 
 
2104
        self.run_bzr('foo bar', retcode=1)
 
2105
        self.assertEqual(1, self.retcode)
 
2106
        self.assertEqual(['foo', 'bar'], self.argv)
 
2107
 
 
2108
        self.run_bzr('foo bar', retcode=None)
 
2109
        self.assertEqual(None, self.retcode)
 
2110
        self.assertEqual(['foo', 'bar'], self.argv)
 
2111
 
 
2112
        self.run_bzr(['foo', 'bar'], retcode=3)
 
2113
        self.assertEqual(3, self.retcode)
 
2114
        self.assertEqual(['foo', 'bar'], self.argv)
 
2115
 
 
2116
    def test_stdin(self):
 
2117
        # test that the stdin keyword to run_bzr is passed through to
 
2118
        # _run_bzr_core as-is. We do this by overriding
 
2119
        # _run_bzr_core in this class, and then calling run_bzr,
 
2120
        # which is a convenience function for _run_bzr_core, so
 
2121
        # should invoke it.
 
2122
        self.run_bzr('foo bar', stdin='gam')
 
2123
        self.assertEqual('gam', self.stdin)
 
2124
        self.assertEqual(['foo', 'bar'], self.argv)
 
2125
 
 
2126
        self.run_bzr('foo bar', stdin='zippy')
 
2127
        self.assertEqual('zippy', self.stdin)
 
2128
        self.assertEqual(['foo', 'bar'], self.argv)
 
2129
 
 
2130
    def test_working_dir(self):
 
2131
        """Test that run_bzr passes working_dir to _run_bzr_core"""
 
2132
        self.run_bzr('foo bar')
 
2133
        self.assertEqual(None, self.working_dir)
 
2134
        self.assertEqual(['foo', 'bar'], self.argv)
 
2135
 
 
2136
        self.run_bzr('foo bar', working_dir='baz')
 
2137
        self.assertEqual('baz', self.working_dir)
 
2138
        self.assertEqual(['foo', 'bar'], self.argv)
 
2139
 
 
2140
    def test_reject_extra_keyword_arguments(self):
 
2141
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
 
2142
                          error_regex=['error message'])
 
2143
 
 
2144
 
 
2145
class TestRunBzrCaptured(tests.TestCaseWithTransport):
 
2146
    # Does IO when testing the working_dir parameter.
 
2147
 
 
2148
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
2149
                         a_callable=None, *args, **kwargs):
 
2150
        self.stdin = stdin
 
2151
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
 
2152
        self.factory = bzrlib.ui.ui_factory
 
2153
        self.working_dir = osutils.getcwd()
 
2154
        stdout.write('foo\n')
 
2155
        stderr.write('bar\n')
 
2156
        return 0
 
2157
 
 
2158
    def test_stdin(self):
 
2159
        # test that the stdin keyword to _run_bzr_core is passed through to
 
2160
        # apply_redirected as a StringIO. We do this by overriding
 
2161
        # apply_redirected in this class, and then calling _run_bzr_core,
 
2162
        # which calls apply_redirected.
 
2163
        self.run_bzr(['foo', 'bar'], stdin='gam')
 
2164
        self.assertEqual('gam', self.stdin.read())
 
2165
        self.assertTrue(self.stdin is self.factory_stdin)
 
2166
        self.run_bzr(['foo', 'bar'], stdin='zippy')
 
2167
        self.assertEqual('zippy', self.stdin.read())
 
2168
        self.assertTrue(self.stdin is self.factory_stdin)
 
2169
 
 
2170
    def test_ui_factory(self):
 
2171
        # each invocation of self.run_bzr should get its
 
2172
        # own UI factory, which is an instance of TestUIFactory,
 
2173
        # with stdin, stdout and stderr attached to the stdin,
 
2174
        # stdout and stderr of the invoked run_bzr
 
2175
        current_factory = bzrlib.ui.ui_factory
 
2176
        self.run_bzr(['foo'])
 
2177
        self.failIf(current_factory is self.factory)
 
2178
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
2179
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
2180
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
2181
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
2182
        self.assertIsInstance(self.factory, tests.TestUIFactory)
 
2183
 
 
2184
    def test_working_dir(self):
 
2185
        self.build_tree(['one/', 'two/'])
 
2186
        cwd = osutils.getcwd()
 
2187
 
 
2188
        # Default is to work in the current directory
 
2189
        self.run_bzr(['foo', 'bar'])
 
2190
        self.assertEqual(cwd, self.working_dir)
 
2191
 
 
2192
        self.run_bzr(['foo', 'bar'], working_dir=None)
 
2193
        self.assertEqual(cwd, self.working_dir)
 
2194
 
 
2195
        # The function should be run in the alternative directory
 
2196
        # but afterwards the current working dir shouldn't be changed
 
2197
        self.run_bzr(['foo', 'bar'], working_dir='one')
 
2198
        self.assertNotEqual(cwd, self.working_dir)
 
2199
        self.assertEndsWith(self.working_dir, 'one')
 
2200
        self.assertEqual(cwd, osutils.getcwd())
 
2201
 
 
2202
        self.run_bzr(['foo', 'bar'], working_dir='two')
 
2203
        self.assertNotEqual(cwd, self.working_dir)
 
2204
        self.assertEndsWith(self.working_dir, 'two')
 
2205
        self.assertEqual(cwd, osutils.getcwd())
 
2206
 
 
2207
 
 
2208
class StubProcess(object):
 
2209
    """A stub process for testing run_bzr_subprocess."""
 
2210
    
 
2211
    def __init__(self, out="", err="", retcode=0):
 
2212
        self.out = out
 
2213
        self.err = err
 
2214
        self.returncode = retcode
 
2215
 
 
2216
    def communicate(self):
 
2217
        return self.out, self.err
 
2218
 
 
2219
 
 
2220
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
 
2221
    """Base class for tests testing how we might run bzr."""
 
2222
 
 
2223
    def setUp(self):
 
2224
        tests.TestCaseWithTransport.setUp(self)
 
2225
        self.subprocess_calls = []
 
2226
 
 
2227
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
2228
                             skip_if_plan_to_signal=False,
 
2229
                             working_dir=None,
 
2230
                             allow_plugins=False):
 
2231
        """capture what run_bzr_subprocess tries to do."""
 
2232
        self.subprocess_calls.append({'process_args':process_args,
 
2233
            'env_changes':env_changes,
 
2234
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
 
2235
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
 
2236
        return self.next_subprocess
 
2237
 
 
2238
 
 
2239
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2240
 
 
2241
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
 
2242
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
 
2243
 
 
2244
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
 
2245
        that will return static results. This assertion method populates those
 
2246
        results and also checks the arguments run_bzr_subprocess generates.
 
2247
        """
 
2248
        self.next_subprocess = process
 
2249
        try:
 
2250
            result = self.run_bzr_subprocess(*args, **kwargs)
 
2251
        except:
 
2252
            self.next_subprocess = None
 
2253
            for key, expected in expected_args.iteritems():
 
2254
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2255
            raise
 
2256
        else:
 
2257
            self.next_subprocess = None
 
2258
            for key, expected in expected_args.iteritems():
 
2259
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2260
            return result
 
2261
 
 
2262
    def test_run_bzr_subprocess(self):
 
2263
        """The run_bzr_helper_external command behaves nicely."""
 
2264
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2265
            StubProcess(), '--version')
 
2266
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2267
            StubProcess(), ['--version'])
 
2268
        # retcode=None disables retcode checking
 
2269
        result = self.assertRunBzrSubprocess({},
 
2270
            StubProcess(retcode=3), '--version', retcode=None)
 
2271
        result = self.assertRunBzrSubprocess({},
 
2272
            StubProcess(out="is free software"), '--version')
 
2273
        self.assertContainsRe(result[0], 'is free software')
 
2274
        # Running a subcommand that is missing errors
 
2275
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
 
2276
            {'process_args':['--versionn']}, StubProcess(retcode=3),
 
2277
            '--versionn')
 
2278
        # Unless it is told to expect the error from the subprocess
 
2279
        result = self.assertRunBzrSubprocess({},
 
2280
            StubProcess(retcode=3), '--versionn', retcode=3)
 
2281
        # Or to ignore retcode checking
 
2282
        result = self.assertRunBzrSubprocess({},
 
2283
            StubProcess(err="unknown command", retcode=3), '--versionn',
 
2284
            retcode=None)
 
2285
        self.assertContainsRe(result[1], 'unknown command')
 
2286
 
 
2287
    def test_env_change_passes_through(self):
 
2288
        self.assertRunBzrSubprocess(
 
2289
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
 
2290
            StubProcess(), '',
 
2291
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
 
2292
 
 
2293
    def test_no_working_dir_passed_as_None(self):
 
2294
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
 
2295
 
 
2296
    def test_no_working_dir_passed_through(self):
 
2297
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
 
2298
            working_dir='dir')
 
2299
 
 
2300
    def test_run_bzr_subprocess_no_plugins(self):
 
2301
        self.assertRunBzrSubprocess({'allow_plugins': False},
 
2302
            StubProcess(), '')
 
2303
 
 
2304
    def test_allow_plugins(self):
 
2305
        self.assertRunBzrSubprocess({'allow_plugins': True},
 
2306
            StubProcess(), '', allow_plugins=True)
 
2307
 
 
2308
 
 
2309
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2310
 
 
2311
    def test_finish_bzr_subprocess_with_error(self):
 
2312
        """finish_bzr_subprocess allows specification of the desired exit code.
 
2313
        """
 
2314
        process = StubProcess(err="unknown command", retcode=3)
 
2315
        result = self.finish_bzr_subprocess(process, retcode=3)
 
2316
        self.assertEqual('', result[0])
 
2317
        self.assertContainsRe(result[1], 'unknown command')
 
2318
 
 
2319
    def test_finish_bzr_subprocess_ignoring_retcode(self):
 
2320
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
2321
        process = StubProcess(err="unknown command", retcode=3)
 
2322
        result = self.finish_bzr_subprocess(process, retcode=None)
 
2323
        self.assertEqual('', result[0])
 
2324
        self.assertContainsRe(result[1], 'unknown command')
 
2325
 
 
2326
    def test_finish_subprocess_with_unexpected_retcode(self):
 
2327
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2328
        not the expected one.
 
2329
        """
 
2330
        process = StubProcess(err="unknown command", retcode=3)
 
2331
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
2332
                          process)
 
2333
 
 
2334
 
 
2335
class _DontSpawnProcess(Exception):
 
2336
    """A simple exception which just allows us to skip unnecessary steps"""
 
2337
 
 
2338
 
 
2339
class TestStartBzrSubProcess(tests.TestCase):
 
2340
 
 
2341
    def check_popen_state(self):
 
2342
        """Replace to make assertions when popen is called."""
 
2343
 
 
2344
    def _popen(self, *args, **kwargs):
 
2345
        """Record the command that is run, so that we can ensure it is correct"""
 
2346
        self.check_popen_state()
 
2347
        self._popen_args = args
 
2348
        self._popen_kwargs = kwargs
 
2349
        raise _DontSpawnProcess()
 
2350
 
 
2351
    def test_run_bzr_subprocess_no_plugins(self):
 
2352
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
 
2353
        command = self._popen_args[0]
 
2354
        self.assertEqual(sys.executable, command[0])
 
2355
        self.assertEqual(self.get_bzr_path(), command[1])
 
2356
        self.assertEqual(['--no-plugins'], command[2:])
 
2357
 
 
2358
    def test_allow_plugins(self):
 
2359
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2360
            allow_plugins=True)
 
2361
        command = self._popen_args[0]
 
2362
        self.assertEqual([], command[2:])
 
2363
 
 
2364
    def test_set_env(self):
 
2365
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2366
        # set in the child
 
2367
        def check_environment():
 
2368
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2369
        self.check_popen_state = check_environment
 
2370
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2371
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2372
        # not set in theparent
 
2373
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2374
 
 
2375
    def test_run_bzr_subprocess_env_del(self):
 
2376
        """run_bzr_subprocess can remove environment variables too."""
 
2377
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2378
        def check_environment():
 
2379
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2380
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
 
2381
        self.check_popen_state = check_environment
 
2382
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2383
            env_changes={'EXISTANT_ENV_VAR':None})
 
2384
        # Still set in parent
 
2385
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2386
        del os.environ['EXISTANT_ENV_VAR']
 
2387
 
 
2388
    def test_env_del_missing(self):
 
2389
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2390
        def check_environment():
 
2391
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2392
        self.check_popen_state = check_environment
 
2393
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2394
            env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2395
 
 
2396
    def test_working_dir(self):
 
2397
        """Test that we can specify the working dir for the child"""
 
2398
        orig_getcwd = osutils.getcwd
 
2399
        orig_chdir = os.chdir
 
2400
        chdirs = []
 
2401
        def chdir(path):
 
2402
            chdirs.append(path)
 
2403
        os.chdir = chdir
 
2404
        try:
 
2405
            def getcwd():
 
2406
                return 'current'
 
2407
            osutils.getcwd = getcwd
 
2408
            try:
 
2409
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2410
                    working_dir='foo')
 
2411
            finally:
 
2412
                osutils.getcwd = orig_getcwd
 
2413
        finally:
 
2414
            os.chdir = orig_chdir
 
2415
        self.assertEqual(['foo', 'current'], chdirs)
 
2416
 
 
2417
 
 
2418
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
 
2419
    """Tests that really need to do things with an external bzr."""
 
2420
 
 
2421
    def test_start_and_stop_bzr_subprocess_send_signal(self):
 
2422
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2423
        not the expected one.
 
2424
        """
 
2425
        self.disable_missing_extensions_warning()
 
2426
        process = self.start_bzr_subprocess(['wait-until-signalled'],
 
2427
                                            skip_if_plan_to_signal=True)
 
2428
        self.assertEqual('running\n', process.stdout.readline())
 
2429
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
 
2430
                                            retcode=3)
 
2431
        self.assertEqual('', result[0])
 
2432
        self.assertEqual('bzr: interrupted\n', result[1])
 
2433
 
 
2434
 
 
2435
class TestKnownFailure(tests.TestCase):
 
2436
 
 
2437
    def test_known_failure(self):
 
2438
        """Check that KnownFailure is defined appropriately."""
 
2439
        # a KnownFailure is an assertion error for compatability with unaware
 
2440
        # runners.
 
2441
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
2442
 
 
2443
    def test_expect_failure(self):
 
2444
        try:
 
2445
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
2446
        except tests.KnownFailure, e:
 
2447
            self.assertEqual('Doomed to failure', e.args[0])
 
2448
        try:
 
2449
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
2450
        except AssertionError, e:
 
2451
            self.assertEqual('Unexpected success.  Should have failed:'
 
2452
                             ' Doomed to failure', e.args[0])
 
2453
        else:
 
2454
            self.fail('Assertion not raised')
 
2455
 
 
2456
 
 
2457
class TestFeature(tests.TestCase):
 
2458
 
 
2459
    def test_caching(self):
 
2460
        """Feature._probe is called by the feature at most once."""
 
2461
        class InstrumentedFeature(tests.Feature):
 
2462
            def __init__(self):
 
2463
                super(InstrumentedFeature, self).__init__()
 
2464
                self.calls = []
 
2465
            def _probe(self):
 
2466
                self.calls.append('_probe')
 
2467
                return False
 
2468
        feature = InstrumentedFeature()
 
2469
        feature.available()
 
2470
        self.assertEqual(['_probe'], feature.calls)
 
2471
        feature.available()
 
2472
        self.assertEqual(['_probe'], feature.calls)
 
2473
 
 
2474
    def test_named_str(self):
 
2475
        """Feature.__str__ should thunk to feature_name()."""
 
2476
        class NamedFeature(tests.Feature):
 
2477
            def feature_name(self):
 
2478
                return 'symlinks'
 
2479
        feature = NamedFeature()
 
2480
        self.assertEqual('symlinks', str(feature))
 
2481
 
 
2482
    def test_default_str(self):
 
2483
        """Feature.__str__ should default to __class__.__name__."""
 
2484
        class NamedFeature(tests.Feature):
 
2485
            pass
 
2486
        feature = NamedFeature()
 
2487
        self.assertEqual('NamedFeature', str(feature))
 
2488
 
 
2489
 
 
2490
class TestUnavailableFeature(tests.TestCase):
 
2491
 
 
2492
    def test_access_feature(self):
 
2493
        feature = tests.Feature()
 
2494
        exception = tests.UnavailableFeature(feature)
 
2495
        self.assertIs(feature, exception.args[0])
 
2496
 
 
2497
 
 
2498
class TestSelftestFiltering(tests.TestCase):
 
2499
 
 
2500
    def setUp(self):
 
2501
        tests.TestCase.setUp(self)
 
2502
        self.suite = TestUtil.TestSuite()
 
2503
        self.loader = TestUtil.TestLoader()
 
2504
        self.suite.addTest(self.loader.loadTestsFromModule(
 
2505
            sys.modules['bzrlib.tests.test_selftest']))
 
2506
        self.all_names = _test_ids(self.suite)
 
2507
 
 
2508
    def test_condition_id_re(self):
 
2509
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2510
            'test_condition_id_re')
 
2511
        filtered_suite = tests.filter_suite_by_condition(
 
2512
            self.suite, tests.condition_id_re('test_condition_id_re'))
 
2513
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
2514
 
 
2515
    def test_condition_id_in_list(self):
 
2516
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2517
                      'test_condition_id_in_list']
 
2518
        id_list = tests.TestIdList(test_names)
 
2519
        filtered_suite = tests.filter_suite_by_condition(
 
2520
            self.suite, tests.condition_id_in_list(id_list))
 
2521
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
 
2522
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
 
2523
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2524
 
 
2525
    def test_condition_id_startswith(self):
 
2526
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2527
        start1 = klass + 'test_condition_id_starts'
 
2528
        start2 = klass + 'test_condition_id_in'
 
2529
        test_names = [ klass + 'test_condition_id_in_list',
 
2530
                      klass + 'test_condition_id_startswith',
 
2531
                     ]
 
2532
        filtered_suite = tests.filter_suite_by_condition(
 
2533
            self.suite, tests.condition_id_startswith([start1, start2]))
 
2534
        self.assertEqual(test_names, _test_ids(filtered_suite))
 
2535
 
 
2536
    def test_condition_isinstance(self):
 
2537
        filtered_suite = tests.filter_suite_by_condition(
 
2538
            self.suite, tests.condition_isinstance(self.__class__))
 
2539
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2540
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
 
2541
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2542
 
 
2543
    def test_exclude_tests_by_condition(self):
 
2544
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2545
            'test_exclude_tests_by_condition')
 
2546
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
 
2547
            lambda x:x.id() == excluded_name)
 
2548
        self.assertEqual(len(self.all_names) - 1,
 
2549
            filtered_suite.countTestCases())
 
2550
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
2551
        remaining_names = list(self.all_names)
 
2552
        remaining_names.remove(excluded_name)
 
2553
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
2554
 
 
2555
    def test_exclude_tests_by_re(self):
 
2556
        self.all_names = _test_ids(self.suite)
 
2557
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
2558
                                                   'exclude_tests_by_re')
 
2559
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2560
            'test_exclude_tests_by_re')
 
2561
        self.assertEqual(len(self.all_names) - 1,
 
2562
            filtered_suite.countTestCases())
 
2563
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
2564
        remaining_names = list(self.all_names)
 
2565
        remaining_names.remove(excluded_name)
 
2566
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
2567
 
 
2568
    def test_filter_suite_by_condition(self):
 
2569
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2570
            'test_filter_suite_by_condition')
 
2571
        filtered_suite = tests.filter_suite_by_condition(self.suite,
 
2572
            lambda x:x.id() == test_name)
 
2573
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
2574
 
 
2575
    def test_filter_suite_by_re(self):
 
2576
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
2577
                                                  'test_filter_suite_by_r')
 
2578
        filtered_names = _test_ids(filtered_suite)
 
2579
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
2580
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
2581
 
 
2582
    def test_filter_suite_by_id_list(self):
 
2583
        test_list = ['bzrlib.tests.test_selftest.'
 
2584
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
 
2585
        filtered_suite = tests.filter_suite_by_id_list(
 
2586
            self.suite, tests.TestIdList(test_list))
 
2587
        filtered_names = _test_ids(filtered_suite)
 
2588
        self.assertEqual(
 
2589
            filtered_names,
 
2590
            ['bzrlib.tests.test_selftest.'
 
2591
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
 
2592
 
 
2593
    def test_filter_suite_by_id_startswith(self):
 
2594
        # By design this test may fail if another test is added whose name also
 
2595
        # begins with one of the start value used.
 
2596
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2597
        start1 = klass + 'test_filter_suite_by_id_starts'
 
2598
        start2 = klass + 'test_filter_suite_by_id_li'
 
2599
        test_list = [klass + 'test_filter_suite_by_id_list',
 
2600
                     klass + 'test_filter_suite_by_id_startswith',
 
2601
                     ]
 
2602
        filtered_suite = tests.filter_suite_by_id_startswith(
 
2603
            self.suite, [start1, start2])
 
2604
        self.assertEqual(
 
2605
            test_list,
 
2606
            _test_ids(filtered_suite),
 
2607
            )
 
2608
 
 
2609
    def test_preserve_input(self):
 
2610
        # NB: Surely this is something in the stdlib to do this?
 
2611
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
2612
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
 
2613
 
 
2614
    def test_randomize_suite(self):
 
2615
        randomized_suite = tests.randomize_suite(self.suite)
 
2616
        # randomizing should not add or remove test names.
 
2617
        self.assertEqual(set(_test_ids(self.suite)),
 
2618
                         set(_test_ids(randomized_suite)))
 
2619
        # Technically, this *can* fail, because random.shuffle(list) can be
 
2620
        # equal to list. Trying multiple times just pushes the frequency back.
 
2621
        # As its len(self.all_names)!:1, the failure frequency should be low
 
2622
        # enough to ignore. RBC 20071021.
 
2623
        # It should change the order.
 
2624
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
 
2625
        # But not the length. (Possibly redundant with the set test, but not
 
2626
        # necessarily.)
 
2627
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
 
2628
 
 
2629
    def test_split_suit_by_condition(self):
 
2630
        self.all_names = _test_ids(self.suite)
 
2631
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2632
        split_suite = tests.split_suite_by_condition(self.suite, condition)
 
2633
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2634
            'test_filter_suite_by_re')
 
2635
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2636
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2637
        remaining_names = list(self.all_names)
 
2638
        remaining_names.remove(filtered_name)
 
2639
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2640
 
 
2641
    def test_split_suit_by_re(self):
 
2642
        self.all_names = _test_ids(self.suite)
 
2643
        split_suite = tests.split_suite_by_re(self.suite,
 
2644
                                              'test_filter_suite_by_r')
 
2645
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2646
            'test_filter_suite_by_re')
 
2647
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2648
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2649
        remaining_names = list(self.all_names)
 
2650
        remaining_names.remove(filtered_name)
 
2651
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2652
 
 
2653
 
 
2654
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2655
 
 
2656
    def test_check_inventory_shape(self):
 
2657
        files = ['a', 'b/', 'b/c']
 
2658
        tree = self.make_branch_and_tree('.')
 
2659
        self.build_tree(files)
 
2660
        tree.add(files)
 
2661
        tree.lock_read()
 
2662
        try:
 
2663
            self.check_inventory_shape(tree.inventory, files)
 
2664
        finally:
 
2665
            tree.unlock()
 
2666
 
 
2667
 
 
2668
class TestBlackboxSupport(tests.TestCase):
 
2669
    """Tests for testsuite blackbox features."""
 
2670
 
 
2671
    def test_run_bzr_failure_not_caught(self):
 
2672
        # When we run bzr in blackbox mode, we want any unexpected errors to
 
2673
        # propagate up to the test suite so that it can show the error in the
 
2674
        # usual way, and we won't get a double traceback.
 
2675
        e = self.assertRaises(
 
2676
            AssertionError,
 
2677
            self.run_bzr, ['assert-fail'])
 
2678
        # make sure we got the real thing, not an error from somewhere else in
 
2679
        # the test framework
 
2680
        self.assertEquals('always fails', str(e))
 
2681
        # check that there's no traceback in the test log
 
2682
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
 
2683
            r'Traceback')
 
2684
 
 
2685
    def test_run_bzr_user_error_caught(self):
 
2686
        # Running bzr in blackbox mode, normal/expected/user errors should be
 
2687
        # caught in the regular way and turned into an error message plus exit
 
2688
        # code.
 
2689
        transport_server = MemoryServer()
 
2690
        transport_server.setUp()
 
2691
        self.addCleanup(transport_server.tearDown)
 
2692
        url = transport_server.get_url()
 
2693
        self.permit_url(url)
 
2694
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
 
2695
        self.assertEqual(out, '')
 
2696
        self.assertContainsRe(err,
 
2697
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2698
 
 
2699
 
 
2700
class TestTestLoader(tests.TestCase):
 
2701
    """Tests for the test loader."""
 
2702
 
 
2703
    def _get_loader_and_module(self):
 
2704
        """Gets a TestLoader and a module with one test in it."""
 
2705
        loader = TestUtil.TestLoader()
 
2706
        module = {}
 
2707
        class Stub(tests.TestCase):
 
2708
            def test_foo(self):
 
2709
                pass
 
2710
        class MyModule(object):
 
2711
            pass
 
2712
        MyModule.a_class = Stub
 
2713
        module = MyModule()
 
2714
        return loader, module
 
2715
 
 
2716
    def test_module_no_load_tests_attribute_loads_classes(self):
 
2717
        loader, module = self._get_loader_and_module()
 
2718
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
 
2719
 
 
2720
    def test_module_load_tests_attribute_gets_called(self):
 
2721
        loader, module = self._get_loader_and_module()
 
2722
        # 'self' is here because we're faking the module with a class. Regular
 
2723
        # load_tests do not need that :)
 
2724
        def load_tests(self, standard_tests, module, loader):
 
2725
            result = loader.suiteClass()
 
2726
            for test in tests.iter_suite_tests(standard_tests):
 
2727
                result.addTests([test, test])
 
2728
            return result
 
2729
        # add a load_tests() method which multiplies the tests from the module.
 
2730
        module.__class__.load_tests = load_tests
 
2731
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2732
 
 
2733
    def test_load_tests_from_module_name_smoke_test(self):
 
2734
        loader = TestUtil.TestLoader()
 
2735
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2736
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2737
                          _test_ids(suite))
 
2738
 
 
2739
    def test_load_tests_from_module_name_with_bogus_module_name(self):
 
2740
        loader = TestUtil.TestLoader()
 
2741
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
 
2742
 
 
2743
 
 
2744
class TestTestIdList(tests.TestCase):
 
2745
 
 
2746
    def _create_id_list(self, test_list):
 
2747
        return tests.TestIdList(test_list)
 
2748
 
 
2749
    def _create_suite(self, test_id_list):
 
2750
 
 
2751
        class Stub(tests.TestCase):
 
2752
            def test_foo(self):
 
2753
                pass
 
2754
 
 
2755
        def _create_test_id(id):
 
2756
            return lambda: id
 
2757
 
 
2758
        suite = TestUtil.TestSuite()
 
2759
        for id in test_id_list:
 
2760
            t  = Stub('test_foo')
 
2761
            t.id = _create_test_id(id)
 
2762
            suite.addTest(t)
 
2763
        return suite
 
2764
 
 
2765
    def _test_ids(self, test_suite):
 
2766
        """Get the ids for the tests in a test suite."""
 
2767
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
2768
 
 
2769
    def test_empty_list(self):
 
2770
        id_list = self._create_id_list([])
 
2771
        self.assertEquals({}, id_list.tests)
 
2772
        self.assertEquals({}, id_list.modules)
 
2773
 
 
2774
    def test_valid_list(self):
 
2775
        id_list = self._create_id_list(
 
2776
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
 
2777
             'mod1.func1', 'mod1.cl2.meth2',
 
2778
             'mod1.submod1',
 
2779
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
 
2780
             ])
 
2781
        self.assertTrue(id_list.refers_to('mod1'))
 
2782
        self.assertTrue(id_list.refers_to('mod1.submod1'))
 
2783
        self.assertTrue(id_list.refers_to('mod1.submod2'))
 
2784
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
 
2785
        self.assertTrue(id_list.includes('mod1.submod1'))
 
2786
        self.assertTrue(id_list.includes('mod1.func1'))
 
2787
 
 
2788
    def test_bad_chars_in_params(self):
 
2789
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
 
2790
        self.assertTrue(id_list.refers_to('mod1'))
 
2791
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
 
2792
 
 
2793
    def test_module_used(self):
 
2794
        id_list = self._create_id_list(['mod.class.meth'])
 
2795
        self.assertTrue(id_list.refers_to('mod'))
 
2796
        self.assertTrue(id_list.refers_to('mod.class'))
 
2797
        self.assertTrue(id_list.refers_to('mod.class.meth'))
 
2798
 
 
2799
    def test_test_suite_matches_id_list_with_unknown(self):
 
2800
        loader = TestUtil.TestLoader()
 
2801
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2802
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2803
                     'bogus']
 
2804
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
 
2805
        self.assertEquals(['bogus'], not_found)
 
2806
        self.assertEquals([], duplicates)
 
2807
 
 
2808
    def test_suite_matches_id_list_with_duplicates(self):
 
2809
        loader = TestUtil.TestLoader()
 
2810
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2811
        dupes = loader.suiteClass()
 
2812
        for test in tests.iter_suite_tests(suite):
 
2813
            dupes.addTest(test)
 
2814
            dupes.addTest(test) # Add it again
 
2815
 
 
2816
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2817
        not_found, duplicates = tests.suite_matches_id_list(
 
2818
            dupes, test_list)
 
2819
        self.assertEquals([], not_found)
 
2820
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2821
                          duplicates)
 
2822
 
 
2823
 
 
2824
class TestTestSuite(tests.TestCase):
 
2825
 
 
2826
    def test__test_suite_testmod_names(self):
 
2827
        # Test that a plausible list of test module names are returned
 
2828
        # by _test_suite_testmod_names.
 
2829
        test_list = tests._test_suite_testmod_names()
 
2830
        self.assertSubset([
 
2831
            'bzrlib.tests.blackbox',
 
2832
            'bzrlib.tests.per_transport',
 
2833
            'bzrlib.tests.test_selftest',
 
2834
            ],
 
2835
            test_list)
 
2836
 
 
2837
    def test__test_suite_modules_to_doctest(self):
 
2838
        # Test that a plausible list of modules to doctest is returned
 
2839
        # by _test_suite_modules_to_doctest.
 
2840
        test_list = tests._test_suite_modules_to_doctest()
 
2841
        self.assertSubset([
 
2842
            'bzrlib.timestamp',
 
2843
            ],
 
2844
            test_list)
 
2845
 
 
2846
    def test_test_suite(self):
 
2847
        # test_suite() loads the entire test suite to operate. To avoid this
 
2848
        # overhead, and yet still be confident that things are happening,
 
2849
        # we temporarily replace two functions used by test_suite with 
 
2850
        # test doubles that supply a few sample tests to load, and check they
 
2851
        # are loaded.
 
2852
        calls = []
 
2853
        def _test_suite_testmod_names():
 
2854
            calls.append("testmod_names")
 
2855
            return [
 
2856
                'bzrlib.tests.blackbox.test_branch',
 
2857
                'bzrlib.tests.per_transport',
 
2858
                'bzrlib.tests.test_selftest',
 
2859
                ]
 
2860
        original_testmod_names = tests._test_suite_testmod_names
 
2861
        def _test_suite_modules_to_doctest():
 
2862
            calls.append("modules_to_doctest")
 
2863
            return ['bzrlib.timestamp']
 
2864
        orig_modules_to_doctest = tests._test_suite_modules_to_doctest
 
2865
        def restore_names():
 
2866
            tests._test_suite_testmod_names = original_testmod_names
 
2867
            tests._test_suite_modules_to_doctest = orig_modules_to_doctest
 
2868
        self.addCleanup(restore_names)
 
2869
        tests._test_suite_testmod_names = _test_suite_testmod_names
 
2870
        tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
 
2871
        expected_test_list = [
 
2872
            # testmod_names
 
2873
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2874
            ('bzrlib.tests.per_transport.TransportTests'
 
2875
             '.test_abspath(LocalTransport,LocalURLServer)'),
 
2876
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2877
            # modules_to_doctest
 
2878
            'bzrlib.timestamp.format_highres_date',
 
2879
            # plugins can't be tested that way since selftest may be run with
 
2880
            # --no-plugins
 
2881
            ]
 
2882
        suite = tests.test_suite()
 
2883
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
 
2884
            set(calls))
 
2885
        self.assertSubset(expected_test_list, _test_ids(suite))
 
2886
 
 
2887
    def test_test_suite_list_and_start(self):
 
2888
        # We cannot test this at the same time as the main load, because we want
 
2889
        # to know that starting_with == None works. So a second load is
 
2890
        # incurred - note that the starting_with parameter causes a partial load
 
2891
        # rather than a full load so this test should be pretty quick.
 
2892
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
2893
        suite = tests.test_suite(test_list,
 
2894
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
2895
        # test_test_suite_list_and_start is not included 
 
2896
        self.assertEquals(test_list, _test_ids(suite))
 
2897
 
 
2898
 
 
2899
class TestLoadTestIdList(tests.TestCaseInTempDir):
 
2900
 
 
2901
    def _create_test_list_file(self, file_name, content):
 
2902
        fl = open(file_name, 'wt')
 
2903
        fl.write(content)
 
2904
        fl.close()
 
2905
 
 
2906
    def test_load_unknown(self):
 
2907
        self.assertRaises(errors.NoSuchFile,
 
2908
                          tests.load_test_id_list, 'i_do_not_exist')
 
2909
 
 
2910
    def test_load_test_list(self):
 
2911
        test_list_fname = 'test.list'
 
2912
        self._create_test_list_file(test_list_fname,
 
2913
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
 
2914
        tlist = tests.load_test_id_list(test_list_fname)
 
2915
        self.assertEquals(2, len(tlist))
 
2916
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2917
        self.assertEquals('mod2.cl2.meth2', tlist[1])
 
2918
 
 
2919
    def test_load_dirty_file(self):
 
2920
        test_list_fname = 'test.list'
 
2921
        self._create_test_list_file(test_list_fname,
 
2922
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
 
2923
                                    'bar baz\n')
 
2924
        tlist = tests.load_test_id_list(test_list_fname)
 
2925
        self.assertEquals(4, len(tlist))
 
2926
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2927
        self.assertEquals('', tlist[1])
 
2928
        self.assertEquals('mod2.cl2.meth2', tlist[2])
 
2929
        self.assertEquals('bar baz', tlist[3])
 
2930
 
 
2931
 
 
2932
class TestFilteredByModuleTestLoader(tests.TestCase):
 
2933
 
 
2934
    def _create_loader(self, test_list):
 
2935
        id_filter = tests.TestIdList(test_list)
 
2936
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
2937
        return loader
 
2938
 
 
2939
    def test_load_tests(self):
 
2940
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2941
        loader = self._create_loader(test_list)
 
2942
 
 
2943
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2944
        self.assertEquals(test_list, _test_ids(suite))
 
2945
 
 
2946
    def test_exclude_tests(self):
 
2947
        test_list = ['bogus']
 
2948
        loader = self._create_loader(test_list)
 
2949
 
 
2950
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2951
        self.assertEquals([], _test_ids(suite))
 
2952
 
 
2953
 
 
2954
class TestFilteredByNameStartTestLoader(tests.TestCase):
 
2955
 
 
2956
    def _create_loader(self, name_start):
 
2957
        def needs_module(name):
 
2958
            return name.startswith(name_start) or name_start.startswith(name)
 
2959
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
 
2960
        return loader
 
2961
 
 
2962
    def test_load_tests(self):
 
2963
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2964
        loader = self._create_loader('bzrlib.tests.test_samp')
 
2965
 
 
2966
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2967
        self.assertEquals(test_list, _test_ids(suite))
 
2968
 
 
2969
    def test_load_tests_inside_module(self):
 
2970
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2971
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
2972
 
 
2973
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2974
        self.assertEquals(test_list, _test_ids(suite))
 
2975
 
 
2976
    def test_exclude_tests(self):
 
2977
        test_list = ['bogus']
 
2978
        loader = self._create_loader('bogus')
 
2979
 
 
2980
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2981
        self.assertEquals([], _test_ids(suite))
 
2982
 
 
2983
 
 
2984
class TestTestPrefixRegistry(tests.TestCase):
 
2985
 
 
2986
    def _get_registry(self):
 
2987
        tp_registry = tests.TestPrefixAliasRegistry()
 
2988
        return tp_registry
 
2989
 
 
2990
    def test_register_new_prefix(self):
 
2991
        tpr = self._get_registry()
 
2992
        tpr.register('foo', 'fff.ooo.ooo')
 
2993
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
2994
 
 
2995
    def test_register_existing_prefix(self):
 
2996
        tpr = self._get_registry()
 
2997
        tpr.register('bar', 'bbb.aaa.rrr')
 
2998
        tpr.register('bar', 'bBB.aAA.rRR')
 
2999
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
3000
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
3001
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
3002
 
 
3003
    def test_get_unknown_prefix(self):
 
3004
        tpr = self._get_registry()
 
3005
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
3006
 
 
3007
    def test_resolve_prefix(self):
 
3008
        tpr = self._get_registry()
 
3009
        tpr.register('bar', 'bb.aa.rr')
 
3010
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
3011
 
 
3012
    def test_resolve_unknown_alias(self):
 
3013
        tpr = self._get_registry()
 
3014
        self.assertRaises(errors.BzrCommandError,
 
3015
                          tpr.resolve_alias, 'I am not a prefix')
 
3016
 
 
3017
    def test_predefined_prefixes(self):
 
3018
        tpr = tests.test_prefix_alias_registry
 
3019
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
3020
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
3021
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
3022
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
3023
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
3024
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
3025
 
 
3026
 
 
3027
class TestRunSuite(tests.TestCase):
 
3028
 
 
3029
    def test_runner_class(self):
 
3030
        """run_suite accepts and uses a runner_class keyword argument."""
 
3031
        class Stub(tests.TestCase):
 
3032
            def test_foo(self):
 
3033
                pass
 
3034
        suite = Stub("test_foo")
 
3035
        calls = []
 
3036
        class MyRunner(tests.TextTestRunner):
 
3037
            def run(self, test):
 
3038
                calls.append(test)
 
3039
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
3040
                                                self.verbosity)
 
3041
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
3042
        self.assertLength(1, calls)