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

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-09-13 12:50:28 UTC
  • mfrom: (7096.2.2 empty-port)
  • Revision ID: breezy.the.bot@gmail.com-20180913125028-mja5gz8xsams9iey
Allow port to be empty when parsing URLs.

Merged from https://code.launchpad.net/~jelmer/brz/empty-port/+merge/354640

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2013, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Tests for the test framework."""
18
18
 
19
 
from cStringIO import StringIO
20
 
from doctest import ELLIPSIS
 
19
import gc
 
20
import doctest
 
21
from functools import reduce
 
22
from io import BytesIO, TextIOWrapper
21
23
import os
22
24
import signal
23
25
import sys
 
26
import threading
24
27
import time
25
28
import unittest
26
29
import warnings
27
30
 
28
 
from testtools import MultiTestResult
 
31
from testtools import (
 
32
    ExtendedToOriginalDecorator,
 
33
    MultiTestResult,
 
34
    )
 
35
from testtools.content import Content
29
36
from testtools.content_type import ContentType
30
37
from testtools.matchers import (
31
38
    DocTestMatches,
32
39
    Equals,
33
40
    )
34
 
import testtools.tests.helpers
 
41
import testtools.testresult.doubles
35
42
 
36
 
import bzrlib
37
 
from bzrlib import (
 
43
import breezy
 
44
from .. import (
38
45
    branchbuilder,
39
 
    bzrdir,
40
 
    debug,
 
46
    controldir,
41
47
    errors,
 
48
    hooks,
42
49
    lockdir,
43
50
    memorytree,
44
51
    osutils,
45
 
    progress,
46
 
    remote,
47
52
    repository,
48
53
    symbol_versioning,
49
54
    tests,
50
55
    transport,
51
56
    workingtree,
52
57
    )
53
 
from bzrlib.repofmt import (
 
58
from ..bzr import (
 
59
    bzrdir,
 
60
    remote,
 
61
    workingtree_3,
 
62
    workingtree_4,
 
63
    )
 
64
from ..bzr import (
54
65
    groupcompress_repo,
55
 
    pack_repo,
56
 
    weaverepo,
57
 
    )
58
 
from bzrlib.symbol_versioning import (
 
66
    )
 
67
from ..sixish import (
 
68
    PY3,
 
69
    StringIO,
 
70
    text_type,
 
71
    )
 
72
from ..symbol_versioning import (
59
73
    deprecated_function,
60
74
    deprecated_in,
61
75
    deprecated_method,
62
76
    )
63
 
from bzrlib.tests import (
 
77
from . import (
64
78
    features,
65
79
    test_lsprof,
66
80
    test_server,
67
 
    test_sftp_transport,
68
81
    TestUtil,
69
82
    )
70
 
from bzrlib.trace import note
71
 
from bzrlib.transport import memory
72
 
from bzrlib.version import _get_bzr_source_tree
 
83
from ..trace import note, mutter
 
84
from ..transport import memory
73
85
 
74
86
 
75
87
def _test_ids(test_suite):
77
89
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
78
90
 
79
91
 
80
 
class SelftestTests(tests.TestCase):
81
 
 
82
 
    def test_import_tests(self):
83
 
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
84
 
        self.assertEqual(mod.SelftestTests, SelftestTests)
85
 
 
86
 
    def test_import_test_failure(self):
87
 
        self.assertRaises(ImportError,
88
 
                          TestUtil._load_module_by_name,
89
 
                          'bzrlib.no-name-yet')
90
 
 
91
 
 
92
92
class MetaTestLog(tests.TestCase):
93
93
 
94
94
    def test_logging(self):
100
100
            "text", "plain", {"charset": "utf8"})))
101
101
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
102
102
        self.assertThat(self.get_log(),
103
 
            DocTestMatches(u"...a test message\n", ELLIPSIS))
104
 
 
105
 
 
106
 
class TestUnicodeFilename(tests.TestCase):
107
 
 
108
 
    def test_probe_passes(self):
109
 
        """UnicodeFilename._probe passes."""
110
 
        # We can't test much more than that because the behaviour depends
111
 
        # on the platform.
112
 
        tests.UnicodeFilename._probe()
 
103
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
113
104
 
114
105
 
115
106
class TestTreeShape(tests.TestCaseInTempDir):
116
107
 
117
108
    def test_unicode_paths(self):
118
 
        self.requireFeature(tests.UnicodeFilename)
 
109
        self.requireFeature(features.UnicodeFilenameFeature)
119
110
 
120
111
        filename = u'hell\u00d8'
121
 
        self.build_tree_contents([(filename, 'contents of hello')])
122
 
        self.failUnlessExists(filename)
 
112
        self.build_tree_contents([(filename, b'contents of hello')])
 
113
        self.assertPathExists(filename)
 
114
 
 
115
 
 
116
class TestClassesAvailable(tests.TestCase):
 
117
    """As a convenience we expose Test* classes from breezy.tests"""
 
118
 
 
119
    def test_test_case(self):
 
120
        from . import TestCase
 
121
 
 
122
    def test_test_loader(self):
 
123
        from . import TestLoader
 
124
 
 
125
    def test_test_suite(self):
 
126
        from . import TestSuite
123
127
 
124
128
 
125
129
class TestTransportScenarios(tests.TestCase):
138
142
        class MockModule(object):
139
143
            def get_test_permutations(self):
140
144
                return sample_permutation
141
 
        sample_permutation = [(1,2), (3,4)]
142
 
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
145
        sample_permutation = [(1, 2), (3, 4)]
 
146
        from .per_transport import get_transport_test_permutations
143
147
        self.assertEqual(sample_permutation,
144
148
                         get_transport_test_permutations(MockModule()))
145
149
 
148
152
        # as there are in all the registered transport modules - we assume if
149
153
        # this matches its probably doing the right thing especially in
150
154
        # combination with the tests for setting the right classes below.
151
 
        from bzrlib.tests.per_transport import transport_test_permutations
152
 
        from bzrlib.transport import _get_transport_modules
 
155
        from .per_transport import transport_test_permutations
 
156
        from ..transport import _get_transport_modules
153
157
        modules = _get_transport_modules()
154
158
        permutation_count = 0
155
159
        for module in modules:
166
170
        # This test used to know about all the possible transports and the
167
171
        # order they were returned but that seems overly brittle (mbp
168
172
        # 20060307)
169
 
        from bzrlib.tests.per_transport import transport_test_permutations
 
173
        from .per_transport import transport_test_permutations
170
174
        scenarios = transport_test_permutations()
171
175
        # there are at least that many builtin transports
172
176
        self.assertTrue(len(scenarios) > 6)
173
177
        one_scenario = scenarios[0]
174
178
        self.assertIsInstance(one_scenario[0], str)
175
179
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
176
 
                                   bzrlib.transport.Transport))
 
180
                                   breezy.transport.Transport))
177
181
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
178
 
                                   bzrlib.transport.Server))
 
182
                                   breezy.transport.Server))
179
183
 
180
184
 
181
185
class TestBranchScenarios(tests.TestCase):
183
187
    def test_scenarios(self):
184
188
        # check that constructor parameters are passed through to the adapted
185
189
        # test.
186
 
        from bzrlib.tests.per_branch import make_scenarios
 
190
        from .per_branch import make_scenarios
187
191
        server1 = "a"
188
192
        server2 = "b"
189
193
        formats = [("c", "C"), ("d", "D")]
208
212
    def test_scenarios(self):
209
213
        # check that constructor parameters are passed through to the adapted
210
214
        # test.
211
 
        from bzrlib.tests.per_bzrdir import make_scenarios
 
215
        from .per_controldir import make_scenarios
212
216
        vfs_factory = "v"
213
217
        server1 = "a"
214
218
        server2 = "b"
231
235
class TestRepositoryScenarios(tests.TestCase):
232
236
 
233
237
    def test_formats_to_scenarios(self):
234
 
        from bzrlib.tests.per_repository import formats_to_scenarios
 
238
        from .per_repository import formats_to_scenarios
235
239
        formats = [("(c)", remote.RemoteRepositoryFormat()),
236
240
                   ("(d)", repository.format_registry.get(
237
 
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
 
241
                    b'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
238
242
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
239
243
            None)
240
244
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
272
276
    """Tests for the test adaption facilities."""
273
277
 
274
278
    def test_apply_scenario(self):
275
 
        from bzrlib.tests import apply_scenario
 
279
        from breezy.tests import apply_scenario
276
280
        input_test = TestTestScenarioApplication("test_apply_scenario")
277
281
        # setup two adapted tests
278
282
        adapted_test1 = apply_scenario(input_test,
294
298
        self.assertEqual("readonly-server",
295
299
            adapted_test1.transport_readonly_server)
296
300
        self.assertEqual(
297
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
301
            "breezy.tests.test_selftest.TestTestScenarioApplication."
298
302
            "test_apply_scenario(new id)",
299
303
            adapted_test1.id())
300
304
        self.assertEqual(None, adapted_test2.bzrdir_format)
301
305
        self.assertEqual(
302
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
306
            "breezy.tests.test_selftest.TestTestScenarioApplication."
303
307
            "test_apply_scenario(new id 2)",
304
308
            adapted_test2.id())
305
309
 
309
313
    def test_scenarios(self):
310
314
        # check that constructor parameters are passed through to the adapted
311
315
        # test.
312
 
        from bzrlib.tests.per_interrepository import make_scenarios
 
316
        from .per_interrepository import make_scenarios
313
317
        server1 = "a"
314
318
        server2 = "b"
315
 
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
 
319
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
316
320
        scenarios = make_scenarios(server1, server2, formats)
317
321
        self.assertEqual([
318
322
            ('C0,str,str',
319
323
             {'repository_format': 'C1',
320
324
              'repository_format_to': 'C2',
321
325
              'transport_readonly_server': 'b',
322
 
              'transport_server': 'a'}),
 
326
              'transport_server': 'a',
 
327
              'extra_setup': 'C3'}),
323
328
            ('D0,str,str',
324
329
             {'repository_format': 'D1',
325
330
              'repository_format_to': 'D2',
326
331
              'transport_readonly_server': 'b',
327
 
              'transport_server': 'a'})],
 
332
              'transport_server': 'a',
 
333
              'extra_setup': 'D3'})],
328
334
            scenarios)
329
335
 
330
336
 
333
339
    def test_scenarios(self):
334
340
        # check that constructor parameters are passed through to the adapted
335
341
        # test.
336
 
        from bzrlib.tests.per_workingtree import make_scenarios
 
342
        from .per_workingtree import make_scenarios
337
343
        server1 = "a"
338
344
        server2 = "b"
339
 
        formats = [workingtree.WorkingTreeFormat2(),
340
 
                   workingtree.WorkingTreeFormat3(),]
341
 
        scenarios = make_scenarios(server1, server2, formats)
 
345
        formats = [workingtree_4.WorkingTreeFormat4(),
 
346
                   workingtree_3.WorkingTreeFormat3(),
 
347
                   workingtree_4.WorkingTreeFormat6()]
 
348
        scenarios = make_scenarios(server1, server2, formats,
 
349
            remote_server='c', remote_readonly_server='d',
 
350
            remote_backing_server='e')
342
351
        self.assertEqual([
343
 
            ('WorkingTreeFormat2',
344
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
352
            ('WorkingTreeFormat4',
 
353
             {'bzrdir_format': formats[0]._matchingcontroldir,
345
354
              'transport_readonly_server': 'b',
346
355
              'transport_server': 'a',
347
356
              'workingtree_format': formats[0]}),
348
357
            ('WorkingTreeFormat3',
349
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
350
 
              'transport_readonly_server': 'b',
351
 
              'transport_server': 'a',
352
 
              'workingtree_format': formats[1]})],
353
 
            scenarios)
 
358
             {'bzrdir_format': formats[1]._matchingcontroldir,
 
359
              'transport_readonly_server': 'b',
 
360
              'transport_server': 'a',
 
361
              'workingtree_format': formats[1]}),
 
362
            ('WorkingTreeFormat6',
 
363
             {'bzrdir_format': formats[2]._matchingcontroldir,
 
364
              'transport_readonly_server': 'b',
 
365
              'transport_server': 'a',
 
366
              'workingtree_format': formats[2]}),
 
367
            ('WorkingTreeFormat6,remote',
 
368
             {'bzrdir_format': formats[2]._matchingcontroldir,
 
369
              'repo_is_remote': True,
 
370
              'transport_readonly_server': 'd',
 
371
              'transport_server': 'c',
 
372
              'vfs_transport_factory': 'e',
 
373
              'workingtree_format': formats[2]}),
 
374
            ], scenarios)
354
375
 
355
376
 
356
377
class TestTreeScenarios(tests.TestCase):
357
378
 
358
379
    def test_scenarios(self):
359
380
        # the tree implementation scenario generator is meant to setup one
360
 
        # instance for each working tree format, and one additional instance
 
381
        # instance for each working tree format, one additional instance
361
382
        # that will use the default wt format, but create a revision tree for
362
 
        # the tests.  this means that the wt ones should have the
363
 
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
364
 
        # revision one set to revision_tree_from_workingtree.
 
383
        # the tests, and one more that uses the default wt format as a
 
384
        # lightweight checkout of a remote repository.  This means that the wt
 
385
        # ones should have the workingtree_to_test_tree attribute set to
 
386
        # 'return_parameter' and the revision one set to
 
387
        # revision_tree_from_workingtree.
365
388
 
366
 
        from bzrlib.tests.per_tree import (
 
389
        from .per_tree import (
367
390
            _dirstate_tree_from_workingtree,
368
391
            make_scenarios,
369
392
            preview_tree_pre,
373
396
            )
374
397
        server1 = "a"
375
398
        server2 = "b"
376
 
        formats = [workingtree.WorkingTreeFormat2(),
377
 
                   workingtree.WorkingTreeFormat3(),]
 
399
        smart_server = test_server.SmartTCPServer_for_testing
 
400
        smart_readonly_server = test_server.ReadonlySmartTCPServer_for_testing
 
401
        mem_server = memory.MemoryServer
 
402
        formats = [workingtree_4.WorkingTreeFormat4(),
 
403
                   workingtree_3.WorkingTreeFormat3(),]
378
404
        scenarios = make_scenarios(server1, server2, formats)
379
 
        self.assertEqual(7, len(scenarios))
380
 
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
381
 
        wt4_format = workingtree.WorkingTreeFormat4()
382
 
        wt5_format = workingtree.WorkingTreeFormat5()
 
405
        self.assertEqual(8, len(scenarios))
 
406
        default_wt_format = workingtree.format_registry.get_default()
 
407
        wt4_format = workingtree_4.WorkingTreeFormat4()
 
408
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
409
        wt6_format = workingtree_4.WorkingTreeFormat6()
383
410
        expected_scenarios = [
384
 
            ('WorkingTreeFormat2',
385
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
411
            ('WorkingTreeFormat4',
 
412
             {'bzrdir_format': formats[0]._matchingcontroldir,
386
413
              'transport_readonly_server': 'b',
387
414
              'transport_server': 'a',
388
415
              'workingtree_format': formats[0],
389
416
              '_workingtree_to_test_tree': return_parameter,
390
417
              }),
391
418
            ('WorkingTreeFormat3',
392
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
419
             {'bzrdir_format': formats[1]._matchingcontroldir,
393
420
              'transport_readonly_server': 'b',
394
421
              'transport_server': 'a',
395
422
              'workingtree_format': formats[1],
396
423
              '_workingtree_to_test_tree': return_parameter,
397
424
             }),
 
425
            ('WorkingTreeFormat6,remote',
 
426
             {'bzrdir_format': wt6_format._matchingcontroldir,
 
427
              'repo_is_remote': True,
 
428
              'transport_readonly_server': smart_readonly_server,
 
429
              'transport_server': smart_server,
 
430
              'vfs_transport_factory': mem_server,
 
431
              'workingtree_format': wt6_format,
 
432
              '_workingtree_to_test_tree': return_parameter,
 
433
             }),
398
434
            ('RevisionTree',
399
435
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
400
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
436
              'bzrdir_format': default_wt_format._matchingcontroldir,
401
437
              'transport_readonly_server': 'b',
402
438
              'transport_server': 'a',
403
439
              'workingtree_format': default_wt_format,
404
440
             }),
405
441
            ('DirStateRevisionTree,WT4',
406
442
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
407
 
              'bzrdir_format': wt4_format._matchingbzrdir,
 
443
              'bzrdir_format': wt4_format._matchingcontroldir,
408
444
              'transport_readonly_server': 'b',
409
445
              'transport_server': 'a',
410
446
              'workingtree_format': wt4_format,
411
447
             }),
412
448
            ('DirStateRevisionTree,WT5',
413
449
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
414
 
              'bzrdir_format': wt5_format._matchingbzrdir,
 
450
              'bzrdir_format': wt5_format._matchingcontroldir,
415
451
              'transport_readonly_server': 'b',
416
452
              'transport_server': 'a',
417
453
              'workingtree_format': wt5_format,
418
454
             }),
419
455
            ('PreviewTree',
420
456
             {'_workingtree_to_test_tree': preview_tree_pre,
421
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
457
              'bzrdir_format': default_wt_format._matchingcontroldir,
422
458
              'transport_readonly_server': 'b',
423
459
              'transport_server': 'a',
424
460
              'workingtree_format': default_wt_format}),
425
461
            ('PreviewTreePost',
426
462
             {'_workingtree_to_test_tree': preview_tree_post,
427
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
463
              'bzrdir_format': default_wt_format._matchingcontroldir,
428
464
              'transport_readonly_server': 'b',
429
465
              'transport_server': 'a',
430
466
              'workingtree_format': default_wt_format}),
445
481
        # unlike the TestProviderAdapter we dont want to automatically add a
446
482
        # parameterized one for WorkingTree - the optimisers will tell us what
447
483
        # ones to add.
448
 
        from bzrlib.tests.per_tree import (
 
484
        from .per_tree import (
449
485
            return_parameter,
450
 
            revision_tree_from_workingtree
451
486
            )
452
 
        from bzrlib.tests.per_intertree import (
 
487
        from .per_intertree import (
453
488
            make_scenarios,
454
489
            )
455
 
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
490
        from ..bzr.workingtree_3 import WorkingTreeFormat3
 
491
        from ..bzr.workingtree_4 import WorkingTreeFormat4
456
492
        input_test = TestInterTreeScenarios(
457
493
            "test_scenarios")
458
494
        server1 = "a"
459
495
        server2 = "b"
460
 
        format1 = WorkingTreeFormat2()
 
496
        format1 = WorkingTreeFormat4()
461
497
        format2 = WorkingTreeFormat3()
462
498
        formats = [("1", str, format1, format2, "converter1"),
463
499
            ("2", int, format2, format1, "converter2")]
465
501
        self.assertEqual(2, len(scenarios))
466
502
        expected_scenarios = [
467
503
            ("1", {
468
 
                "bzrdir_format": format1._matchingbzrdir,
 
504
                "bzrdir_format": format1._matchingcontroldir,
469
505
                "intertree_class": formats[0][1],
470
506
                "workingtree_format": formats[0][2],
471
507
                "workingtree_format_to": formats[0][3],
475
511
                "transport_readonly_server": server2,
476
512
                }),
477
513
            ("2", {
478
 
                "bzrdir_format": format2._matchingbzrdir,
 
514
                "bzrdir_format": format2._matchingcontroldir,
479
515
                "intertree_class": formats[1][1],
480
516
                "workingtree_format": formats[1][2],
481
517
                "workingtree_format_to": formats[1][3],
497
533
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
498
534
 
499
535
    def test_assertEqualStat_equal(self):
500
 
        from bzrlib.tests.test_dirstate import _FakeStat
 
536
        from .test_dirstate import _FakeStat
501
537
        self.build_tree(["foo"])
502
538
        real = os.lstat("foo")
503
539
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
509
545
        self.assertRaises(AssertionError, self.assertEqualStat,
510
546
            os.lstat("foo"), os.lstat("longname"))
511
547
 
 
548
    def test_assertPathExists(self):
 
549
        self.assertPathExists('.')
 
550
        self.build_tree(['foo/', 'foo/bar'])
 
551
        self.assertPathExists('foo/bar')
 
552
        self.assertPathDoesNotExist('foo/foo')
 
553
 
512
554
 
513
555
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
514
556
 
516
558
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
517
559
 
518
560
        This is because TestCaseWithMemoryTransport is for tests that do not
519
 
        need any disk resources: they should be hooked into bzrlib in such a
 
561
        need any disk resources: they should be hooked into breezy in such a
520
562
        way that no global settings are being changed by the test (only a
521
563
        few tests should need to do that), and having a missing dir as home is
522
564
        an effective way to ensure that this is the case.
531
573
        cwd = osutils.getcwd()
532
574
        self.assertIsSameRealPath(self.test_dir, cwd)
533
575
 
534
 
    def test_BZR_HOME_and_HOME_are_bytestrings(self):
535
 
        """The $BZR_HOME and $HOME environment variables should not be unicode.
 
576
    def test_BRZ_HOME_and_HOME_are_bytestrings(self):
 
577
        """The $BRZ_HOME and $HOME environment variables should not be unicode.
536
578
 
537
579
        See https://bugs.launchpad.net/bzr/+bug/464174
538
580
        """
539
 
        self.assertIsInstance(os.environ['BZR_HOME'], str)
 
581
        self.assertIsInstance(os.environ['BRZ_HOME'], str)
540
582
        self.assertIsInstance(os.environ['HOME'], str)
541
583
 
542
584
    def test_make_branch_and_memory_tree(self):
548
590
        tree = self.make_branch_and_memory_tree('dir')
549
591
        # Guard against regression into MemoryTransport leaking
550
592
        # files to disk instead of keeping them in memory.
551
 
        self.failIf(osutils.lexists('dir'))
 
593
        self.assertFalse(osutils.lexists('dir'))
552
594
        self.assertIsInstance(tree, memorytree.MemoryTree)
553
595
 
554
596
    def test_make_branch_and_memory_tree_with_format(self):
555
597
        """make_branch_and_memory_tree should accept a format option."""
556
598
        format = bzrdir.BzrDirMetaFormat1()
557
 
        format.repository_format = weaverepo.RepositoryFormat7()
 
599
        format.repository_format = repository.format_registry.get_default()
558
600
        tree = self.make_branch_and_memory_tree('dir', format=format)
559
601
        # Guard against regression into MemoryTransport leaking
560
602
        # files to disk instead of keeping them in memory.
561
 
        self.failIf(osutils.lexists('dir'))
 
603
        self.assertFalse(osutils.lexists('dir'))
562
604
        self.assertIsInstance(tree, memorytree.MemoryTree)
563
605
        self.assertEqual(format.repository_format.__class__,
564
606
            tree.branch.repository._format.__class__)
568
610
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
569
611
        # Guard against regression into MemoryTransport leaking
570
612
        # files to disk instead of keeping them in memory.
571
 
        self.failIf(osutils.lexists('dir'))
 
613
        self.assertFalse(osutils.lexists('dir'))
572
614
 
573
615
    def test_make_branch_builder_with_format(self):
574
616
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
575
617
        # that the format objects are used.
576
618
        format = bzrdir.BzrDirMetaFormat1()
577
 
        repo_format = weaverepo.RepositoryFormat7()
 
619
        repo_format = repository.format_registry.get_default()
578
620
        format.repository_format = repo_format
579
621
        builder = self.make_branch_builder('dir', format=format)
580
622
        the_branch = builder.get_branch()
581
623
        # Guard against regression into MemoryTransport leaking
582
624
        # files to disk instead of keeping them in memory.
583
 
        self.failIf(osutils.lexists('dir'))
 
625
        self.assertFalse(osutils.lexists('dir'))
584
626
        self.assertEqual(format.repository_format.__class__,
585
627
                         the_branch.repository._format.__class__)
586
628
        self.assertEqual(repo_format.get_format_string(),
592
634
        the_branch = builder.get_branch()
593
635
        # Guard against regression into MemoryTransport leaking
594
636
        # files to disk instead of keeping them in memory.
595
 
        self.failIf(osutils.lexists('dir'))
596
 
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
637
        self.assertFalse(osutils.lexists('dir'))
 
638
        dir_format = controldir.format_registry.make_controldir('knit')
597
639
        self.assertEqual(dir_format.repository_format.__class__,
598
640
                         the_branch.repository._format.__class__)
599
 
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
641
        self.assertEqual(b'Bazaar-NG Knit Repository Format 1',
600
642
                         self.get_transport().get_bytes(
601
643
                            'dir/.bzr/repository/format'))
602
644
 
603
645
    def test_dangling_locks_cause_failures(self):
604
646
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
605
647
            def test_function(self):
606
 
                t = self.get_transport('.')
 
648
                t = self.get_transport_from_path('.')
607
649
                l = lockdir.LockDir(t, 'lock')
608
650
                l.create()
609
651
                l.attempt_lock()
610
652
        test = TestDanglingLock('test_function')
611
653
        result = test.run()
 
654
        total_failures = result.errors + result.failures
612
655
        if self._lock_check_thorough:
613
 
            self.assertEqual(1, len(result.errors))
 
656
            self.assertEqual(1, len(total_failures))
614
657
        else:
615
658
            # When _lock_check_thorough is disabled, then we don't trigger a
616
659
            # failure
617
 
            self.assertEqual(0, len(result.errors))
 
660
            self.assertEqual(0, len(total_failures))
618
661
 
619
662
 
620
663
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
621
664
    """Tests for the convenience functions TestCaseWithTransport introduces."""
622
665
 
623
666
    def test_get_readonly_url_none(self):
624
 
        from bzrlib.transport import get_transport
625
 
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
667
        from ..transport.readonly import ReadonlyTransportDecorator
626
668
        self.vfs_transport_factory = memory.MemoryServer
627
669
        self.transport_readonly_server = None
628
670
        # calling get_readonly_transport() constructs a decorator on the url
629
671
        # for the server
630
672
        url = self.get_readonly_url()
631
673
        url2 = self.get_readonly_url('foo/bar')
632
 
        t = get_transport(url)
633
 
        t2 = get_transport(url2)
634
 
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
635
 
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
674
        t = transport.get_transport_from_url(url)
 
675
        t2 = transport.get_transport_from_url(url2)
 
676
        self.assertIsInstance(t, ReadonlyTransportDecorator)
 
677
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
636
678
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
637
679
 
638
680
    def test_get_readonly_url_http(self):
639
 
        from bzrlib.tests.http_server import HttpServer
640
 
        from bzrlib.transport import get_transport
641
 
        from bzrlib.transport.http import HttpTransportBase
 
681
        from .http_server import HttpServer
 
682
        from ..transport.http import HttpTransport
642
683
        self.transport_server = test_server.LocalURLServer
643
684
        self.transport_readonly_server = HttpServer
644
685
        # calling get_readonly_transport() gives us a HTTP server instance.
645
686
        url = self.get_readonly_url()
646
687
        url2 = self.get_readonly_url('foo/bar')
647
688
        # the transport returned may be any HttpTransportBase subclass
648
 
        t = get_transport(url)
649
 
        t2 = get_transport(url2)
650
 
        self.failUnless(isinstance(t, HttpTransportBase))
651
 
        self.failUnless(isinstance(t2, HttpTransportBase))
 
689
        t = transport.get_transport_from_url(url)
 
690
        t2 = transport.get_transport_from_url(url2)
 
691
        self.assertIsInstance(t, HttpTransport)
 
692
        self.assertIsInstance(t2, HttpTransport)
652
693
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
653
694
 
654
695
    def test_is_directory(self):
662
703
    def test_make_branch_builder(self):
663
704
        builder = self.make_branch_builder('dir')
664
705
        rev_id = builder.build_commit()
665
 
        self.failUnlessExists('dir')
666
 
        a_dir = bzrdir.BzrDir.open('dir')
 
706
        self.assertPathExists('dir')
 
707
        a_dir = controldir.ControlDir.open('dir')
667
708
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
668
709
        a_branch = a_dir.open_branch()
669
710
        builder_branch = builder.get_branch()
678
719
        super(TestTestCaseTransports, self).setUp()
679
720
        self.vfs_transport_factory = memory.MemoryServer
680
721
 
681
 
    def test_make_bzrdir_preserves_transport(self):
 
722
    def test_make_controldir_preserves_transport(self):
682
723
        t = self.get_transport()
683
 
        result_bzrdir = self.make_bzrdir('subdir')
 
724
        result_bzrdir = self.make_controldir('subdir')
684
725
        self.assertIsInstance(result_bzrdir.transport,
685
726
                              memory.MemoryTransport)
686
727
        # should not be on disk, should only be in memory
687
 
        self.failIfExists('subdir')
 
728
        self.assertPathDoesNotExist('subdir')
688
729
 
689
730
 
690
731
class TestChrootedTest(tests.ChrootedTestCase):
691
732
 
692
733
    def test_root_is_root(self):
693
 
        from bzrlib.transport import get_transport
694
 
        t = get_transport(self.get_readonly_url())
 
734
        t = transport.get_transport_from_url(self.get_readonly_url())
695
735
        url = t.base
696
736
        self.assertEqual(url, t.clone('..').base)
697
737
 
699
739
class TestProfileResult(tests.TestCase):
700
740
 
701
741
    def test_profiles_tests(self):
702
 
        self.requireFeature(test_lsprof.LSProfFeature)
703
 
        terminal = testtools.tests.helpers.ExtendedTestResult()
 
742
        self.requireFeature(features.lsprof_feature)
 
743
        terminal = testtools.testresult.doubles.ExtendedTestResult()
704
744
        result = tests.ProfileResult(terminal)
705
745
        class Sample(tests.TestCase):
706
746
            def a(self):
719
759
class TestTestResult(tests.TestCase):
720
760
 
721
761
    def check_timing(self, test_case, expected_re):
722
 
        result = bzrlib.tests.TextTestResult(self._log_file,
723
 
                descriptions=0,
724
 
                verbosity=1,
725
 
                )
726
 
        capture = testtools.tests.helpers.ExtendedTestResult()
 
762
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
763
        capture = testtools.testresult.doubles.ExtendedTestResult()
727
764
        test_case.run(MultiTestResult(result, capture))
728
765
        run_case = capture._events[0][1]
729
766
        timed_string = result._testTimeString(run_case)
743
780
                          r"^ +[0-9]+ms\*$")
744
781
 
745
782
    def test_unittest_reporting_unittest_class(self):
746
 
        # getting the time from a non-bzrlib test works ok
 
783
        # getting the time from a non-breezy test works ok
747
784
        class ShortDelayTestCase(unittest.TestCase):
748
785
            def test_short_delay(self):
749
786
                time.sleep(0.003)
750
787
        self.check_timing(ShortDelayTestCase('test_short_delay'),
751
788
                          r"^ +[0-9]+ms$")
752
789
 
753
 
    def _patch_get_bzr_source_tree(self):
754
 
        # Reading from the actual source tree breaks isolation, but we don't
755
 
        # want to assume that thats *all* that would happen.
756
 
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
757
 
 
758
 
    def test_assigned_benchmark_file_stores_date(self):
759
 
        self._patch_get_bzr_source_tree()
760
 
        output = StringIO()
761
 
        result = bzrlib.tests.TextTestResult(self._log_file,
762
 
                                        descriptions=0,
763
 
                                        verbosity=1,
764
 
                                        bench_history=output
765
 
                                        )
766
 
        output_string = output.getvalue()
767
 
        # if you are wondering about the regexp please read the comment in
768
 
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
769
 
        # XXX: what comment?  -- Andrew Bennetts
770
 
        self.assertContainsRe(output_string, "--date [0-9.]+")
771
 
 
772
 
    def test_benchhistory_records_test_times(self):
773
 
        self._patch_get_bzr_source_tree()
774
 
        result_stream = StringIO()
775
 
        result = bzrlib.tests.TextTestResult(
776
 
            self._log_file,
777
 
            descriptions=0,
778
 
            verbosity=1,
779
 
            bench_history=result_stream
780
 
            )
781
 
 
782
 
        # we want profile a call and check that its test duration is recorded
783
 
        # make a new test instance that when run will generate a benchmark
784
 
        example_test_case = TestTestResult("_time_hello_world_encoding")
785
 
        # execute the test, which should succeed and record times
786
 
        example_test_case.run(result)
787
 
        lines = result_stream.getvalue().splitlines()
788
 
        self.assertEqual(2, len(lines))
789
 
        self.assertContainsRe(lines[1],
790
 
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
791
 
            "._time_hello_world_encoding")
792
 
 
793
790
    def _time_hello_world_encoding(self):
794
791
        """Profile two sleep calls
795
792
 
796
793
        This is used to exercise the test framework.
797
794
        """
798
 
        self.time(unicode, 'hello', errors='replace')
799
 
        self.time(unicode, 'world', errors='replace')
 
795
        self.time(text_type, b'hello', errors='replace')
 
796
        self.time(text_type, b'world', errors='replace')
800
797
 
801
798
    def test_lsprofiling(self):
802
799
        """Verbose test result prints lsprof statistics from test cases."""
803
 
        self.requireFeature(test_lsprof.LSProfFeature)
 
800
        self.requireFeature(features.lsprof_feature)
804
801
        result_stream = StringIO()
805
 
        result = bzrlib.tests.VerboseTestResult(
806
 
            unittest._WritelnDecorator(result_stream),
 
802
        result = breezy.tests.VerboseTestResult(
 
803
            result_stream,
807
804
            descriptions=0,
808
805
            verbosity=2,
809
806
            )
826
823
        # and then repeated but with 'world', rather than 'hello'.
827
824
        # this should appear in the output stream of our test result.
828
825
        output = result_stream.getvalue()
829
 
        self.assertContainsRe(output,
830
 
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
826
        if PY3:
 
827
            self.assertContainsRe(output,
 
828
                r"LSProf output for <class 'str'>\(\(b'hello',\), {'errors': 'replace'}\)")
 
829
            self.assertContainsRe(output,
 
830
                r"LSProf output for <class 'str'>\(\(b'world',\), {'errors': 'replace'}\)")
 
831
        else:
 
832
            self.assertContainsRe(output,
 
833
                r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
834
            self.assertContainsRe(output,
 
835
                r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
831
836
        self.assertContainsRe(output,
832
837
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
833
838
        self.assertContainsRe(output,
834
839
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
835
 
        self.assertContainsRe(output,
836
 
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
840
 
 
841
    def test_uses_time_from_testtools(self):
 
842
        """Test case timings in verbose results should use testtools times"""
 
843
        import datetime
 
844
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
 
845
            def startTest(self, test):
 
846
                self.time(datetime.datetime.utcfromtimestamp(1.145))
 
847
                super(TimeAddedVerboseTestResult, self).startTest(test)
 
848
            def addSuccess(self, test):
 
849
                self.time(datetime.datetime.utcfromtimestamp(51.147))
 
850
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
 
851
            def report_tests_starting(self): pass
 
852
        sio = StringIO()
 
853
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
 
854
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
837
855
 
838
856
    def test_known_failure(self):
839
 
        """A KnownFailure being raised should trigger several result actions."""
 
857
        """Using knownFailure should trigger several result actions."""
840
858
        class InstrumentedTestResult(tests.ExtendedTestResult):
841
859
            def stopTestRun(self): pass
842
 
            def startTests(self): pass
843
 
            def report_test_start(self, test): pass
 
860
            def report_tests_starting(self): pass
844
861
            def report_known_failure(self, test, err=None, details=None):
845
862
                self._call = test, 'known failure'
846
863
        result = InstrumentedTestResult(None, None, None, None)
847
864
        class Test(tests.TestCase):
848
865
            def test_function(self):
849
 
                raise tests.KnownFailure('failed!')
 
866
                self.knownFailure('failed!')
850
867
        test = Test("test_function")
851
868
        test.run(result)
852
869
        # it should invoke 'report_known_failure'.
863
880
    def test_verbose_report_known_failure(self):
864
881
        # verbose test output formatting
865
882
        result_stream = StringIO()
866
 
        result = bzrlib.tests.VerboseTestResult(
867
 
            unittest._WritelnDecorator(result_stream),
 
883
        result = breezy.tests.VerboseTestResult(
 
884
            result_stream,
868
885
            descriptions=0,
869
886
            verbosity=2,
870
887
            )
871
 
        test = self.get_passing_test()
872
 
        result.startTest(test)
873
 
        prefix = len(result_stream.getvalue())
874
 
        # the err parameter has the shape:
875
 
        # (class, exception object, traceback)
876
 
        # KnownFailures dont get their tracebacks shown though, so we
877
 
        # can skip that.
878
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
879
 
        result.report_known_failure(test, err)
880
 
        output = result_stream.getvalue()[prefix:]
881
 
        lines = output.splitlines()
882
 
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
883
 
        self.assertEqual(lines[1], '    foo')
884
 
        self.assertEqual(2, len(lines))
 
888
        _get_test("test_xfail").run(result)
 
889
        self.assertContainsRe(result_stream.getvalue(),
 
890
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
 
891
            "\\s*(?:Text attachment: )?reason"
 
892
            "(?:\n-+\n|: {{{)"
 
893
            "this_fails"
 
894
            "(?:\n-+\n|}}}\n)")
885
895
 
886
896
    def get_passing_test(self):
887
897
        """Return a test object that can't be run usefully."""
893
903
        """Test the behaviour of invoking addNotSupported."""
894
904
        class InstrumentedTestResult(tests.ExtendedTestResult):
895
905
            def stopTestRun(self): pass
896
 
            def startTests(self): pass
897
 
            def report_test_start(self, test): pass
 
906
            def report_tests_starting(self): pass
898
907
            def report_unsupported(self, test, feature):
899
908
                self._call = test, feature
900
909
        result = InstrumentedTestResult(None, None, None, None)
901
910
        test = SampleTestCase('_test_pass')
902
 
        feature = tests.Feature()
 
911
        feature = features.Feature()
903
912
        result.startTest(test)
904
913
        result.addNotSupported(test, feature)
905
914
        # it should invoke 'report_unsupported'.
918
927
    def test_verbose_report_unsupported(self):
919
928
        # verbose test output formatting
920
929
        result_stream = StringIO()
921
 
        result = bzrlib.tests.VerboseTestResult(
922
 
            unittest._WritelnDecorator(result_stream),
 
930
        result = breezy.tests.VerboseTestResult(
 
931
            result_stream,
923
932
            descriptions=0,
924
933
            verbosity=2,
925
934
            )
926
935
        test = self.get_passing_test()
927
 
        feature = tests.Feature()
 
936
        feature = features.Feature()
928
937
        result.startTest(test)
929
938
        prefix = len(result_stream.getvalue())
930
939
        result.report_unsupported(test, feature)
939
948
        """An UnavailableFeature being raised should invoke addNotSupported."""
940
949
        class InstrumentedTestResult(tests.ExtendedTestResult):
941
950
            def stopTestRun(self): pass
942
 
            def startTests(self): pass
943
 
            def report_test_start(self, test): pass
 
951
            def report_tests_starting(self): pass
944
952
            def addNotSupported(self, test, feature):
945
953
                self._call = test, feature
946
954
        result = InstrumentedTestResult(None, None, None, None)
947
 
        feature = tests.Feature()
 
955
        feature = features.Feature()
948
956
        class Test(tests.TestCase):
949
957
            def test_function(self):
950
958
                raise tests.UnavailableFeature(feature)
958
966
        self.assertEqual(0, result.error_count)
959
967
 
960
968
    def test_strict_with_unsupported_feature(self):
961
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
962
 
                                             verbosity=1)
 
969
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
963
970
        test = self.get_passing_test()
964
971
        feature = "Unsupported Feature"
965
972
        result.addNotSupported(test, feature)
967
974
        self.assertEqual(None, result._extractBenchmarkTime(test))
968
975
 
969
976
    def test_strict_with_known_failure(self):
970
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
971
 
                                             verbosity=1)
972
 
        test = self.get_passing_test()
973
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
974
 
        result.addExpectedFailure(test, err)
 
977
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
978
        test = _get_test("test_xfail")
 
979
        test.run(result)
975
980
        self.assertFalse(result.wasStrictlySuccessful())
976
981
        self.assertEqual(None, result._extractBenchmarkTime(test))
977
982
 
978
983
    def test_strict_with_success(self):
979
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
980
 
                                             verbosity=1)
 
984
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
981
985
        test = self.get_passing_test()
982
986
        result.addSuccess(test)
983
987
        self.assertTrue(result.wasStrictlySuccessful())
988
992
        class InstrumentedTestResult(tests.ExtendedTestResult):
989
993
            calls = 0
990
994
            def startTests(self): self.calls += 1
991
 
            def report_test_start(self, test): pass
992
995
        result = InstrumentedTestResult(None, None, None, None)
993
996
        def test_function():
994
997
            pass
995
998
        test = unittest.FunctionTestCase(test_function)
996
999
        test.run(result)
997
 
        self.assertEquals(1, result.calls)
998
 
 
999
 
 
1000
 
class TestUnicodeFilenameFeature(tests.TestCase):
1001
 
 
1002
 
    def test_probe_passes(self):
1003
 
        """UnicodeFilenameFeature._probe passes."""
1004
 
        # We can't test much more than that because the behaviour depends
1005
 
        # on the platform.
1006
 
        tests.UnicodeFilenameFeature._probe()
 
1000
        self.assertEqual(1, result.calls)
 
1001
 
 
1002
    def test_startTests_only_once(self):
 
1003
        """With multiple tests startTests should still only be called once"""
 
1004
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
1005
            calls = 0
 
1006
            def startTests(self): self.calls += 1
 
1007
        result = InstrumentedTestResult(None, None, None, None)
 
1008
        suite = unittest.TestSuite([
 
1009
            unittest.FunctionTestCase(lambda: None),
 
1010
            unittest.FunctionTestCase(lambda: None)])
 
1011
        suite.run(result)
 
1012
        self.assertEqual(1, result.calls)
 
1013
        self.assertEqual(2, result.count)
1007
1014
 
1008
1015
 
1009
1016
class TestRunner(tests.TestCase):
1018
1025
        TestCaseInTempDir.TEST_ROOT
1019
1026
 
1020
1027
        There should be no tests in this file that use
1021
 
        bzrlib.tests.TextTestRunner without using this convenience method,
 
1028
        breezy.tests.TextTestRunner without using this convenience method,
1022
1029
        because of our use of global state.
1023
1030
        """
1024
1031
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1025
 
        old_leak = tests.TestCase._first_thread_leaker_id
1026
1032
        try:
1027
1033
            tests.TestCaseInTempDir.TEST_ROOT = None
1028
 
            tests.TestCase._first_thread_leaker_id = None
1029
1034
            return testrunner.run(test)
1030
1035
        finally:
1031
1036
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1032
 
            tests.TestCase._first_thread_leaker_id = old_leak
1033
1037
 
1034
1038
    def test_known_failure_failed_run(self):
1035
1039
        # run a test that generates a known failure which should be printed in
1040
1044
        test = unittest.TestSuite()
1041
1045
        test.addTest(Test("known_failure_test"))
1042
1046
        def failing_test():
1043
 
            self.fail('foo')
 
1047
            raise AssertionError('foo')
1044
1048
        test.addTest(unittest.FunctionTestCase(failing_test))
1045
1049
        stream = StringIO()
1046
1050
        runner = tests.TextTestRunner(stream=stream)
1047
1051
        result = self.run_test_runner(runner, test)
1048
1052
        lines = stream.getvalue().splitlines()
1049
1053
        self.assertContainsRe(stream.getvalue(),
1050
 
            '(?sm)^bzr selftest.*$'
 
1054
            '(?sm)^brz selftest.*$'
1051
1055
            '.*'
1052
1056
            '^======================================================================\n'
1053
1057
            '^FAIL: failing_test\n'
1054
1058
            '^----------------------------------------------------------------------\n'
1055
1059
            'Traceback \\(most recent call last\\):\n'
1056
1060
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1057
 
            '    self.fail\\(\'foo\'\\)\n'
 
1061
            '    raise AssertionError\\(\'foo\'\\)\n'
1058
1062
            '.*'
1059
1063
            '^----------------------------------------------------------------------\n'
1060
1064
            '.*'
1066
1070
        # the final output.
1067
1071
        class Test(tests.TestCase):
1068
1072
            def known_failure_test(self):
1069
 
                self.expectFailure('failed', self.assertTrue, False)
 
1073
                self.knownFailure("Never works...")
1070
1074
        test = Test("known_failure_test")
1071
1075
        stream = StringIO()
1072
1076
        runner = tests.TextTestRunner(stream=stream)
1078
1082
            '\n'
1079
1083
            'OK \\(known_failures=1\\)\n')
1080
1084
 
 
1085
    def test_unexpected_success_bad(self):
 
1086
        class Test(tests.TestCase):
 
1087
            def test_truth(self):
 
1088
                self.expectFailure("No absolute truth", self.assertTrue, True)
 
1089
        runner = tests.TextTestRunner(stream=StringIO())
 
1090
        result = self.run_test_runner(runner, Test("test_truth"))
 
1091
        self.assertContainsRe(runner.stream.getvalue(),
 
1092
            "=+\n"
 
1093
            "FAIL: \\S+\\.test_truth\n"
 
1094
            "-+\n"
 
1095
            "(?:.*\n)*"
 
1096
            "\\s*(?:Text attachment: )?reason"
 
1097
            "(?:\n-+\n|: {{{)"
 
1098
            "No absolute truth"
 
1099
            "(?:\n-+\n|}}}\n)"
 
1100
            "(?:.*\n)*"
 
1101
            "-+\n"
 
1102
            "Ran 1 test in .*\n"
 
1103
            "\n"
 
1104
            "FAILED \\(failures=1\\)\n\\Z")
 
1105
 
1081
1106
    def test_result_decorator(self):
1082
1107
        # decorate results
1083
1108
        calls = []
1084
 
        class LoggingDecorator(tests.ForwardingResult):
 
1109
        class LoggingDecorator(ExtendedToOriginalDecorator):
1085
1110
            def startTest(self, test):
1086
 
                tests.ForwardingResult.startTest(self, test)
 
1111
                ExtendedToOriginalDecorator.startTest(self, test)
1087
1112
                calls.append('start')
1088
1113
        test = unittest.FunctionTestCase(lambda:None)
1089
1114
        stream = StringIO()
1099
1124
        class SkippingTest(tests.TestCase):
1100
1125
            def skipping_test(self):
1101
1126
                raise tests.TestSkipped('test intentionally skipped')
1102
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1127
        runner = tests.TextTestRunner(stream=StringIO())
1103
1128
        test = SkippingTest("skipping_test")
1104
1129
        result = self.run_test_runner(runner, test)
1105
1130
        self.assertTrue(result.wasSuccessful())
1119
1144
            def cleanup(self):
1120
1145
                calls.append('cleanup')
1121
1146
 
1122
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1147
        runner = tests.TextTestRunner(stream=StringIO())
1123
1148
        test = SkippedSetupTest('test_skip')
1124
1149
        result = self.run_test_runner(runner, test)
1125
1150
        self.assertTrue(result.wasSuccessful())
1131
1156
        class SkippedTest(tests.TestCase):
1132
1157
 
1133
1158
            def setUp(self):
1134
 
                tests.TestCase.setUp(self)
 
1159
                super(SkippedTest, self).setUp()
1135
1160
                calls.append('setUp')
1136
1161
                self.addCleanup(self.cleanup)
1137
1162
 
1141
1166
            def cleanup(self):
1142
1167
                calls.append('cleanup')
1143
1168
 
1144
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1169
        runner = tests.TextTestRunner(stream=StringIO())
1145
1170
        test = SkippedTest('test_skip')
1146
1171
        result = self.run_test_runner(runner, test)
1147
1172
        self.assertTrue(result.wasSuccessful())
1157
1182
        runner = tests.TextTestRunner(stream=out, verbosity=2)
1158
1183
        test = Test("not_applicable_test")
1159
1184
        result = self.run_test_runner(runner, test)
1160
 
        self._log_file.write(out.getvalue())
 
1185
        self.log(out.getvalue())
1161
1186
        self.assertTrue(result.wasSuccessful())
1162
1187
        self.assertTrue(result.wasStrictlySuccessful())
1163
1188
        self.assertContainsRe(out.getvalue(),
1164
 
                r'(?m)not_applicable_test   * N/A')
 
1189
                r'(?m)not_applicable_test  * N/A')
1165
1190
        self.assertContainsRe(out.getvalue(),
1166
1191
                r'(?m)^    this test never runs')
1167
1192
 
1168
1193
    def test_unsupported_features_listed(self):
1169
1194
        """When unsupported features are encountered they are detailed."""
1170
 
        class Feature1(tests.Feature):
 
1195
        class Feature1(features.Feature):
1171
1196
            def _probe(self): return False
1172
 
        class Feature2(tests.Feature):
 
1197
        class Feature2(features.Feature):
1173
1198
            def _probe(self): return False
1174
1199
        # create sample tests
1175
1200
        test1 = SampleTestCase('_test_pass')
1190
1215
            ],
1191
1216
            lines[-3:])
1192
1217
 
1193
 
    def _patch_get_bzr_source_tree(self):
1194
 
        # Reading from the actual source tree breaks isolation, but we don't
1195
 
        # want to assume that thats *all* that would happen.
1196
 
        self._get_source_tree_calls = []
1197
 
        def new_get():
1198
 
            self._get_source_tree_calls.append("called")
1199
 
            return None
1200
 
        self.overrideAttr(bzrlib.version, '_get_bzr_source_tree',  new_get)
1201
 
 
1202
 
    def test_bench_history(self):
1203
 
        # tests that the running the benchmark passes bench_history into
1204
 
        # the test result object. We can tell that happens if
1205
 
        # _get_bzr_source_tree is called.
1206
 
        self._patch_get_bzr_source_tree()
1207
 
        test = TestRunner('dummy_test')
1208
 
        output = StringIO()
1209
 
        runner = tests.TextTestRunner(stream=self._log_file,
1210
 
                                      bench_history=output)
1211
 
        result = self.run_test_runner(runner, test)
1212
 
        output_string = output.getvalue()
1213
 
        self.assertContainsRe(output_string, "--date [0-9.]+")
1214
 
        self.assertLength(1, self._get_source_tree_calls)
 
1218
    def test_verbose_test_count(self):
 
1219
        """A verbose test run reports the right test count at the start"""
 
1220
        suite = TestUtil.TestSuite([
 
1221
            unittest.FunctionTestCase(lambda:None),
 
1222
            unittest.FunctionTestCase(lambda:None)])
 
1223
        self.assertEqual(suite.countTestCases(), 2)
 
1224
        stream = StringIO()
 
1225
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
 
1226
        # Need to use the CountingDecorator as that's what sets num_tests
 
1227
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
 
1228
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
1215
1229
 
1216
1230
    def test_startTestRun(self):
1217
1231
        """run should call result.startTestRun()"""
1218
1232
        calls = []
1219
 
        class LoggingDecorator(tests.ForwardingResult):
 
1233
        class LoggingDecorator(ExtendedToOriginalDecorator):
1220
1234
            def startTestRun(self):
1221
 
                tests.ForwardingResult.startTestRun(self)
 
1235
                ExtendedToOriginalDecorator.startTestRun(self)
1222
1236
                calls.append('startTestRun')
1223
1237
        test = unittest.FunctionTestCase(lambda:None)
1224
1238
        stream = StringIO()
1230
1244
    def test_stopTestRun(self):
1231
1245
        """run should call result.stopTestRun()"""
1232
1246
        calls = []
1233
 
        class LoggingDecorator(tests.ForwardingResult):
 
1247
        class LoggingDecorator(ExtendedToOriginalDecorator):
1234
1248
            def stopTestRun(self):
1235
 
                tests.ForwardingResult.stopTestRun(self)
 
1249
                ExtendedToOriginalDecorator.stopTestRun(self)
1236
1250
                calls.append('stopTestRun')
1237
1251
        test = unittest.FunctionTestCase(lambda:None)
1238
1252
        stream = StringIO()
1241
1255
        result = self.run_test_runner(runner, test)
1242
1256
        self.assertLength(1, calls)
1243
1257
 
 
1258
    def test_unicode_test_output_on_ascii_stream(self):
 
1259
        """Showing results should always succeed even on an ascii console"""
 
1260
        class FailureWithUnicode(tests.TestCase):
 
1261
            def test_log_unicode(self):
 
1262
                self.log(u"\u2606")
 
1263
                self.fail("Now print that log!")
 
1264
        if PY3:
 
1265
            bio = BytesIO()
 
1266
            out = TextIOWrapper(bio, 'ascii', 'backslashreplace')
 
1267
        else:
 
1268
            bio = out = StringIO()
 
1269
        self.overrideAttr(osutils, "get_terminal_encoding",
 
1270
            lambda trace=False: "ascii")
 
1271
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
 
1272
            FailureWithUnicode("test_log_unicode"))
 
1273
        out.flush()
 
1274
        self.assertContainsRe(bio.getvalue(),
 
1275
            b"(?:Text attachment: )?log"
 
1276
            b"(?:\n-+\n|: {{{)"
 
1277
            b"\\d+\\.\\d+  \\\\u2606"
 
1278
            b"(?:\n-+\n|}}}\n)")
 
1279
 
1244
1280
 
1245
1281
class SampleTestCase(tests.TestCase):
1246
1282
 
1252
1288
 
1253
1289
 
1254
1290
class TestTestCase(tests.TestCase):
1255
 
    """Tests that test the core bzrlib TestCase."""
 
1291
    """Tests that test the core breezy TestCase."""
1256
1292
 
1257
1293
    def test_assertLength_matches_empty(self):
1258
1294
        a_list = []
1298
1334
        self.assertEqual(1, result.testsRun)
1299
1335
 
1300
1336
    def test_debug_flags_sanitised(self):
1301
 
        """The bzrlib debug flags should be sanitised by setUp."""
 
1337
        """The breezy debug flags should be sanitised by setUp."""
1302
1338
        if 'allow_debug' in tests.selftest_debug_flags:
1303
1339
            raise tests.TestNotApplicable(
1304
1340
                '-Eallow_debug option prevents debug flag sanitisation')
1308
1344
        flags = set()
1309
1345
        if self._lock_check_thorough:
1310
1346
            flags.add('strict_locks')
1311
 
        self.assertEqual(flags, bzrlib.debug.debug_flags)
 
1347
        self.assertEqual(flags, breezy.debug.debug_flags)
1312
1348
 
1313
1349
    def change_selftest_debug_flags(self, new_flags):
1314
1350
        self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
1315
1351
 
1316
1352
    def test_allow_debug_flag(self):
1317
 
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1353
        """The -Eallow_debug flag prevents breezy.debug.debug_flags from being
1318
1354
        sanitised (i.e. cleared) before running a test.
1319
1355
        """
1320
 
        self.change_selftest_debug_flags(set(['allow_debug']))
1321
 
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1356
        self.change_selftest_debug_flags({'allow_debug'})
 
1357
        breezy.debug.debug_flags = {'a-flag'}
1322
1358
        class TestThatRecordsFlags(tests.TestCase):
1323
1359
            def test_foo(nested_self):
1324
 
                self.flags = set(bzrlib.debug.debug_flags)
 
1360
                self.flags = set(breezy.debug.debug_flags)
1325
1361
        test = TestThatRecordsFlags('test_foo')
1326
1362
        test.run(self.make_test_result())
1327
 
        flags = set(['a-flag'])
 
1363
        flags = {'a-flag'}
1328
1364
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
1329
1365
            flags.add('strict_locks')
1330
1366
        self.assertEqual(flags, self.flags)
1333
1369
        """The -Edisable_lock_checks flag disables thorough checks."""
1334
1370
        class TestThatRecordsFlags(tests.TestCase):
1335
1371
            def test_foo(nested_self):
1336
 
                self.flags = set(bzrlib.debug.debug_flags)
 
1372
                self.flags = set(breezy.debug.debug_flags)
1337
1373
                self.test_lock_check_thorough = nested_self._lock_check_thorough
1338
1374
        self.change_selftest_debug_flags(set())
1339
1375
        test = TestThatRecordsFlags('test_foo')
1341
1377
        # By default we do strict lock checking and thorough lock/unlock
1342
1378
        # tracking.
1343
1379
        self.assertTrue(self.test_lock_check_thorough)
1344
 
        self.assertEqual(set(['strict_locks']), self.flags)
 
1380
        self.assertEqual({'strict_locks'}, self.flags)
1345
1381
        # Now set the disable_lock_checks flag, and show that this changed.
1346
 
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
 
1382
        self.change_selftest_debug_flags({'disable_lock_checks'})
1347
1383
        test = TestThatRecordsFlags('test_foo')
1348
1384
        test.run(self.make_test_result())
1349
1385
        self.assertFalse(self.test_lock_check_thorough)
1352
1388
    def test_this_fails_strict_lock_check(self):
1353
1389
        class TestThatRecordsFlags(tests.TestCase):
1354
1390
            def test_foo(nested_self):
1355
 
                self.flags1 = set(bzrlib.debug.debug_flags)
 
1391
                self.flags1 = set(breezy.debug.debug_flags)
1356
1392
                self.thisFailsStrictLockCheck()
1357
 
                self.flags2 = set(bzrlib.debug.debug_flags)
 
1393
                self.flags2 = set(breezy.debug.debug_flags)
1358
1394
        # Make sure lock checking is active
1359
1395
        self.change_selftest_debug_flags(set())
1360
1396
        test = TestThatRecordsFlags('test_foo')
1361
1397
        test.run(self.make_test_result())
1362
 
        self.assertEqual(set(['strict_locks']), self.flags1)
 
1398
        self.assertEqual({'strict_locks'}, self.flags1)
1363
1399
        self.assertEqual(set(), self.flags2)
1364
1400
 
1365
1401
    def test_debug_flags_restored(self):
1366
 
        """The bzrlib debug flags should be restored to their original state
 
1402
        """The breezy debug flags should be restored to their original state
1367
1403
        after the test was run, even if allow_debug is set.
1368
1404
        """
1369
 
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1405
        self.change_selftest_debug_flags({'allow_debug'})
1370
1406
        # Now run a test that modifies debug.debug_flags.
1371
 
        bzrlib.debug.debug_flags = set(['original-state'])
 
1407
        breezy.debug.debug_flags = {'original-state'}
1372
1408
        class TestThatModifiesFlags(tests.TestCase):
1373
1409
            def test_foo(self):
1374
 
                bzrlib.debug.debug_flags = set(['modified'])
 
1410
                breezy.debug.debug_flags = {'modified'}
1375
1411
        test = TestThatModifiesFlags('test_foo')
1376
1412
        test.run(self.make_test_result())
1377
 
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1413
        self.assertEqual({'original-state'}, breezy.debug.debug_flags)
1378
1414
 
1379
1415
    def make_test_result(self):
1380
 
        """Get a test result that writes to the test log file."""
1381
 
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
 
1416
        """Get a test result that writes to a StringIO."""
 
1417
        return tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
1382
1418
 
1383
1419
    def inner_test(self):
1384
1420
        # the inner child test
1405
1441
        # one child, we should instead see the bad result inside our test with
1406
1442
        # the two children.
1407
1443
        # the outer child test
1408
 
        original_trace = bzrlib.trace._trace_file
 
1444
        original_trace = breezy.trace._trace_file
1409
1445
        outer_test = TestTestCase("outer_child")
1410
1446
        result = self.make_test_result()
1411
1447
        outer_test.run(result)
1412
 
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1448
        self.assertEqual(original_trace, breezy.trace._trace_file)
1413
1449
 
1414
1450
    def method_that_times_a_bit_twice(self):
1415
1451
        # call self.time twice to ensure it aggregates
1420
1456
        """Test that the TestCase.time() method accumulates a benchmark time."""
1421
1457
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1422
1458
        output_stream = StringIO()
1423
 
        result = bzrlib.tests.VerboseTestResult(
1424
 
            unittest._WritelnDecorator(output_stream),
 
1459
        result = breezy.tests.VerboseTestResult(
 
1460
            output_stream,
1425
1461
            descriptions=0,
1426
1462
            verbosity=2)
1427
1463
        sample_test.run(result)
1430
1466
            r"\d+ms\*\n$")
1431
1467
 
1432
1468
    def test_hooks_sanitised(self):
1433
 
        """The bzrlib hooks should be sanitised by setUp."""
 
1469
        """The breezy hooks should be sanitised by setUp."""
1434
1470
        # Note this test won't fail with hooks that the core library doesn't
1435
1471
        # use - but it trigger with a plugin that adds hooks, so its still a
1436
1472
        # useful warning in that case.
1437
 
        self.assertEqual(bzrlib.branch.BranchHooks(),
1438
 
            bzrlib.branch.Branch.hooks)
1439
 
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1440
 
            bzrlib.smart.server.SmartTCPServer.hooks)
1441
 
        self.assertEqual(bzrlib.commands.CommandHooks(),
1442
 
            bzrlib.commands.Command.hooks)
 
1473
        self.assertEqual(breezy.branch.BranchHooks(), breezy.branch.Branch.hooks)
 
1474
        self.assertEqual(
 
1475
            breezy.bzr.smart.server.SmartServerHooks(),
 
1476
            breezy.bzr.smart.server.SmartTCPServer.hooks)
 
1477
        self.assertEqual(
 
1478
            breezy.commands.CommandHooks(), breezy.commands.Command.hooks)
1443
1479
 
1444
1480
    def test__gather_lsprof_in_benchmarks(self):
1445
1481
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1446
1482
 
1447
1483
        Each self.time() call is individually and separately profiled.
1448
1484
        """
1449
 
        self.requireFeature(test_lsprof.LSProfFeature)
 
1485
        self.requireFeature(features.lsprof_feature)
1450
1486
        # overrides the class member with an instance member so no cleanup
1451
1487
        # needed.
1452
1488
        self._gather_lsprof_in_benchmarks = True
1455
1491
        self.assertEqual(2, len(self._benchcalls))
1456
1492
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1457
1493
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1458
 
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1459
 
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1494
        self.assertIsInstance(self._benchcalls[0][1], breezy.lsprof.Stats)
 
1495
        self.assertIsInstance(self._benchcalls[1][1], breezy.lsprof.Stats)
1460
1496
        del self._benchcalls[:]
1461
1497
 
1462
1498
    def test_knownFailure(self):
1471
1507
        transport_server = memory.MemoryServer()
1472
1508
        transport_server.start_server()
1473
1509
        self.addCleanup(transport_server.stop_server)
1474
 
        t = transport.get_transport(transport_server.get_url())
1475
 
        bzrdir.BzrDir.create(t.base)
 
1510
        t = transport.get_transport_from_url(transport_server.get_url())
 
1511
        controldir.ControlDir.create(t.base)
1476
1512
        self.assertRaises(errors.BzrError,
1477
 
            bzrdir.BzrDir.open_from_transport, t)
 
1513
            controldir.ControlDir.open_from_transport, t)
1478
1514
        # But if we declare this as safe, we can open the bzrdir.
1479
1515
        self.permit_url(t.base)
1480
1516
        self._bzr_selftest_roots.append(t.base)
1481
 
        bzrdir.BzrDir.open_from_transport(t)
 
1517
        controldir.ControlDir.open_from_transport(t)
1482
1518
 
1483
1519
    def test_requireFeature_available(self):
1484
1520
        """self.requireFeature(available) is a no-op."""
1485
 
        class Available(tests.Feature):
 
1521
        class Available(features.Feature):
1486
1522
            def _probe(self):return True
1487
1523
        feature = Available()
1488
1524
        self.requireFeature(feature)
1489
1525
 
1490
1526
    def test_requireFeature_unavailable(self):
1491
1527
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1492
 
        class Unavailable(tests.Feature):
 
1528
        class Unavailable(features.Feature):
1493
1529
            def _probe(self):return False
1494
1530
        feature = Unavailable()
1495
1531
        self.assertRaises(tests.UnavailableFeature,
1618
1654
        self.assertRaises(AssertionError,
1619
1655
            self.assertListRaises, _TestException, success_generator)
1620
1656
 
 
1657
    def _run_successful_test(self, test):
 
1658
        result = testtools.TestResult()
 
1659
        test.run(result)
 
1660
        self.assertTrue(result.wasSuccessful())
 
1661
        return result
 
1662
 
1621
1663
    def test_overrideAttr_without_value(self):
1622
1664
        self.test_attr = 'original' # Define a test attribute
1623
1665
        obj = self # Make 'obj' visible to the embedded test
1624
1666
        class Test(tests.TestCase):
1625
1667
 
1626
1668
            def setUp(self):
1627
 
                tests.TestCase.setUp(self)
 
1669
                super(Test, self).setUp()
1628
1670
                self.orig = self.overrideAttr(obj, 'test_attr')
1629
1671
 
1630
1672
            def test_value(self):
1633
1675
                obj.test_attr = 'modified'
1634
1676
                self.assertEqual('modified', obj.test_attr)
1635
1677
 
1636
 
        test = Test('test_value')
1637
 
        test.run(unittest.TestResult())
 
1678
        self._run_successful_test(Test('test_value'))
1638
1679
        self.assertEqual('original', obj.test_attr)
1639
1680
 
1640
1681
    def test_overrideAttr_with_value(self):
1643
1684
        class Test(tests.TestCase):
1644
1685
 
1645
1686
            def setUp(self):
1646
 
                tests.TestCase.setUp(self)
 
1687
                super(Test, self).setUp()
1647
1688
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1648
1689
 
1649
1690
            def test_value(self):
1650
1691
                self.assertEqual('original', self.orig)
1651
1692
                self.assertEqual('modified', obj.test_attr)
1652
1693
 
1653
 
        test = Test('test_value')
1654
 
        test.run(unittest.TestResult())
 
1694
        self._run_successful_test(Test('test_value'))
1655
1695
        self.assertEqual('original', obj.test_attr)
1656
1696
 
 
1697
    def test_overrideAttr_with_no_existing_value_and_value(self):
 
1698
        # Do not define the test_attribute
 
1699
        obj = self # Make 'obj' visible to the embedded test
 
1700
        class Test(tests.TestCase):
 
1701
 
 
1702
            def setUp(self):
 
1703
                tests.TestCase.setUp(self)
 
1704
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
 
1705
 
 
1706
            def test_value(self):
 
1707
                self.assertEqual(tests._unitialized_attr, self.orig)
 
1708
                self.assertEqual('modified', obj.test_attr)
 
1709
 
 
1710
        self._run_successful_test(Test('test_value'))
 
1711
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1712
 
 
1713
    def test_overrideAttr_with_no_existing_value_and_no_value(self):
 
1714
        # Do not define the test_attribute
 
1715
        obj = self # Make 'obj' visible to the embedded test
 
1716
        class Test(tests.TestCase):
 
1717
 
 
1718
            def setUp(self):
 
1719
                tests.TestCase.setUp(self)
 
1720
                self.orig = self.overrideAttr(obj, 'test_attr')
 
1721
 
 
1722
            def test_value(self):
 
1723
                self.assertEqual(tests._unitialized_attr, self.orig)
 
1724
                self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1725
 
 
1726
        self._run_successful_test(Test('test_value'))
 
1727
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1728
 
 
1729
    def test_recordCalls(self):
 
1730
        from breezy.tests import test_selftest
 
1731
        calls = self.recordCalls(
 
1732
            test_selftest, '_add_numbers')
 
1733
        self.assertEqual(test_selftest._add_numbers(2, 10),
 
1734
            12)
 
1735
        self.assertEqual(calls, [((2, 10), {})])
 
1736
 
 
1737
 
 
1738
def _add_numbers(a, b):
 
1739
    return a + b
 
1740
 
 
1741
 
 
1742
class _MissingFeature(features.Feature):
 
1743
    def _probe(self):
 
1744
        return False
 
1745
missing_feature = _MissingFeature()
 
1746
 
 
1747
 
 
1748
def _get_test(name):
 
1749
    """Get an instance of a specific example test.
 
1750
 
 
1751
    We protect this in a function so that they don't auto-run in the test
 
1752
    suite.
 
1753
    """
 
1754
 
 
1755
    class ExampleTests(tests.TestCase):
 
1756
 
 
1757
        def test_fail(self):
 
1758
            mutter('this was a failing test')
 
1759
            self.fail('this test will fail')
 
1760
 
 
1761
        def test_error(self):
 
1762
            mutter('this test errored')
 
1763
            raise RuntimeError('gotcha')
 
1764
 
 
1765
        def test_missing_feature(self):
 
1766
            mutter('missing the feature')
 
1767
            self.requireFeature(missing_feature)
 
1768
 
 
1769
        def test_skip(self):
 
1770
            mutter('this test will be skipped')
 
1771
            raise tests.TestSkipped('reason')
 
1772
 
 
1773
        def test_success(self):
 
1774
            mutter('this test succeeds')
 
1775
 
 
1776
        def test_xfail(self):
 
1777
            mutter('test with expected failure')
 
1778
            self.knownFailure('this_fails')
 
1779
 
 
1780
        def test_unexpected_success(self):
 
1781
            mutter('test with unexpected success')
 
1782
            self.expectFailure('should_fail', lambda: None)
 
1783
 
 
1784
    return ExampleTests(name)
 
1785
 
 
1786
 
 
1787
class TestTestCaseLogDetails(tests.TestCase):
 
1788
 
 
1789
    def _run_test(self, test_name):
 
1790
        test = _get_test(test_name)
 
1791
        result = testtools.TestResult()
 
1792
        test.run(result)
 
1793
        return result
 
1794
 
 
1795
    def test_fail_has_log(self):
 
1796
        result = self._run_test('test_fail')
 
1797
        self.assertEqual(1, len(result.failures))
 
1798
        result_content = result.failures[0][1]
 
1799
        self.assertContainsRe(result_content,
 
1800
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1801
        self.assertContainsRe(result_content, 'this was a failing test')
 
1802
 
 
1803
    def test_error_has_log(self):
 
1804
        result = self._run_test('test_error')
 
1805
        self.assertEqual(1, len(result.errors))
 
1806
        result_content = result.errors[0][1]
 
1807
        self.assertContainsRe(result_content,
 
1808
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1809
        self.assertContainsRe(result_content, 'this test errored')
 
1810
 
 
1811
    def test_skip_has_no_log(self):
 
1812
        result = self._run_test('test_skip')
 
1813
        reasons = result.skip_reasons
 
1814
        self.assertEqual({'reason'}, set(reasons))
 
1815
        skips = reasons['reason']
 
1816
        self.assertEqual(1, len(skips))
 
1817
        test = skips[0]
 
1818
        self.assertFalse('log' in test.getDetails())
 
1819
 
 
1820
    def test_missing_feature_has_no_log(self):
 
1821
        # testtools doesn't know about addNotSupported, so it just gets
 
1822
        # considered as a skip
 
1823
        result = self._run_test('test_missing_feature')
 
1824
        reasons = result.skip_reasons
 
1825
        self.assertEqual({str(missing_feature)}, set(reasons))
 
1826
        skips = reasons[str(missing_feature)]
 
1827
        self.assertEqual(1, len(skips))
 
1828
        test = skips[0]
 
1829
        self.assertFalse('log' in test.getDetails())
 
1830
 
 
1831
    def test_xfail_has_no_log(self):
 
1832
        result = self._run_test('test_xfail')
 
1833
        self.assertEqual(1, len(result.expectedFailures))
 
1834
        result_content = result.expectedFailures[0][1]
 
1835
        self.assertNotContainsRe(result_content,
 
1836
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1837
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
1838
 
 
1839
    def test_unexpected_success_has_log(self):
 
1840
        result = self._run_test('test_unexpected_success')
 
1841
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
1842
        # Inconsistency, unexpectedSuccesses is a list of tests,
 
1843
        # expectedFailures is a list of reasons?
 
1844
        test = result.unexpectedSuccesses[0]
 
1845
        details = test.getDetails()
 
1846
        self.assertTrue('log' in details)
 
1847
 
 
1848
 
 
1849
class TestTestCloning(tests.TestCase):
 
1850
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
 
1851
 
 
1852
    def test_cloned_testcase_does_not_share_details(self):
 
1853
        """A TestCase cloned with clone_test does not share mutable attributes
 
1854
        such as details or cleanups.
 
1855
        """
 
1856
        class Test(tests.TestCase):
 
1857
            def test_foo(self):
 
1858
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
 
1859
        orig_test = Test('test_foo')
 
1860
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
 
1861
        orig_test.run(unittest.TestResult())
 
1862
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
 
1863
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
 
1864
 
 
1865
    def test_double_apply_scenario_preserves_first_scenario(self):
 
1866
        """Applying two levels of scenarios to a test preserves the attributes
 
1867
        added by both scenarios.
 
1868
        """
 
1869
        class Test(tests.TestCase):
 
1870
            def test_foo(self):
 
1871
                pass
 
1872
        test = Test('test_foo')
 
1873
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
 
1874
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
 
1875
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
 
1876
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
 
1877
        all_tests = list(tests.iter_suite_tests(suite))
 
1878
        self.assertLength(4, all_tests)
 
1879
        all_xys = sorted((t.x, t.y) for t in all_tests)
 
1880
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
 
1881
 
1657
1882
 
1658
1883
# NB: Don't delete this; it's not actually from 0.11!
1659
1884
@deprecated_function(deprecated_in((0, 11, 0)))
1683
1908
 
1684
1909
 
1685
1910
class TestExtraAssertions(tests.TestCase):
1686
 
    """Tests for new test assertions in bzrlib test suite"""
 
1911
    """Tests for new test assertions in breezy test suite"""
1687
1912
 
1688
1913
    def test_assert_isinstance(self):
1689
1914
        self.assertIsInstance(2, int)
1690
 
        self.assertIsInstance(u'', basestring)
 
1915
        self.assertIsInstance(u'', (str, text_type))
1691
1916
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1692
 
        self.assertEquals(str(e),
1693
 
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
 
1917
        self.assertIn(str(e),
 
1918
            ["None is an instance of <type 'NoneType'> rather than <type 'int'>",
 
1919
             "None is an instance of <class 'NoneType'> rather than <class 'int'>"])
1694
1920
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1695
1921
        e = self.assertRaises(AssertionError,
1696
1922
            self.assertIsInstance, None, int, "it's just not")
1697
 
        self.assertEquals(str(e),
1698
 
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
1699
 
            ": it's just not")
 
1923
        if PY3:
 
1924
            self.assertEqual(str(e),
 
1925
                "None is an instance of <class 'NoneType'> rather than <class 'int'>: it's "
 
1926
                "just not")
 
1927
        else:
 
1928
            self.assertEqual(str(e),
 
1929
                "None is an instance of <type 'NoneType'> rather than <type 'int'>"
 
1930
                ": it's just not")
1700
1931
 
1701
1932
    def test_assertEndsWith(self):
1702
1933
        self.assertEndsWith('foo', 'oo')
1705
1936
    def test_assertEqualDiff(self):
1706
1937
        e = self.assertRaises(AssertionError,
1707
1938
                              self.assertEqualDiff, '', '\n')
1708
 
        self.assertEquals(str(e),
 
1939
        self.assertEqual(str(e),
1709
1940
                          # Don't blink ! The '+' applies to the second string
1710
1941
                          'first string is missing a final newline.\n+ \n')
1711
1942
        e = self.assertRaises(AssertionError,
1712
1943
                              self.assertEqualDiff, '\n', '')
1713
 
        self.assertEquals(str(e),
 
1944
        self.assertEqual(str(e),
1714
1945
                          # Don't blink ! The '-' applies to the second string
1715
1946
                          'second string is missing a final newline.\n- \n')
1716
1947
 
1773
2004
            warnings.warn("this is your last warning")
1774
2005
            return a + b
1775
2006
        wlist, result = self.callCatchWarnings(meth, 1, 2)
1776
 
        self.assertEquals(3, result)
 
2007
        self.assertEqual(3, result)
1777
2008
        # would like just to compare them, but UserWarning doesn't implement
1778
2009
        # eq well
1779
2010
        w0, = wlist
1780
2011
        self.assertIsInstance(w0, UserWarning)
1781
 
        self.assertEquals("this is your last warning", str(w0))
 
2012
        self.assertEqual("this is your last warning", str(w0))
1782
2013
 
1783
2014
 
1784
2015
class TestConvenienceMakers(tests.TestCaseWithTransport):
1786
2017
 
1787
2018
    def test_make_branch_and_tree_with_format(self):
1788
2019
        # we should be able to supply a format to make_branch_and_tree
1789
 
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1790
 
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1791
 
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1792
 
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1793
 
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1794
 
                              bzrlib.bzrdir.BzrDirFormat6)
 
2020
        self.make_branch_and_tree('a', format=breezy.bzr.bzrdir.BzrDirMetaFormat1())
 
2021
        self.assertIsInstance(breezy.controldir.ControlDir.open('a')._format,
 
2022
                              breezy.bzr.bzrdir.BzrDirMetaFormat1)
1795
2023
 
1796
2024
    def test_make_branch_and_memory_tree(self):
1797
2025
        # we should be able to get a new branch and a mutable tree from
1798
2026
        # TestCaseWithTransport
1799
2027
        tree = self.make_branch_and_memory_tree('a')
1800
 
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
2028
        self.assertIsInstance(tree, breezy.memorytree.MemoryTree)
1801
2029
 
1802
2030
    def test_make_tree_for_local_vfs_backed_transport(self):
1803
2031
        # make_branch_and_tree has to use local branch and repositories
1806
2034
        self.transport_server = test_server.FakeVFATServer
1807
2035
        self.assertFalse(self.get_url('t1').startswith('file://'))
1808
2036
        tree = self.make_branch_and_tree('t1')
1809
 
        base = tree.bzrdir.root_transport.base
 
2037
        base = tree.controldir.root_transport.base
1810
2038
        self.assertStartsWith(base, 'file://')
1811
 
        self.assertEquals(tree.bzrdir.root_transport,
1812
 
                tree.branch.bzrdir.root_transport)
1813
 
        self.assertEquals(tree.bzrdir.root_transport,
1814
 
                tree.branch.repository.bzrdir.root_transport)
1815
 
 
1816
 
 
1817
 
class SelfTestHelper:
 
2039
        self.assertEqual(tree.controldir.root_transport,
 
2040
                tree.branch.controldir.root_transport)
 
2041
        self.assertEqual(tree.controldir.root_transport,
 
2042
                tree.branch.repository.controldir.root_transport)
 
2043
 
 
2044
 
 
2045
class SelfTestHelper(object):
1818
2046
 
1819
2047
    def run_selftest(self, **kwargs):
1820
2048
        """Run selftest returning its output."""
1821
 
        output = StringIO()
1822
 
        old_transport = bzrlib.tests.default_transport
 
2049
        if PY3:
 
2050
            bio = BytesIO()
 
2051
            output = TextIOWrapper(bio, 'utf-8')
 
2052
        else:
 
2053
            bio = output = StringIO()
 
2054
        old_transport = breezy.tests.default_transport
1823
2055
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1824
2056
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1825
2057
        try:
1826
2058
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1827
2059
        finally:
1828
 
            bzrlib.tests.default_transport = old_transport
 
2060
            breezy.tests.default_transport = old_transport
1829
2061
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1830
 
        output.seek(0)
1831
 
        return output
 
2062
        if PY3:
 
2063
            output.flush()
 
2064
            output.detach()
 
2065
        bio.seek(0)
 
2066
        return bio
1832
2067
 
1833
2068
 
1834
2069
class TestSelftest(tests.TestCase, SelfTestHelper):
1835
 
    """Tests of bzrlib.tests.selftest."""
 
2070
    """Tests of breezy.tests.selftest."""
1836
2071
 
1837
2072
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1838
2073
        factory_called = []
1841
2076
            return TestUtil.TestSuite()
1842
2077
        out = StringIO()
1843
2078
        err = StringIO()
1844
 
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
2079
        self.apply_redirected(out, err, None, breezy.tests.selftest,
1845
2080
            test_suite_factory=factory)
1846
2081
        self.assertEqual([True], factory_called)
1847
2082
 
1848
2083
    def factory(self):
1849
2084
        """A test suite factory."""
1850
2085
        class Test(tests.TestCase):
 
2086
            def id(self):
 
2087
                return __name__ + ".Test." + self._testMethodName
1851
2088
            def a(self):
1852
2089
                pass
1853
2090
            def b(self):
1854
2091
                pass
1855
 
            def c(self):
 
2092
            def c(telf):
1856
2093
                pass
1857
2094
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1858
2095
 
1864
2101
    def test_list_only_filtered(self):
1865
2102
        output = self.run_selftest(test_suite_factory=self.factory,
1866
2103
            list_only=True, pattern="Test.b")
1867
 
        self.assertEndsWith(output.getvalue(), "Test.b\n")
 
2104
        self.assertEndsWith(output.getvalue(), b"Test.b\n")
1868
2105
        self.assertLength(1, output.readlines())
1869
2106
 
1870
2107
    def test_list_only_excludes(self):
1871
2108
        output = self.run_selftest(test_suite_factory=self.factory,
1872
2109
            list_only=True, exclude_pattern="Test.b")
1873
 
        self.assertNotContainsRe("Test.b", output.getvalue())
 
2110
        self.assertNotContainsRe(b"Test.b", output.getvalue())
1874
2111
        self.assertLength(2, output.readlines())
1875
2112
 
1876
2113
    def test_lsprof_tests(self):
1877
 
        self.requireFeature(test_lsprof.LSProfFeature)
1878
 
        calls = []
 
2114
        self.requireFeature(features.lsprof_feature)
 
2115
        results = []
1879
2116
        class Test(object):
1880
2117
            def __call__(test, result):
1881
2118
                test.run(result)
1882
2119
            def run(test, result):
1883
 
                self.assertIsInstance(result, tests.ForwardingResult)
1884
 
                calls.append("called")
 
2120
                results.append(result)
1885
2121
            def countTestCases(self):
1886
2122
                return 1
1887
2123
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1888
 
        self.assertLength(1, calls)
 
2124
        self.assertLength(1, results)
 
2125
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
1889
2126
 
1890
2127
    def test_random(self):
1891
2128
        # test randomising by listing a number of tests.
1909
2146
    def test_runner_class(self):
1910
2147
        self.requireFeature(features.subunit)
1911
2148
        from subunit import ProtocolTestCase
1912
 
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
2149
        stream = self.run_selftest(
 
2150
            runner_class=tests.SubUnitBzrRunnerv1,
1913
2151
            test_suite_factory=self.factory)
1914
2152
        test = ProtocolTestCase(stream)
1915
2153
        result = unittest.TestResult()
1918
2156
 
1919
2157
    def test_starting_with_single_argument(self):
1920
2158
        output = self.run_selftest(test_suite_factory=self.factory,
1921
 
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
 
2159
            starting_with=['breezy.tests.test_selftest.Test.a'],
1922
2160
            list_only=True)
1923
 
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
 
2161
        self.assertEqual(b'breezy.tests.test_selftest.Test.a\n',
1924
2162
            output.getvalue())
1925
2163
 
1926
2164
    def test_starting_with_multiple_argument(self):
1927
2165
        output = self.run_selftest(test_suite_factory=self.factory,
1928
 
            starting_with=['bzrlib.tests.test_selftest.Test.a',
1929
 
                'bzrlib.tests.test_selftest.Test.b'],
 
2166
            starting_with=['breezy.tests.test_selftest.Test.a',
 
2167
                'breezy.tests.test_selftest.Test.b'],
1930
2168
            list_only=True)
1931
 
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1932
 
            'bzrlib.tests.test_selftest.Test.b\n',
 
2169
        self.assertEqual(b'breezy.tests.test_selftest.Test.a\n'
 
2170
            b'breezy.tests.test_selftest.Test.b\n',
1933
2171
            output.getvalue())
1934
2172
 
1935
2173
    def check_transport_set(self, transport_server):
1938
2176
            captured_transport.append(a_transport)
1939
2177
        class Capture(tests.TestCase):
1940
2178
            def a(self):
1941
 
                seen_transport(bzrlib.tests.default_transport)
 
2179
                seen_transport(breezy.tests.default_transport)
1942
2180
        def factory():
1943
2181
            return TestUtil.TestSuite([Capture("a")])
1944
2182
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
1946
2184
 
1947
2185
    def test_transport_sftp(self):
1948
2186
        self.requireFeature(features.paramiko)
1949
 
        from bzrlib.tests import stub_sftp
 
2187
        from breezy.tests import stub_sftp
1950
2188
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
1951
2189
 
1952
2190
    def test_transport_memory(self):
1958
2196
 
1959
2197
    def test_load_list(self):
1960
2198
        # Provide a list with one test - this test.
1961
 
        test_id_line = '%s\n' % self.id()
 
2199
        test_id_line = b'%s\n' % self.id().encode('ascii')
1962
2200
        self.build_tree_contents([('test.list', test_id_line)])
1963
2201
        # And generate a list of the tests in  the suite.
1964
2202
        stream = self.run_selftest(load_list='test.list', list_only=True)
1971
2209
            load_list='missing file name', list_only=True)
1972
2210
 
1973
2211
 
 
2212
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
 
2213
 
 
2214
    _test_needs_features = [features.subunit]
 
2215
 
 
2216
    def run_subunit_stream(self, test_name):
 
2217
        from subunit import ProtocolTestCase
 
2218
        def factory():
 
2219
            return TestUtil.TestSuite([_get_test(test_name)])
 
2220
        stream = self.run_selftest(
 
2221
            runner_class=tests.SubUnitBzrRunnerv1,
 
2222
            test_suite_factory=factory)
 
2223
        test = ProtocolTestCase(stream)
 
2224
        result = testtools.TestResult()
 
2225
        test.run(result)
 
2226
        content = stream.getvalue()
 
2227
        return content, result
 
2228
 
 
2229
    def test_fail_has_log(self):
 
2230
        content, result = self.run_subunit_stream('test_fail')
 
2231
        self.assertEqual(1, len(result.failures))
 
2232
        self.assertContainsRe(content, b'(?m)^log$')
 
2233
        self.assertContainsRe(content, b'this test will fail')
 
2234
 
 
2235
    def test_error_has_log(self):
 
2236
        content, result = self.run_subunit_stream('test_error')
 
2237
        self.assertContainsRe(content, b'(?m)^log$')
 
2238
        self.assertContainsRe(content, b'this test errored')
 
2239
 
 
2240
    def test_skip_has_no_log(self):
 
2241
        content, result = self.run_subunit_stream('test_skip')
 
2242
        self.assertNotContainsRe(content, b'(?m)^log$')
 
2243
        self.assertNotContainsRe(content, b'this test will be skipped')
 
2244
        reasons = result.skip_reasons
 
2245
        self.assertEqual({'reason'}, set(reasons))
 
2246
        skips = reasons['reason']
 
2247
        self.assertEqual(1, len(skips))
 
2248
        test = skips[0]
 
2249
        # RemotedTestCase doesn't preserve the "details"
 
2250
        ## self.assertFalse('log' in test.getDetails())
 
2251
 
 
2252
    def test_missing_feature_has_no_log(self):
 
2253
        content, result = self.run_subunit_stream('test_missing_feature')
 
2254
        self.assertNotContainsRe(content, b'(?m)^log$')
 
2255
        self.assertNotContainsRe(content, b'missing the feature')
 
2256
        reasons = result.skip_reasons
 
2257
        self.assertEqual({'_MissingFeature\n'}, set(reasons))
 
2258
        skips = reasons['_MissingFeature\n']
 
2259
        self.assertEqual(1, len(skips))
 
2260
        test = skips[0]
 
2261
        # RemotedTestCase doesn't preserve the "details"
 
2262
        ## self.assertFalse('log' in test.getDetails())
 
2263
 
 
2264
    def test_xfail_has_no_log(self):
 
2265
        content, result = self.run_subunit_stream('test_xfail')
 
2266
        self.assertNotContainsRe(content, b'(?m)^log$')
 
2267
        self.assertNotContainsRe(content, b'test with expected failure')
 
2268
        self.assertEqual(1, len(result.expectedFailures))
 
2269
        result_content = result.expectedFailures[0][1]
 
2270
        self.assertNotContainsRe(result_content,
 
2271
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
2272
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
2273
 
 
2274
    def test_unexpected_success_has_log(self):
 
2275
        content, result = self.run_subunit_stream('test_unexpected_success')
 
2276
        self.assertContainsRe(content, b'(?m)^log$')
 
2277
        self.assertContainsRe(content, b'test with unexpected success')
 
2278
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
2279
        test = result.unexpectedSuccesses[0]
 
2280
        # RemotedTestCase doesn't preserve the "details"
 
2281
        ## self.assertTrue('log' in test.getDetails())
 
2282
 
 
2283
    def test_success_has_no_log(self):
 
2284
        content, result = self.run_subunit_stream('test_success')
 
2285
        self.assertEqual(1, result.testsRun)
 
2286
        self.assertNotContainsRe(content, b'(?m)^log$')
 
2287
        self.assertNotContainsRe(content, b'this test succeeds')
 
2288
 
 
2289
 
1974
2290
class TestRunBzr(tests.TestCase):
1975
2291
 
 
2292
    result = 0
1976
2293
    out = ''
1977
2294
    err = ''
1978
2295
 
1979
 
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
1980
 
                         working_dir=None):
 
2296
    def _run_bzr_core(self, argv, encoding=None, stdin=None,
 
2297
                      stdout=None, stderr=None, working_dir=None):
1981
2298
        """Override _run_bzr_core to test how it is invoked by run_bzr.
1982
2299
 
1983
2300
        Attempts to run bzr from inside this class don't actually run it.
1986
2303
        only need to test that it passes the right parameters to run_bzr.
1987
2304
        """
1988
2305
        self.argv = list(argv)
1989
 
        self.retcode = retcode
1990
2306
        self.encoding = encoding
1991
2307
        self.stdin = stdin
1992
2308
        self.working_dir = working_dir
1993
 
        return self.retcode, self.out, self.err
 
2309
        stdout.write(self.out)
 
2310
        stderr.write(self.err)
 
2311
        return self.result
1994
2312
 
1995
2313
    def test_run_bzr_error(self):
1996
2314
        self.out = "It sure does!\n"
 
2315
        self.result = 34
1997
2316
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
1998
2317
        self.assertEqual(['rocks'], self.argv)
1999
 
        self.assertEqual(34, self.retcode)
2000
2318
        self.assertEqual('It sure does!\n', out)
2001
 
        self.assertEquals(out, self.out)
 
2319
        self.assertEqual(out, self.out)
2002
2320
        self.assertEqual('', err)
2003
 
        self.assertEquals(err, self.err)
 
2321
        self.assertEqual(err, self.err)
2004
2322
 
2005
2323
    def test_run_bzr_error_regexes(self):
2006
2324
        self.out = ''
2007
2325
        self.err = "bzr: ERROR: foobarbaz is not versioned"
 
2326
        self.result = 3
2008
2327
        out, err = self.run_bzr_error(
2009
2328
            ["bzr: ERROR: foobarbaz is not versioned"],
2010
2329
            ['file-id', 'foobarbaz'])
2012
2331
    def test_encoding(self):
2013
2332
        """Test that run_bzr passes encoding to _run_bzr_core"""
2014
2333
        self.run_bzr('foo bar')
2015
 
        self.assertEqual(None, self.encoding)
 
2334
        self.assertEqual(osutils.get_user_encoding(), self.encoding)
2016
2335
        self.assertEqual(['foo', 'bar'], self.argv)
2017
2336
 
2018
2337
        self.run_bzr('foo bar', encoding='baz')
2019
2338
        self.assertEqual('baz', self.encoding)
2020
2339
        self.assertEqual(['foo', 'bar'], self.argv)
2021
2340
 
2022
 
    def test_retcode(self):
2023
 
        """Test that run_bzr passes retcode to _run_bzr_core"""
2024
 
        # Default is retcode == 0
2025
 
        self.run_bzr('foo bar')
2026
 
        self.assertEqual(0, self.retcode)
2027
 
        self.assertEqual(['foo', 'bar'], self.argv)
2028
 
 
2029
 
        self.run_bzr('foo bar', retcode=1)
2030
 
        self.assertEqual(1, self.retcode)
2031
 
        self.assertEqual(['foo', 'bar'], self.argv)
2032
 
 
2033
 
        self.run_bzr('foo bar', retcode=None)
2034
 
        self.assertEqual(None, self.retcode)
2035
 
        self.assertEqual(['foo', 'bar'], self.argv)
2036
 
 
2037
 
        self.run_bzr(['foo', 'bar'], retcode=3)
2038
 
        self.assertEqual(3, self.retcode)
2039
 
        self.assertEqual(['foo', 'bar'], self.argv)
2040
 
 
2041
2341
    def test_stdin(self):
2042
2342
        # test that the stdin keyword to run_bzr is passed through to
2043
2343
        # _run_bzr_core as-is. We do this by overriding
2073
2373
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2074
2374
                         a_callable=None, *args, **kwargs):
2075
2375
        self.stdin = stdin
2076
 
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2077
 
        self.factory = bzrlib.ui.ui_factory
 
2376
        self.factory_stdin = getattr(breezy.ui.ui_factory, "stdin", None)
 
2377
        self.factory = breezy.ui.ui_factory
2078
2378
        self.working_dir = osutils.getcwd()
2079
2379
        stdout.write('foo\n')
2080
2380
        stderr.write('bar\n')
2097
2397
        # own UI factory, which is an instance of TestUIFactory,
2098
2398
        # with stdin, stdout and stderr attached to the stdin,
2099
2399
        # stdout and stderr of the invoked run_bzr
2100
 
        current_factory = bzrlib.ui.ui_factory
 
2400
        current_factory = breezy.ui.ui_factory
2101
2401
        self.run_bzr(['foo'])
2102
 
        self.failIf(current_factory is self.factory)
 
2402
        self.assertFalse(current_factory is self.factory)
2103
2403
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2104
2404
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2105
2405
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2146
2446
    """Base class for tests testing how we might run bzr."""
2147
2447
 
2148
2448
    def setUp(self):
2149
 
        tests.TestCaseWithTransport.setUp(self)
 
2449
        super(TestWithFakedStartBzrSubprocess, self).setUp()
2150
2450
        self.subprocess_calls = []
2151
2451
 
2152
2452
    def start_bzr_subprocess(self, process_args, env_changes=None,
2175
2475
            result = self.run_bzr_subprocess(*args, **kwargs)
2176
2476
        except:
2177
2477
            self.next_subprocess = None
2178
 
            for key, expected in expected_args.iteritems():
 
2478
            for key, expected in expected_args.items():
2179
2479
                self.assertEqual(expected, self.subprocess_calls[-1][key])
2180
2480
            raise
2181
2481
        else:
2182
2482
            self.next_subprocess = None
2183
 
            for key, expected in expected_args.iteritems():
 
2483
            for key, expected in expected_args.items():
2184
2484
                self.assertEqual(expected, self.subprocess_calls[-1][key])
2185
2485
            return result
2186
2486
 
2262
2562
 
2263
2563
 
2264
2564
class TestStartBzrSubProcess(tests.TestCase):
 
2565
    """Stub test start_bzr_subprocess."""
2265
2566
 
2266
 
    def check_popen_state(self):
2267
 
        """Replace to make assertions when popen is called."""
 
2567
    def _subprocess_log_cleanup(self):
 
2568
        """Inhibits the base version as we don't produce a log file."""
2268
2569
 
2269
2570
    def _popen(self, *args, **kwargs):
2270
 
        """Record the command that is run, so that we can ensure it is correct"""
 
2571
        """Override the base version to record the command that is run.
 
2572
 
 
2573
        From there we can ensure it is correct without spawning a real process.
 
2574
        """
2271
2575
        self.check_popen_state()
2272
2576
        self._popen_args = args
2273
2577
        self._popen_kwargs = kwargs
2274
2578
        raise _DontSpawnProcess()
2275
2579
 
 
2580
    def check_popen_state(self):
 
2581
        """Replace to make assertions when popen is called."""
 
2582
 
2276
2583
    def test_run_bzr_subprocess_no_plugins(self):
2277
2584
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2278
2585
        command = self._popen_args[0]
2279
2586
        self.assertEqual(sys.executable, command[0])
2280
 
        self.assertEqual(self.get_bzr_path(), command[1])
 
2587
        self.assertEqual(self.get_brz_path(), command[1])
2281
2588
        self.assertEqual(['--no-plugins'], command[2:])
2282
2589
 
2283
2590
    def test_allow_plugins(self):
2284
2591
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2285
 
            allow_plugins=True)
 
2592
                          allow_plugins=True)
2286
2593
        command = self._popen_args[0]
2287
2594
        self.assertEqual([], command[2:])
2288
2595
 
2289
2596
    def test_set_env(self):
2290
 
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2597
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2291
2598
        # set in the child
2292
2599
        def check_environment():
2293
2600
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2294
2601
        self.check_popen_state = check_environment
2295
2602
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2296
 
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2603
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
2297
2604
        # not set in theparent
2298
2605
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2299
2606
 
2300
2607
    def test_run_bzr_subprocess_env_del(self):
2301
2608
        """run_bzr_subprocess can remove environment variables too."""
2302
 
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2609
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2303
2610
        def check_environment():
2304
2611
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2305
2612
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2306
2613
        self.check_popen_state = check_environment
2307
2614
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2308
 
            env_changes={'EXISTANT_ENV_VAR':None})
 
2615
                          env_changes={'EXISTANT_ENV_VAR':None})
2309
2616
        # Still set in parent
2310
2617
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2311
2618
        del os.environ['EXISTANT_ENV_VAR']
2312
2619
 
2313
2620
    def test_env_del_missing(self):
2314
 
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2621
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2315
2622
        def check_environment():
2316
2623
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2317
2624
        self.check_popen_state = check_environment
2318
2625
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2319
 
            env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2626
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
2320
2627
 
2321
2628
    def test_working_dir(self):
2322
2629
        """Test that we can specify the working dir for the child"""
2325
2632
        chdirs = []
2326
2633
        def chdir(path):
2327
2634
            chdirs.append(path)
2328
 
        os.chdir = chdir
2329
 
        try:
2330
 
            def getcwd():
2331
 
                return 'current'
2332
 
            osutils.getcwd = getcwd
2333
 
            try:
2334
 
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2335
 
                    working_dir='foo')
2336
 
            finally:
2337
 
                osutils.getcwd = orig_getcwd
2338
 
        finally:
2339
 
            os.chdir = orig_chdir
 
2635
        self.overrideAttr(os, 'chdir', chdir)
 
2636
        def getcwd():
 
2637
            return 'current'
 
2638
        self.overrideAttr(osutils, 'getcwd', getcwd)
 
2639
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2640
                          working_dir='foo')
2340
2641
        self.assertEqual(['foo', 'current'], chdirs)
2341
2642
 
 
2643
    def test_get_brz_path_with_cwd_breezy(self):
 
2644
        self.get_source_path = lambda: ""
 
2645
        self.overrideAttr(os.path, "isfile", lambda path: True)
 
2646
        self.assertEqual(self.get_brz_path(), "brz")
 
2647
 
2342
2648
 
2343
2649
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2344
2650
    """Tests that really need to do things with an external bzr."""
2350
2656
        self.disable_missing_extensions_warning()
2351
2657
        process = self.start_bzr_subprocess(['wait-until-signalled'],
2352
2658
                                            skip_if_plan_to_signal=True)
2353
 
        self.assertEqual('running\n', process.stdout.readline())
 
2659
        self.assertEqual(b'running\n', process.stdout.readline())
2354
2660
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2355
2661
                                            retcode=3)
2356
 
        self.assertEqual('', result[0])
2357
 
        self.assertEqual('bzr: interrupted\n', result[1])
2358
 
 
2359
 
 
2360
 
class TestFeature(tests.TestCase):
2361
 
 
2362
 
    def test_caching(self):
2363
 
        """Feature._probe is called by the feature at most once."""
2364
 
        class InstrumentedFeature(tests.Feature):
2365
 
            def __init__(self):
2366
 
                super(InstrumentedFeature, self).__init__()
2367
 
                self.calls = []
2368
 
            def _probe(self):
2369
 
                self.calls.append('_probe')
2370
 
                return False
2371
 
        feature = InstrumentedFeature()
2372
 
        feature.available()
2373
 
        self.assertEqual(['_probe'], feature.calls)
2374
 
        feature.available()
2375
 
        self.assertEqual(['_probe'], feature.calls)
2376
 
 
2377
 
    def test_named_str(self):
2378
 
        """Feature.__str__ should thunk to feature_name()."""
2379
 
        class NamedFeature(tests.Feature):
2380
 
            def feature_name(self):
2381
 
                return 'symlinks'
2382
 
        feature = NamedFeature()
2383
 
        self.assertEqual('symlinks', str(feature))
2384
 
 
2385
 
    def test_default_str(self):
2386
 
        """Feature.__str__ should default to __class__.__name__."""
2387
 
        class NamedFeature(tests.Feature):
2388
 
            pass
2389
 
        feature = NamedFeature()
2390
 
        self.assertEqual('NamedFeature', str(feature))
2391
 
 
2392
 
 
2393
 
class TestUnavailableFeature(tests.TestCase):
2394
 
 
2395
 
    def test_access_feature(self):
2396
 
        feature = tests.Feature()
2397
 
        exception = tests.UnavailableFeature(feature)
2398
 
        self.assertIs(feature, exception.args[0])
2399
 
 
2400
 
 
2401
 
simple_thunk_feature = tests._CompatabilityThunkFeature(
2402
 
    deprecated_in((2, 1, 0)),
2403
 
    'bzrlib.tests.test_selftest',
2404
 
    'simple_thunk_feature','UnicodeFilename',
2405
 
    replacement_module='bzrlib.tests'
2406
 
    )
2407
 
 
2408
 
class Test_CompatibilityFeature(tests.TestCase):
2409
 
 
2410
 
    def test_does_thunk(self):
2411
 
        res = self.callDeprecated(
2412
 
            ['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
2413
 
             ' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
2414
 
            simple_thunk_feature.available)
2415
 
        self.assertEqual(tests.UnicodeFilename.available(), res)
2416
 
 
2417
 
 
2418
 
class TestModuleAvailableFeature(tests.TestCase):
2419
 
 
2420
 
    def test_available_module(self):
2421
 
        feature = tests.ModuleAvailableFeature('bzrlib.tests')
2422
 
        self.assertEqual('bzrlib.tests', feature.module_name)
2423
 
        self.assertEqual('bzrlib.tests', str(feature))
2424
 
        self.assertTrue(feature.available())
2425
 
        self.assertIs(tests, feature.module)
2426
 
 
2427
 
    def test_unavailable_module(self):
2428
 
        feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
2429
 
        self.assertEqual('bzrlib.no_such_module_exists', str(feature))
2430
 
        self.assertFalse(feature.available())
2431
 
        self.assertIs(None, feature.module)
 
2662
        self.assertEqual(b'', result[0])
 
2663
        self.assertEqual(b'brz: interrupted\n', result[1])
2432
2664
 
2433
2665
 
2434
2666
class TestSelftestFiltering(tests.TestCase):
2435
2667
 
2436
2668
    def setUp(self):
2437
 
        tests.TestCase.setUp(self)
 
2669
        super(TestSelftestFiltering, self).setUp()
2438
2670
        self.suite = TestUtil.TestSuite()
2439
2671
        self.loader = TestUtil.TestLoader()
2440
2672
        self.suite.addTest(self.loader.loadTestsFromModule(
2441
 
            sys.modules['bzrlib.tests.test_selftest']))
 
2673
            sys.modules['breezy.tests.test_selftest']))
2442
2674
        self.all_names = _test_ids(self.suite)
2443
2675
 
2444
2676
    def test_condition_id_re(self):
2445
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2677
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2446
2678
            'test_condition_id_re')
2447
2679
        filtered_suite = tests.filter_suite_by_condition(
2448
2680
            self.suite, tests.condition_id_re('test_condition_id_re'))
2449
2681
        self.assertEqual([test_name], _test_ids(filtered_suite))
2450
2682
 
2451
2683
    def test_condition_id_in_list(self):
2452
 
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2684
        test_names = ['breezy.tests.test_selftest.TestSelftestFiltering.'
2453
2685
                      'test_condition_id_in_list']
2454
2686
        id_list = tests.TestIdList(test_names)
2455
2687
        filtered_suite = tests.filter_suite_by_condition(
2459
2691
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2460
2692
 
2461
2693
    def test_condition_id_startswith(self):
2462
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2694
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
2463
2695
        start1 = klass + 'test_condition_id_starts'
2464
2696
        start2 = klass + 'test_condition_id_in'
2465
2697
        test_names = [ klass + 'test_condition_id_in_list',
2472
2704
    def test_condition_isinstance(self):
2473
2705
        filtered_suite = tests.filter_suite_by_condition(
2474
2706
            self.suite, tests.condition_isinstance(self.__class__))
2475
 
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2707
        class_pattern = 'breezy.tests.test_selftest.TestSelftestFiltering.'
2476
2708
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2477
2709
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2478
2710
 
2479
2711
    def test_exclude_tests_by_condition(self):
2480
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2712
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2481
2713
            'test_exclude_tests_by_condition')
2482
2714
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
2483
2715
            lambda x:x.id() == excluded_name)
2492
2724
        self.all_names = _test_ids(self.suite)
2493
2725
        filtered_suite = tests.exclude_tests_by_re(self.suite,
2494
2726
                                                   'exclude_tests_by_re')
2495
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2727
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2496
2728
            'test_exclude_tests_by_re')
2497
2729
        self.assertEqual(len(self.all_names) - 1,
2498
2730
            filtered_suite.countTestCases())
2502
2734
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
2503
2735
 
2504
2736
    def test_filter_suite_by_condition(self):
2505
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2737
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2506
2738
            'test_filter_suite_by_condition')
2507
2739
        filtered_suite = tests.filter_suite_by_condition(self.suite,
2508
2740
            lambda x:x.id() == test_name)
2512
2744
        filtered_suite = tests.filter_suite_by_re(self.suite,
2513
2745
                                                  'test_filter_suite_by_r')
2514
2746
        filtered_names = _test_ids(filtered_suite)
2515
 
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
2747
        self.assertEqual(filtered_names, ['breezy.tests.test_selftest.'
2516
2748
            'TestSelftestFiltering.test_filter_suite_by_re'])
2517
2749
 
2518
2750
    def test_filter_suite_by_id_list(self):
2519
 
        test_list = ['bzrlib.tests.test_selftest.'
 
2751
        test_list = ['breezy.tests.test_selftest.'
2520
2752
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
2521
2753
        filtered_suite = tests.filter_suite_by_id_list(
2522
2754
            self.suite, tests.TestIdList(test_list))
2523
2755
        filtered_names = _test_ids(filtered_suite)
2524
2756
        self.assertEqual(
2525
2757
            filtered_names,
2526
 
            ['bzrlib.tests.test_selftest.'
 
2758
            ['breezy.tests.test_selftest.'
2527
2759
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
2528
2760
 
2529
2761
    def test_filter_suite_by_id_startswith(self):
2530
2762
        # By design this test may fail if another test is added whose name also
2531
2763
        # begins with one of the start value used.
2532
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2764
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
2533
2765
        start1 = klass + 'test_filter_suite_by_id_starts'
2534
2766
        start2 = klass + 'test_filter_suite_by_id_li'
2535
2767
        test_list = [klass + 'test_filter_suite_by_id_list',
2566
2798
        self.all_names = _test_ids(self.suite)
2567
2799
        condition = tests.condition_id_re('test_filter_suite_by_r')
2568
2800
        split_suite = tests.split_suite_by_condition(self.suite, condition)
2569
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2801
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2570
2802
            'test_filter_suite_by_re')
2571
2803
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2572
2804
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2578
2810
        self.all_names = _test_ids(self.suite)
2579
2811
        split_suite = tests.split_suite_by_re(self.suite,
2580
2812
                                              'test_filter_suite_by_r')
2581
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2813
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2582
2814
            'test_filter_suite_by_re')
2583
2815
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2584
2816
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2587
2819
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2588
2820
 
2589
2821
 
2590
 
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2822
class TestCheckTreeShape(tests.TestCaseWithTransport):
2591
2823
 
2592
 
    def test_check_inventory_shape(self):
 
2824
    def test_check_tree_shape(self):
2593
2825
        files = ['a', 'b/', 'b/c']
2594
2826
        tree = self.make_branch_and_tree('.')
2595
2827
        self.build_tree(files)
2596
2828
        tree.add(files)
2597
2829
        tree.lock_read()
2598
2830
        try:
2599
 
            self.check_inventory_shape(tree.inventory, files)
 
2831
            self.check_tree_shape(tree, files)
2600
2832
        finally:
2601
2833
            tree.unlock()
2602
2834
 
2613
2845
            self.run_bzr, ['assert-fail'])
2614
2846
        # make sure we got the real thing, not an error from somewhere else in
2615
2847
        # the test framework
2616
 
        self.assertEquals('always fails', str(e))
 
2848
        self.assertEqual('always fails', str(e))
2617
2849
        # check that there's no traceback in the test log
2618
2850
        self.assertNotContainsRe(self.get_log(), r'Traceback')
2619
2851
 
2629
2861
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2630
2862
        self.assertEqual(out, '')
2631
2863
        self.assertContainsRe(err,
2632
 
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2864
            'brz: ERROR: Not a branch: ".*nonexistantpath/".\n')
2633
2865
 
2634
2866
 
2635
2867
class TestTestLoader(tests.TestCase):
2646
2878
            pass
2647
2879
        MyModule.a_class = Stub
2648
2880
        module = MyModule()
 
2881
        module.__name__ = 'fake_module'
2649
2882
        return loader, module
2650
2883
 
2651
2884
    def test_module_no_load_tests_attribute_loads_classes(self):
2654
2887
 
2655
2888
    def test_module_load_tests_attribute_gets_called(self):
2656
2889
        loader, module = self._get_loader_and_module()
2657
 
        # 'self' is here because we're faking the module with a class. Regular
2658
 
        # load_tests do not need that :)
2659
 
        def load_tests(self, standard_tests, module, loader):
 
2890
        def load_tests(loader, standard_tests, pattern):
2660
2891
            result = loader.suiteClass()
2661
2892
            for test in tests.iter_suite_tests(standard_tests):
2662
2893
                result.addTests([test, test])
2663
2894
            return result
2664
2895
        # add a load_tests() method which multiplies the tests from the module.
2665
 
        module.__class__.load_tests = load_tests
2666
 
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2896
        module.__class__.load_tests = staticmethod(load_tests)
 
2897
        self.assertEqual(
 
2898
            2 * [str(module.a_class('test_foo'))],
 
2899
            list(map(str, loader.loadTestsFromModule(module))))
2667
2900
 
2668
2901
    def test_load_tests_from_module_name_smoke_test(self):
2669
2902
        loader = TestUtil.TestLoader()
2670
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2671
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2903
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2904
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
2672
2905
                          _test_ids(suite))
2673
2906
 
2674
2907
    def test_load_tests_from_module_name_with_bogus_module_name(self):
2703
2936
 
2704
2937
    def test_empty_list(self):
2705
2938
        id_list = self._create_id_list([])
2706
 
        self.assertEquals({}, id_list.tests)
2707
 
        self.assertEquals({}, id_list.modules)
 
2939
        self.assertEqual({}, id_list.tests)
 
2940
        self.assertEqual({}, id_list.modules)
2708
2941
 
2709
2942
    def test_valid_list(self):
2710
2943
        id_list = self._create_id_list(
2733
2966
 
2734
2967
    def test_test_suite_matches_id_list_with_unknown(self):
2735
2968
        loader = TestUtil.TestLoader()
2736
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2737
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2969
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2970
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',
2738
2971
                     'bogus']
2739
2972
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2740
 
        self.assertEquals(['bogus'], not_found)
2741
 
        self.assertEquals([], duplicates)
 
2973
        self.assertEqual(['bogus'], not_found)
 
2974
        self.assertEqual([], duplicates)
2742
2975
 
2743
2976
    def test_suite_matches_id_list_with_duplicates(self):
2744
2977
        loader = TestUtil.TestLoader()
2745
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2978
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
2746
2979
        dupes = loader.suiteClass()
2747
2980
        for test in tests.iter_suite_tests(suite):
2748
2981
            dupes.addTest(test)
2749
2982
            dupes.addTest(test) # Add it again
2750
2983
 
2751
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2984
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',]
2752
2985
        not_found, duplicates = tests.suite_matches_id_list(
2753
2986
            dupes, test_list)
2754
 
        self.assertEquals([], not_found)
2755
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2987
        self.assertEqual([], not_found)
 
2988
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
2756
2989
                          duplicates)
2757
2990
 
2758
2991
 
2763
2996
        # by _test_suite_testmod_names.
2764
2997
        test_list = tests._test_suite_testmod_names()
2765
2998
        self.assertSubset([
2766
 
            'bzrlib.tests.blackbox',
2767
 
            'bzrlib.tests.per_transport',
2768
 
            'bzrlib.tests.test_selftest',
 
2999
            'breezy.tests.blackbox',
 
3000
            'breezy.tests.per_transport',
 
3001
            'breezy.tests.test_selftest',
2769
3002
            ],
2770
3003
            test_list)
2771
3004
 
2778
3011
            self.assertEqual([], test_list)
2779
3012
            return
2780
3013
        self.assertSubset([
2781
 
            'bzrlib.timestamp',
 
3014
            'breezy.timestamp',
2782
3015
            ],
2783
3016
            test_list)
2784
3017
 
2792
3025
        def testmod_names():
2793
3026
            calls.append("testmod_names")
2794
3027
            return [
2795
 
                'bzrlib.tests.blackbox.test_branch',
2796
 
                'bzrlib.tests.per_transport',
2797
 
                'bzrlib.tests.test_selftest',
 
3028
                'breezy.tests.blackbox.test_branch',
 
3029
                'breezy.tests.per_transport',
 
3030
                'breezy.tests.test_selftest',
2798
3031
                ]
2799
3032
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
2800
3033
        def doctests():
2801
3034
            calls.append("modules_to_doctest")
2802
3035
            if __doc__ is None:
2803
3036
                return []
2804
 
            return ['bzrlib.timestamp']
 
3037
            return ['breezy.timestamp']
2805
3038
        self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
2806
3039
        expected_test_list = [
2807
3040
            # testmod_names
2808
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2809
 
            ('bzrlib.tests.per_transport.TransportTests'
 
3041
            'breezy.tests.blackbox.test_branch.TestBranch.test_branch',
 
3042
            ('breezy.tests.per_transport.TransportTests'
2810
3043
             '.test_abspath(LocalTransport,LocalURLServer)'),
2811
 
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
3044
            'breezy.tests.test_selftest.TestTestSuite.test_test_suite',
2812
3045
            # plugins can't be tested that way since selftest may be run with
2813
3046
            # --no-plugins
2814
3047
            ]
2815
 
        if __doc__ is not None:
 
3048
        if __doc__ is not None and not PY3:
2816
3049
            expected_test_list.extend([
2817
3050
                # modules_to_doctest
2818
 
                'bzrlib.timestamp.format_highres_date',
 
3051
                'breezy.timestamp.format_highres_date',
2819
3052
                ])
2820
3053
        suite = tests.test_suite()
2821
 
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2822
 
            set(calls))
 
3054
        if PY3:
 
3055
            self.assertEqual({"testmod_names"}, set(calls))
 
3056
        else:
 
3057
            self.assertEqual({"testmod_names", "modules_to_doctest"},
 
3058
                set(calls))
2823
3059
        self.assertSubset(expected_test_list, _test_ids(suite))
2824
3060
 
2825
3061
    def test_test_suite_list_and_start(self):
2827
3063
        # to know that starting_with == None works. So a second load is
2828
3064
        # incurred - note that the starting_with parameter causes a partial load
2829
3065
        # rather than a full load so this test should be pretty quick.
2830
 
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
3066
        test_list = ['breezy.tests.test_selftest.TestTestSuite.test_test_suite']
2831
3067
        suite = tests.test_suite(test_list,
2832
 
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
3068
                                 ['breezy.tests.test_selftest.TestTestSuite'])
2833
3069
        # test_test_suite_list_and_start is not included 
2834
 
        self.assertEquals(test_list, _test_ids(suite))
 
3070
        self.assertEqual(test_list, _test_ids(suite))
2835
3071
 
2836
3072
 
2837
3073
class TestLoadTestIdList(tests.TestCaseInTempDir):
2850
3086
        self._create_test_list_file(test_list_fname,
2851
3087
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2852
3088
        tlist = tests.load_test_id_list(test_list_fname)
2853
 
        self.assertEquals(2, len(tlist))
2854
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2855
 
        self.assertEquals('mod2.cl2.meth2', tlist[1])
 
3089
        self.assertEqual(2, len(tlist))
 
3090
        self.assertEqual('mod1.cl1.meth1', tlist[0])
 
3091
        self.assertEqual('mod2.cl2.meth2', tlist[1])
2856
3092
 
2857
3093
    def test_load_dirty_file(self):
2858
3094
        test_list_fname = 'test.list'
2860
3096
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
2861
3097
                                    'bar baz\n')
2862
3098
        tlist = tests.load_test_id_list(test_list_fname)
2863
 
        self.assertEquals(4, len(tlist))
2864
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2865
 
        self.assertEquals('', tlist[1])
2866
 
        self.assertEquals('mod2.cl2.meth2', tlist[2])
2867
 
        self.assertEquals('bar baz', tlist[3])
 
3099
        self.assertEqual(4, len(tlist))
 
3100
        self.assertEqual('mod1.cl1.meth1', tlist[0])
 
3101
        self.assertEqual('', tlist[1])
 
3102
        self.assertEqual('mod2.cl2.meth2', tlist[2])
 
3103
        self.assertEqual('bar baz', tlist[3])
2868
3104
 
2869
3105
 
2870
3106
class TestFilteredByModuleTestLoader(tests.TestCase):
2875
3111
        return loader
2876
3112
 
2877
3113
    def test_load_tests(self):
2878
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
3114
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
2879
3115
        loader = self._create_loader(test_list)
2880
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2881
 
        self.assertEquals(test_list, _test_ids(suite))
 
3116
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3117
        self.assertEqual(test_list, _test_ids(suite))
2882
3118
 
2883
3119
    def test_exclude_tests(self):
2884
3120
        test_list = ['bogus']
2885
3121
        loader = self._create_loader(test_list)
2886
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2887
 
        self.assertEquals([], _test_ids(suite))
 
3122
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3123
        self.assertEqual([], _test_ids(suite))
2888
3124
 
2889
3125
 
2890
3126
class TestFilteredByNameStartTestLoader(tests.TestCase):
2896
3132
        return loader
2897
3133
 
2898
3134
    def test_load_tests(self):
2899
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2900
 
        loader = self._create_loader('bzrlib.tests.test_samp')
 
3135
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3136
        loader = self._create_loader('breezy.tests.test_samp')
2901
3137
 
2902
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2903
 
        self.assertEquals(test_list, _test_ids(suite))
 
3138
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3139
        self.assertEqual(test_list, _test_ids(suite))
2904
3140
 
2905
3141
    def test_load_tests_inside_module(self):
2906
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2907
 
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
3142
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3143
        loader = self._create_loader('breezy.tests.test_sampler.Demo')
2908
3144
 
2909
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2910
 
        self.assertEquals(test_list, _test_ids(suite))
 
3145
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3146
        self.assertEqual(test_list, _test_ids(suite))
2911
3147
 
2912
3148
    def test_exclude_tests(self):
2913
3149
        test_list = ['bogus']
2914
3150
        loader = self._create_loader('bogus')
2915
3151
 
2916
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2917
 
        self.assertEquals([], _test_ids(suite))
 
3152
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3153
        self.assertEqual([], _test_ids(suite))
2918
3154
 
2919
3155
 
2920
3156
class TestTestPrefixRegistry(tests.TestCase):
2926
3162
    def test_register_new_prefix(self):
2927
3163
        tpr = self._get_registry()
2928
3164
        tpr.register('foo', 'fff.ooo.ooo')
2929
 
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
3165
        self.assertEqual('fff.ooo.ooo', tpr.get('foo'))
2930
3166
 
2931
3167
    def test_register_existing_prefix(self):
2932
3168
        tpr = self._get_registry()
2933
3169
        tpr.register('bar', 'bbb.aaa.rrr')
2934
3170
        tpr.register('bar', 'bBB.aAA.rRR')
2935
 
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
3171
        self.assertEqual('bbb.aaa.rrr', tpr.get('bar'))
2936
3172
        self.assertThat(self.get_log(),
2937
 
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
 
3173
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
 
3174
                           doctest.ELLIPSIS))
2938
3175
 
2939
3176
    def test_get_unknown_prefix(self):
2940
3177
        tpr = self._get_registry()
2943
3180
    def test_resolve_prefix(self):
2944
3181
        tpr = self._get_registry()
2945
3182
        tpr.register('bar', 'bb.aa.rr')
2946
 
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
3183
        self.assertEqual('bb.aa.rr', tpr.resolve_alias('bar'))
2947
3184
 
2948
3185
    def test_resolve_unknown_alias(self):
2949
3186
        tpr = self._get_registry()
2952
3189
 
2953
3190
    def test_predefined_prefixes(self):
2954
3191
        tpr = tests.test_prefix_alias_registry
2955
 
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2956
 
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2957
 
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2958
 
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2959
 
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2960
 
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
3192
        self.assertEqual('breezy', tpr.resolve_alias('breezy'))
 
3193
        self.assertEqual('breezy.doc', tpr.resolve_alias('bd'))
 
3194
        self.assertEqual('breezy.utils', tpr.resolve_alias('bu'))
 
3195
        self.assertEqual('breezy.tests', tpr.resolve_alias('bt'))
 
3196
        self.assertEqual('breezy.tests.blackbox', tpr.resolve_alias('bb'))
 
3197
        self.assertEqual('breezy.plugins', tpr.resolve_alias('bp'))
 
3198
 
 
3199
 
 
3200
class TestThreadLeakDetection(tests.TestCase):
 
3201
    """Ensure when tests leak threads we detect and report it"""
 
3202
 
 
3203
    class LeakRecordingResult(tests.ExtendedTestResult):
 
3204
        def __init__(self):
 
3205
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3206
            self.leaks = []
 
3207
        def _report_thread_leak(self, test, leaks, alive):
 
3208
            self.leaks.append((test, leaks))
 
3209
 
 
3210
    def test_testcase_without_addCleanups(self):
 
3211
        """Check old TestCase instances don't break with leak detection"""
 
3212
        class Test(unittest.TestCase):
 
3213
            def runTest(self):
 
3214
                pass
 
3215
        result = self.LeakRecordingResult()
 
3216
        test = Test()
 
3217
        result.startTestRun()
 
3218
        test.run(result)
 
3219
        result.stopTestRun()
 
3220
        self.assertEqual(result._tests_leaking_threads_count, 0)
 
3221
        self.assertEqual(result.leaks, [])
 
3222
        
 
3223
    def test_thread_leak(self):
 
3224
        """Ensure a thread that outlives the running of a test is reported
 
3225
 
 
3226
        Uses a thread that blocks on an event, and is started by the inner
 
3227
        test case. As the thread outlives the inner case's run, it should be
 
3228
        detected as a leak, but the event is then set so that the thread can
 
3229
        be safely joined in cleanup so it's not leaked for real.
 
3230
        """
 
3231
        event = threading.Event()
 
3232
        thread = threading.Thread(name="Leaker", target=event.wait)
 
3233
        class Test(tests.TestCase):
 
3234
            def test_leak(self):
 
3235
                thread.start()
 
3236
        result = self.LeakRecordingResult()
 
3237
        test = Test("test_leak")
 
3238
        self.addCleanup(thread.join)
 
3239
        self.addCleanup(event.set)
 
3240
        result.startTestRun()
 
3241
        test.run(result)
 
3242
        result.stopTestRun()
 
3243
        self.assertEqual(result._tests_leaking_threads_count, 1)
 
3244
        self.assertEqual(result._first_thread_leaker_id, test.id())
 
3245
        self.assertEqual(result.leaks, [(test, {thread})])
 
3246
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3247
 
 
3248
    def test_multiple_leaks(self):
 
3249
        """Check multiple leaks are blamed on the test cases at fault
 
3250
 
 
3251
        Same concept as the previous test, but has one inner test method that
 
3252
        leaks two threads, and one that doesn't leak at all.
 
3253
        """
 
3254
        event = threading.Event()
 
3255
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
 
3256
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
 
3257
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
 
3258
        class Test(tests.TestCase):
 
3259
            def test_first_leak(self):
 
3260
                thread_b.start()
 
3261
            def test_second_no_leak(self):
 
3262
                pass
 
3263
            def test_third_leak(self):
 
3264
                thread_c.start()
 
3265
                thread_a.start()
 
3266
        result = self.LeakRecordingResult()
 
3267
        first_test = Test("test_first_leak")
 
3268
        third_test = Test("test_third_leak")
 
3269
        self.addCleanup(thread_a.join)
 
3270
        self.addCleanup(thread_b.join)
 
3271
        self.addCleanup(thread_c.join)
 
3272
        self.addCleanup(event.set)
 
3273
        result.startTestRun()
 
3274
        unittest.TestSuite(
 
3275
            [first_test, Test("test_second_no_leak"), third_test]
 
3276
            ).run(result)
 
3277
        result.stopTestRun()
 
3278
        self.assertEqual(result._tests_leaking_threads_count, 2)
 
3279
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
 
3280
        self.assertEqual(result.leaks, [
 
3281
            (first_test, {thread_b}),
 
3282
            (third_test, {thread_a, thread_c})])
 
3283
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3284
 
 
3285
 
 
3286
class TestPostMortemDebugging(tests.TestCase):
 
3287
    """Check post mortem debugging works when tests fail or error"""
 
3288
 
 
3289
    class TracebackRecordingResult(tests.ExtendedTestResult):
 
3290
        def __init__(self):
 
3291
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3292
            self.postcode = None
 
3293
        def _post_mortem(self, tb=None):
 
3294
            """Record the code object at the end of the current traceback"""
 
3295
            tb = tb or sys.exc_info()[2]
 
3296
            if tb is not None:
 
3297
                next = tb.tb_next
 
3298
                while next is not None:
 
3299
                    tb = next
 
3300
                    next = next.tb_next
 
3301
                self.postcode = tb.tb_frame.f_code
 
3302
        def report_error(self, test, err):
 
3303
            pass
 
3304
        def report_failure(self, test, err):
 
3305
            pass
 
3306
 
 
3307
    def test_location_unittest_error(self):
 
3308
        """Needs right post mortem traceback with erroring unittest case"""
 
3309
        class Test(unittest.TestCase):
 
3310
            def runTest(self):
 
3311
                raise RuntimeError
 
3312
        result = self.TracebackRecordingResult()
 
3313
        Test().run(result)
 
3314
        self.assertEqual(result.postcode, Test.runTest.__code__)
 
3315
 
 
3316
    def test_location_unittest_failure(self):
 
3317
        """Needs right post mortem traceback with failing unittest case"""
 
3318
        class Test(unittest.TestCase):
 
3319
            def runTest(self):
 
3320
                raise self.failureException
 
3321
        result = self.TracebackRecordingResult()
 
3322
        Test().run(result)
 
3323
        self.assertEqual(result.postcode, Test.runTest.__code__)
 
3324
 
 
3325
    def test_location_bt_error(self):
 
3326
        """Needs right post mortem traceback with erroring breezy.tests case"""
 
3327
        class Test(tests.TestCase):
 
3328
            def test_error(self):
 
3329
                raise RuntimeError
 
3330
        result = self.TracebackRecordingResult()
 
3331
        Test("test_error").run(result)
 
3332
        self.assertEqual(result.postcode, Test.test_error.__code__)
 
3333
 
 
3334
    def test_location_bt_failure(self):
 
3335
        """Needs right post mortem traceback with failing breezy.tests case"""
 
3336
        class Test(tests.TestCase):
 
3337
            def test_failure(self):
 
3338
                raise self.failureException
 
3339
        result = self.TracebackRecordingResult()
 
3340
        Test("test_failure").run(result)
 
3341
        self.assertEqual(result.postcode, Test.test_failure.__code__)
 
3342
 
 
3343
    def test_env_var_triggers_post_mortem(self):
 
3344
        """Check pdb.post_mortem is called iff BRZ_TEST_PDB is set"""
 
3345
        import pdb
 
3346
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
 
3347
        post_mortem_calls = []
 
3348
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
 
3349
        self.overrideEnv('BRZ_TEST_PDB', None)
 
3350
        result._post_mortem(1)
 
3351
        self.overrideEnv('BRZ_TEST_PDB', 'on')
 
3352
        result._post_mortem(2)
 
3353
        self.assertEqual([2], post_mortem_calls)
2961
3354
 
2962
3355
 
2963
3356
class TestRunSuite(tests.TestCase):
2976
3369
                                                self.verbosity)
2977
3370
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2978
3371
        self.assertLength(1, calls)
 
3372
 
 
3373
 
 
3374
class _Selftest(object):
 
3375
    """Mixin for tests needing full selftest output"""
 
3376
 
 
3377
    def _inject_stream_into_subunit(self, stream):
 
3378
        """To be overridden by subclasses that run tests out of process"""
 
3379
 
 
3380
    def _run_selftest(self, **kwargs):
 
3381
        if PY3:
 
3382
            bio = BytesIO()
 
3383
            sio = TextIOWrapper(bio, 'utf-8')
 
3384
        else:
 
3385
            sio = bio = StringIO()
 
3386
        self._inject_stream_into_subunit(bio)
 
3387
        tests.selftest(stream=sio, stop_on_failure=False, **kwargs)
 
3388
        sio.flush()
 
3389
        return bio.getvalue()
 
3390
 
 
3391
 
 
3392
class _ForkedSelftest(_Selftest):
 
3393
    """Mixin for tests needing full selftest output with forked children"""
 
3394
 
 
3395
    _test_needs_features = [features.subunit]
 
3396
 
 
3397
    def _inject_stream_into_subunit(self, stream):
 
3398
        """Monkey-patch subunit so the extra output goes to stream not stdout
 
3399
 
 
3400
        Some APIs need rewriting so this kind of bogus hackery can be replaced
 
3401
        by passing the stream param from run_tests down into ProtocolTestCase.
 
3402
        """
 
3403
        from subunit import ProtocolTestCase
 
3404
        _original_init = ProtocolTestCase.__init__
 
3405
        def _init_with_passthrough(self, *args, **kwargs):
 
3406
            _original_init(self, *args, **kwargs)
 
3407
            self._passthrough = stream
 
3408
        self.overrideAttr(ProtocolTestCase, "__init__", _init_with_passthrough)
 
3409
 
 
3410
    def _run_selftest(self, **kwargs):
 
3411
        # GZ 2011-05-26: Add a PosixSystem feature so this check can go away
 
3412
        if getattr(os, "fork", None) is None:
 
3413
            raise tests.TestNotApplicable("Platform doesn't support forking")
 
3414
        # Make sure the fork code is actually invoked by claiming two cores
 
3415
        self.overrideAttr(osutils, "local_concurrency", lambda: 2)
 
3416
        kwargs.setdefault("suite_decorators", []).append(tests.fork_decorator)
 
3417
        return super(_ForkedSelftest, self)._run_selftest(**kwargs)
 
3418
 
 
3419
 
 
3420
class TestParallelFork(_ForkedSelftest, tests.TestCase):
 
3421
    """Check operation of --parallel=fork selftest option"""
 
3422
 
 
3423
    def test_error_in_child_during_fork(self):
 
3424
        """Error in a forked child during test setup should get reported"""
 
3425
        class Test(tests.TestCase):
 
3426
            def testMethod(self):
 
3427
                pass
 
3428
        # We don't care what, just break something that a child will run
 
3429
        self.overrideAttr(tests, "workaround_zealous_crypto_random", None)
 
3430
        out = self._run_selftest(test_suite_factory=Test)
 
3431
        # Lines from the tracebacks of the two child processes may be mixed
 
3432
        # together due to the way subunit parses and forwards the streams,
 
3433
        # so permit extra lines between each part of the error output.
 
3434
        self.assertContainsRe(out,
 
3435
            b"Traceback.*:\n"
 
3436
            b"(?:.*\n)*"
 
3437
            b".+ in fork_for_tests\n"
 
3438
            b"(?:.*\n)*"
 
3439
            b"\\s*workaround_zealous_crypto_random\\(\\)\n"
 
3440
            b"(?:.*\n)*"
 
3441
            b"TypeError:")
 
3442
 
 
3443
 
 
3444
class TestUncollectedWarnings(_Selftest, tests.TestCase):
 
3445
    """Check a test case still alive after being run emits a warning"""
 
3446
 
 
3447
    class Test(tests.TestCase):
 
3448
        def test_pass(self):
 
3449
            pass
 
3450
        def test_self_ref(self):
 
3451
            self.also_self = self.test_self_ref
 
3452
        def test_skip(self):
 
3453
            self.skipTest("Don't need")
 
3454
 
 
3455
    def _get_suite(self):
 
3456
        return TestUtil.TestSuite([
 
3457
            self.Test("test_pass"),
 
3458
            self.Test("test_self_ref"),
 
3459
            self.Test("test_skip"),
 
3460
            ])
 
3461
 
 
3462
    def _run_selftest_with_suite(self, **kwargs):
 
3463
        old_flags = tests.selftest_debug_flags
 
3464
        tests.selftest_debug_flags = old_flags.union(["uncollected_cases"])
 
3465
        gc_on = gc.isenabled()
 
3466
        if gc_on:
 
3467
            gc.disable()
 
3468
        try:
 
3469
            output = self._run_selftest(test_suite_factory=self._get_suite,
 
3470
                **kwargs)
 
3471
        finally:
 
3472
            if gc_on:
 
3473
                gc.enable()
 
3474
            tests.selftest_debug_flags = old_flags
 
3475
        self.assertNotContainsRe(output, b"Uncollected test case.*test_pass")
 
3476
        self.assertContainsRe(output, b"Uncollected test case.*test_self_ref")
 
3477
        return output
 
3478
 
 
3479
    def test_testsuite(self):
 
3480
        self._run_selftest_with_suite()
 
3481
 
 
3482
    def test_pattern(self):
 
3483
        out = self._run_selftest_with_suite(pattern="test_(?:pass|self_ref)$")
 
3484
        self.assertNotContainsRe(out, b"test_skip")
 
3485
 
 
3486
    def test_exclude_pattern(self):
 
3487
        out = self._run_selftest_with_suite(exclude_pattern="test_skip$")
 
3488
        self.assertNotContainsRe(out, b"test_skip")
 
3489
 
 
3490
    def test_random_seed(self):
 
3491
        self._run_selftest_with_suite(random_seed="now")
 
3492
 
 
3493
    def test_matching_tests_first(self):
 
3494
        self._run_selftest_with_suite(matching_tests_first=True,
 
3495
            pattern="test_self_ref$")
 
3496
 
 
3497
    def test_starting_with_and_exclude(self):
 
3498
        out = self._run_selftest_with_suite(starting_with=["bt."],
 
3499
            exclude_pattern="test_skip$")
 
3500
        self.assertNotContainsRe(out, b"test_skip")
 
3501
 
 
3502
    def test_additonal_decorator(self):
 
3503
        out = self._run_selftest_with_suite(
 
3504
            suite_decorators=[tests.TestDecorator])
 
3505
 
 
3506
 
 
3507
class TestUncollectedWarningsSubunit(TestUncollectedWarnings):
 
3508
    """Check warnings from tests staying alive are emitted with subunit"""
 
3509
 
 
3510
    _test_needs_features = [features.subunit]
 
3511
 
 
3512
    def _run_selftest_with_suite(self, **kwargs):
 
3513
        return TestUncollectedWarnings._run_selftest_with_suite(
 
3514
            self, runner_class=tests.SubUnitBzrRunnerv1, **kwargs)
 
3515
 
 
3516
 
 
3517
class TestUncollectedWarningsForked(_ForkedSelftest, TestUncollectedWarnings):
 
3518
    """Check warnings from tests staying alive are emitted when forking"""
 
3519
 
 
3520
 
 
3521
class TestEnvironHandling(tests.TestCase):
 
3522
 
 
3523
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
 
3524
        self.assertFalse('MYVAR' in os.environ)
 
3525
        self.overrideEnv('MYVAR', '42')
 
3526
        # We use an embedded test to make sure we fix the _captureVar bug
 
3527
        class Test(tests.TestCase):
 
3528
            def test_me(self):
 
3529
                # The first call save the 42 value
 
3530
                self.overrideEnv('MYVAR', None)
 
3531
                self.assertEqual(None, os.environ.get('MYVAR'))
 
3532
                # Make sure we can call it twice
 
3533
                self.overrideEnv('MYVAR', None)
 
3534
                self.assertEqual(None, os.environ.get('MYVAR'))
 
3535
        output = StringIO()
 
3536
        result = tests.TextTestResult(output, 0, 1)
 
3537
        Test('test_me').run(result)
 
3538
        if not result.wasStrictlySuccessful():
 
3539
            self.fail(output.getvalue())
 
3540
        # We get our value back
 
3541
        self.assertEqual('42', os.environ.get('MYVAR'))
 
3542
 
 
3543
 
 
3544
class TestIsolatedEnv(tests.TestCase):
 
3545
    """Test isolating tests from os.environ.
 
3546
 
 
3547
    Since we use tests that are already isolated from os.environ a bit of care
 
3548
    should be taken when designing the tests to avoid bootstrap side-effects.
 
3549
    The tests start an already clean os.environ which allow doing valid
 
3550
    assertions about which variables are present or not and design tests around
 
3551
    these assertions.
 
3552
    """
 
3553
 
 
3554
    class ScratchMonkey(tests.TestCase):
 
3555
 
 
3556
        def test_me(self):
 
3557
            pass
 
3558
 
 
3559
    def test_basics(self):
 
3560
        # Make sure we know the definition of BRZ_HOME: not part of os.environ
 
3561
        # for tests.TestCase.
 
3562
        self.assertTrue('BRZ_HOME' in tests.isolated_environ)
 
3563
        self.assertEqual(None, tests.isolated_environ['BRZ_HOME'])
 
3564
        # Being part of isolated_environ, BRZ_HOME should not appear here
 
3565
        self.assertFalse('BRZ_HOME' in os.environ)
 
3566
        # Make sure we know the definition of LINES: part of os.environ for
 
3567
        # tests.TestCase
 
3568
        self.assertTrue('LINES' in tests.isolated_environ)
 
3569
        self.assertEqual('25', tests.isolated_environ['LINES'])
 
3570
        self.assertEqual('25', os.environ['LINES'])
 
3571
 
 
3572
    def test_injecting_unknown_variable(self):
 
3573
        # BRZ_HOME is known to be absent from os.environ
 
3574
        test = self.ScratchMonkey('test_me')
 
3575
        tests.override_os_environ(test, {'BRZ_HOME': 'foo'})
 
3576
        self.assertEqual('foo', os.environ['BRZ_HOME'])
 
3577
        tests.restore_os_environ(test)
 
3578
        self.assertFalse('BRZ_HOME' in os.environ)
 
3579
 
 
3580
    def test_injecting_known_variable(self):
 
3581
        test = self.ScratchMonkey('test_me')
 
3582
        # LINES is known to be present in os.environ
 
3583
        tests.override_os_environ(test, {'LINES': '42'})
 
3584
        self.assertEqual('42', os.environ['LINES'])
 
3585
        tests.restore_os_environ(test)
 
3586
        self.assertEqual('25', os.environ['LINES'])
 
3587
 
 
3588
    def test_deleting_variable(self):
 
3589
        test = self.ScratchMonkey('test_me')
 
3590
        # LINES is known to be present in os.environ
 
3591
        tests.override_os_environ(test, {'LINES': None})
 
3592
        self.assertTrue('LINES' not in os.environ)
 
3593
        tests.restore_os_environ(test)
 
3594
        self.assertEqual('25', os.environ['LINES'])
 
3595
 
 
3596
 
 
3597
class TestDocTestSuiteIsolation(tests.TestCase):
 
3598
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
 
3599
 
 
3600
    Since tests.TestCase alreay provides an isolation from os.environ, we use
 
3601
    the clean environment as a base for testing. To precisely capture the
 
3602
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
 
3603
    compare against.
 
3604
 
 
3605
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
 
3606
    not `os.environ` so each test overrides it to suit its needs.
 
3607
 
 
3608
    """
 
3609
 
 
3610
    def get_doctest_suite_for_string(self, klass, string):
 
3611
        class Finder(doctest.DocTestFinder):
 
3612
 
 
3613
            def find(*args, **kwargs):
 
3614
                test = doctest.DocTestParser().get_doctest(
 
3615
                    string, {}, 'foo', 'foo.py', 0)
 
3616
                return [test]
 
3617
 
 
3618
        suite = klass(test_finder=Finder())
 
3619
        return suite
 
3620
 
 
3621
    def run_doctest_suite_for_string(self, klass, string):
 
3622
        suite = self.get_doctest_suite_for_string(klass, string)
 
3623
        output = StringIO()
 
3624
        result = tests.TextTestResult(output, 0, 1)
 
3625
        suite.run(result)
 
3626
        return result, output
 
3627
 
 
3628
    def assertDocTestStringSucceds(self, klass, string):
 
3629
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3630
        if not result.wasStrictlySuccessful():
 
3631
            self.fail(output.getvalue())
 
3632
 
 
3633
    def assertDocTestStringFails(self, klass, string):
 
3634
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3635
        if result.wasStrictlySuccessful():
 
3636
            self.fail(output.getvalue())
 
3637
 
 
3638
    def test_injected_variable(self):
 
3639
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
 
3640
        test = """
 
3641
            >>> import os
 
3642
            >>> os.environ['LINES']
 
3643
            '42'
 
3644
            """
 
3645
        # doctest.DocTestSuite fails as it sees '25'
 
3646
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3647
        # tests.DocTestSuite sees '42'
 
3648
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3649
 
 
3650
    def test_deleted_variable(self):
 
3651
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
 
3652
        test = """
 
3653
            >>> import os
 
3654
            >>> os.environ.get('LINES')
 
3655
            """
 
3656
        # doctest.DocTestSuite fails as it sees '25'
 
3657
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3658
        # tests.DocTestSuite sees None
 
3659
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3660
 
 
3661
 
 
3662
class TestSelftestExcludePatterns(tests.TestCase):
 
3663
 
 
3664
    def setUp(self):
 
3665
        super(TestSelftestExcludePatterns, self).setUp()
 
3666
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
 
3667
 
 
3668
    def suite_factory(self, keep_only=None, starting_with=None):
 
3669
        """A test suite factory with only a few tests."""
 
3670
        class Test(tests.TestCase):
 
3671
            def id(self):
 
3672
                # We don't need the full class path
 
3673
                return self._testMethodName
 
3674
            def a(self):
 
3675
                pass
 
3676
            def b(self):
 
3677
                pass
 
3678
            def c(self):
 
3679
                pass
 
3680
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
3681
 
 
3682
    def assertTestList(self, expected, *selftest_args):
 
3683
        # We rely on setUp installing the right test suite factory so we can
 
3684
        # test at the command level without loading the whole test suite
 
3685
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
 
3686
        actual = out.splitlines()
 
3687
        self.assertEqual(expected, actual)
 
3688
 
 
3689
    def test_full_list(self):
 
3690
        self.assertTestList(['a', 'b', 'c'])
 
3691
 
 
3692
    def test_single_exclude(self):
 
3693
        self.assertTestList(['b', 'c'], '-x', 'a')
 
3694
 
 
3695
    def test_mutiple_excludes(self):
 
3696
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
 
3697
 
 
3698
 
 
3699
class TestCounterHooks(tests.TestCase, SelfTestHelper):
 
3700
 
 
3701
    _test_needs_features = [features.subunit]
 
3702
 
 
3703
    def setUp(self):
 
3704
        super(TestCounterHooks, self).setUp()
 
3705
        class Test(tests.TestCase):
 
3706
 
 
3707
            def setUp(self):
 
3708
                super(Test, self).setUp()
 
3709
                self.hooks = hooks.Hooks()
 
3710
                self.hooks.add_hook('myhook', 'Foo bar blah', (2, 4))
 
3711
                self.install_counter_hook(self.hooks, 'myhook')
 
3712
 
 
3713
            def no_hook(self):
 
3714
                pass
 
3715
 
 
3716
            def run_hook_once(self):
 
3717
                for hook in self.hooks['myhook']:
 
3718
                    hook(self)
 
3719
 
 
3720
        self.test_class = Test
 
3721
 
 
3722
    def assertHookCalls(self, expected_calls, test_name):
 
3723
        test = self.test_class(test_name)
 
3724
        result = unittest.TestResult()
 
3725
        test.run(result)
 
3726
        self.assertTrue(hasattr(test, '_counters'))
 
3727
        self.assertTrue('myhook' in test._counters)
 
3728
        self.assertEqual(expected_calls, test._counters['myhook'])
 
3729
 
 
3730
    def test_no_hook(self):
 
3731
        self.assertHookCalls(0, 'no_hook')
 
3732
 
 
3733
    def test_run_hook_once(self):
 
3734
        tt = features.testtools
 
3735
        if tt.module.__version__ < (0, 9, 8):
 
3736
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
 
3737
        self.assertHookCalls(1, 'run_hook_once')