~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-11-04 18:51:39 UTC
  • mfrom: (2961.1.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20071104185139-kaio3sneodg2kp71
Authentication ring implementation (read-only)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 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
26
26
 
27
27
import bzrlib
28
28
from bzrlib import (
29
 
    branchbuilder,
30
29
    bzrdir,
31
30
    errors,
32
31
    memorytree,
33
32
    osutils,
34
 
    remote,
35
33
    repository,
36
34
    symbol_versioning,
37
 
    tests,
38
 
    workingtree,
39
35
    )
40
36
from bzrlib.progress import _BaseProgressBar
41
 
from bzrlib.repofmt import (
42
 
    pack_repo,
43
 
    weaverepo,
44
 
    )
 
37
from bzrlib.repofmt import weaverepo
45
38
from bzrlib.symbol_versioning import (
46
 
    one_zero,
47
 
    zero_eleven,
48
 
    zero_ten,
49
 
    )
 
39
        zero_ten,
 
40
        zero_eleven,
 
41
        )
50
42
from bzrlib.tests import (
51
43
                          ChrootedTestCase,
52
44
                          ExtendedTestResult,
62
54
                          TestUtil,
63
55
                          TextTestRunner,
64
56
                          UnavailableFeature,
65
 
                          condition_id_re,
66
 
                          condition_isinstance,
67
 
                          exclude_tests_by_condition,
68
 
                          exclude_tests_by_re,
69
 
                          filter_suite_by_condition,
 
57
                          iter_suite_tests,
70
58
                          filter_suite_by_re,
71
 
                          iter_suite_tests,
72
 
                          preserve_input,
73
 
                          randomize_suite,
74
 
                          split_suite_by_condition,
75
 
                          split_suite_by_re,
 
59
                          sort_suite_by_re,
76
60
                          test_lsprof,
77
61
                          test_suite,
78
62
                          )
83
67
from bzrlib.version import _get_bzr_source_tree
84
68
 
85
69
 
86
 
def _test_ids(test_suite):
87
 
    """Get the ids for the tests in a test suite."""
88
 
    return [t.id() for t in iter_suite_tests(test_suite)]
89
 
 
90
 
 
91
70
class SelftestTests(TestCase):
92
71
 
93
72
    def test_import_tests(self):
109
88
                              'a test message\n')
110
89
 
111
90
 
112
 
class TestUnicodeFilename(TestCase):
113
 
 
114
 
    def test_probe_passes(self):
115
 
        """UnicodeFilename._probe passes."""
116
 
        # We can't test much more than that because the behaviour depends
117
 
        # on the platform.
118
 
        tests.UnicodeFilename._probe()
119
 
 
120
 
 
121
91
class TestTreeShape(TestCaseInTempDir):
122
92
 
123
93
    def test_unicode_paths(self):
124
 
        self.requireFeature(tests.UnicodeFilename)
125
 
 
126
94
        filename = u'hell\u00d8'
127
 
        self.build_tree_contents([(filename, 'contents of hello')])
 
95
        try:
 
96
            self.build_tree_contents([(filename, 'contents of hello')])
 
97
        except UnicodeEncodeError:
 
98
            raise TestSkipped("can't build unicode working tree in "
 
99
                "filesystem encoding %s" % sys.getfilesystemencoding())
128
100
        self.failUnlessExists(filename)
129
101
 
130
102
 
139
111
    """
140
112
 
141
113
    def test_get_transport_permutations(self):
142
 
        # this checks that get_test_permutations defined by the module is
143
 
        # called by the adapter get_transport_test_permutations method.
 
114
        # this checks that we the module get_test_permutations call
 
115
        # is made by the adapter get_transport_test_permitations method.
144
116
        class MockModule(object):
145
117
            def get_test_permutations(self):
146
118
                return sample_permutation
152
124
                         adapter.get_transport_test_permutations(MockModule()))
153
125
 
154
126
    def test_adapter_checks_all_modules(self):
155
 
        # this checks that the adapter returns as many permutations as there
156
 
        # are in all the registered transport modules - we assume if this
157
 
        # matches its probably doing the right thing especially in combination
158
 
        # with the tests for setting the right classes below.
 
127
        # this checks that the adapter returns as many permurtations as
 
128
        # there are in all the registered# transport modules for there
 
129
        # - we assume if this matches its probably doing the right thing
 
130
        # especially in combination with the tests for setting the right
 
131
        # classes below.
159
132
        from bzrlib.tests.test_transport_implementations \
160
133
            import TransportTestProviderAdapter
161
134
        from bzrlib.transport import _get_transport_modules
247
220
            adapter.scenarios)
248
221
 
249
222
 
250
 
class TestRepositoryParameterisation(TestCase):
 
223
class TestRepositoryProviderAdapter(TestCase):
251
224
    """A group of tests that test the repository implementation test adapter."""
252
225
 
 
226
    def test_constructor(self):
 
227
        # check that constructor parameters are passed through to the
 
228
        # scenarios.
 
229
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
230
        server1 = "a"
 
231
        server2 = "b"
 
232
        formats = [("c", "C"), ("d", "D")]
 
233
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
 
234
        self.assertEqual([
 
235
            ('str',
 
236
             {'bzrdir_format': 'C',
 
237
              'repository_format': 'c',
 
238
              'transport_readonly_server': 'b',
 
239
              'transport_server': 'a'}),
 
240
            ('str',
 
241
             {'bzrdir_format': 'D',
 
242
              'repository_format': 'd',
 
243
              'transport_readonly_server': 'b',
 
244
              'transport_server': 'a'})],
 
245
            adapter.scenarios)
 
246
 
 
247
    def test_setting_vfs_transport(self):
 
248
        """The vfs_transport_factory can be set optionally."""
 
249
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
250
        formats = [("a", "b"), ("c", "d")]
 
251
        adapter = RepositoryTestProviderAdapter(None, None, formats,
 
252
            vfs_transport_factory="vfs")
 
253
        self.assertEqual([
 
254
            ('str',
 
255
             {'bzrdir_format': 'b',
 
256
              'repository_format': 'a',
 
257
              'transport_readonly_server': None,
 
258
              'transport_server': None,
 
259
              'vfs_transport_factory': 'vfs'}),
 
260
            ('str',
 
261
             {'bzrdir_format': 'd',
 
262
              'repository_format': 'c',
 
263
              'transport_readonly_server': None,
 
264
              'transport_server': None,
 
265
              'vfs_transport_factory': 'vfs'})],
 
266
            adapter.scenarios)
 
267
 
253
268
    def test_formats_to_scenarios(self):
254
269
        """The adapter can generate all the scenarios needed."""
255
 
        from bzrlib.tests.repository_implementations import formats_to_scenarios
256
 
        formats = [("(c)", remote.RemoteRepositoryFormat()),
257
 
                   ("(d)", repository.format_registry.get(
258
 
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
259
 
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
260
 
            None)
261
 
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
262
 
            vfs_transport_factory="vfs")
263
 
        # no_vfs generate scenarios without vfs_transport_factory
 
270
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
271
        no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
 
272
            [], None)
 
273
        vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
 
274
            [], vfs_transport_factory="vfs")
 
275
        # no_vfs generate scenarios without vfs_transport_factor
 
276
        formats = [("c", "C"), (1, "D")]
264
277
        self.assertEqual([
265
 
            ('RemoteRepositoryFormat(c)',
266
 
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
267
 
              'repository_format': remote.RemoteRepositoryFormat(),
 
278
            ('str',
 
279
             {'bzrdir_format': 'C',
 
280
              'repository_format': 'c',
268
281
              'transport_readonly_server': 'readonly',
269
282
              'transport_server': 'server'}),
270
 
            ('RepositoryFormatKnitPack1(d)',
271
 
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
272
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
283
            ('int',
 
284
             {'bzrdir_format': 'D',
 
285
              'repository_format': 1,
273
286
              'transport_readonly_server': 'readonly',
274
287
              'transport_server': 'server'})],
275
 
            no_vfs_scenarios)
 
288
            no_vfs_adapter.formats_to_scenarios(formats))
276
289
        self.assertEqual([
277
 
            ('RemoteRepositoryFormat(c)',
278
 
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
279
 
              'repository_format': remote.RemoteRepositoryFormat(),
 
290
            ('str',
 
291
             {'bzrdir_format': 'C',
 
292
              'repository_format': 'c',
280
293
              'transport_readonly_server': 'readonly',
281
294
              'transport_server': 'server',
282
295
              'vfs_transport_factory': 'vfs'}),
283
 
            ('RepositoryFormatKnitPack1(d)',
284
 
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
285
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
296
            ('int',
 
297
             {'bzrdir_format': 'D',
 
298
              'repository_format': 1,
286
299
              'transport_readonly_server': 'readonly',
287
300
              'transport_server': 'server',
288
301
              'vfs_transport_factory': 'vfs'})],
289
 
            vfs_scenarios)
 
302
            vfs_adapter.formats_to_scenarios(formats))
290
303
 
291
304
 
292
305
class TestTestScenarioApplier(TestCase):
353
366
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
354
367
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
355
368
        self.assertEqual([
356
 
            ('str,str,str',
 
369
            ('str',
357
370
             {'interrepo_class': str,
358
371
              'repository_format': 'C1',
359
372
              'repository_format_to': 'C2',
360
373
              'transport_readonly_server': 'b',
361
374
              'transport_server': 'a'}),
362
 
            ('int,str,str',
 
375
            ('int',
363
376
             {'interrepo_class': int,
364
377
              'repository_format': 'D1',
365
378
              'repository_format_to': 'D2',
368
381
            adapter.formats_to_scenarios(formats))
369
382
 
370
383
 
 
384
class TestInterVersionedFileProviderAdapter(TestCase):
 
385
    """A group of tests that test the InterVersionedFile test adapter."""
 
386
 
 
387
    def test_scenarios(self):
 
388
        # check that constructor parameters are passed through to the adapted
 
389
        # test.
 
390
        from bzrlib.tests.interversionedfile_implementations \
 
391
            import InterVersionedFileTestProviderAdapter
 
392
        server1 = "a"
 
393
        server2 = "b"
 
394
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
395
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
 
396
        self.assertEqual([
 
397
            ('str',
 
398
             {'interversionedfile_class':str,
 
399
              'transport_readonly_server': 'b',
 
400
              'transport_server': 'a',
 
401
              'versionedfile_factory': 'C1',
 
402
              'versionedfile_factory_to': 'C2'}),
 
403
            ('int',
 
404
             {'interversionedfile_class': int,
 
405
              'transport_readonly_server': 'b',
 
406
              'transport_server': 'a',
 
407
              'versionedfile_factory': 'D1',
 
408
              'versionedfile_factory_to': 'D2'})],
 
409
            adapter.scenarios)
 
410
 
 
411
 
 
412
class TestRevisionStoreProviderAdapter(TestCase):
 
413
    """A group of tests that test the RevisionStore test adapter."""
 
414
 
 
415
    def test_scenarios(self):
 
416
        # check that constructor parameters are passed through to the adapted
 
417
        # test.
 
418
        from bzrlib.tests.revisionstore_implementations \
 
419
            import RevisionStoreTestProviderAdapter
 
420
        # revision stores need a store factory - i.e. RevisionKnit
 
421
        #, a readonly and rw transport 
 
422
        # transport servers:
 
423
        server1 = "a"
 
424
        server2 = "b"
 
425
        store_factories = ["c", "d"]
 
426
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
 
427
        self.assertEqual([
 
428
            ('c',
 
429
             {'store_factory': 'c',
 
430
              'transport_readonly_server': 'b',
 
431
              'transport_server': 'a'}),
 
432
            ('d',
 
433
             {'store_factory': 'd',
 
434
              'transport_readonly_server': 'b',
 
435
              'transport_server': 'a'})],
 
436
            adapter.scenarios)
 
437
 
 
438
 
371
439
class TestWorkingTreeProviderAdapter(TestCase):
372
440
    """A group of tests that test the workingtree implementation test adapter."""
373
441
 
378
446
            import WorkingTreeTestProviderAdapter
379
447
        server1 = "a"
380
448
        server2 = "b"
381
 
        formats = [workingtree.WorkingTreeFormat2(),
382
 
                   workingtree.WorkingTreeFormat3(),]
 
449
        formats = [("c", "C"), ("d", "D")]
383
450
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
384
451
        self.assertEqual([
385
 
            ('WorkingTreeFormat2',
386
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
387
 
              'transport_readonly_server': 'b',
388
 
              'transport_server': 'a',
389
 
              'workingtree_format': formats[0]}),
390
 
            ('WorkingTreeFormat3',
391
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
392
 
              'transport_readonly_server': 'b',
393
 
              'transport_server': 'a',
394
 
              'workingtree_format': formats[1]})],
 
452
            ('str',
 
453
             {'bzrdir_format': 'C',
 
454
              'transport_readonly_server': 'b',
 
455
              'transport_server': 'a',
 
456
              'workingtree_format': 'c'}),
 
457
            ('str',
 
458
             {'bzrdir_format': 'D',
 
459
              'transport_readonly_server': 'b',
 
460
              'transport_server': 'a',
 
461
              'workingtree_format': 'd'})],
395
462
            adapter.scenarios)
396
463
 
397
464
 
411
478
            return_parameter,
412
479
            revision_tree_from_workingtree
413
480
            )
 
481
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
414
482
        input_test = TestTreeProviderAdapter(
415
483
            "test_adapted_tests")
416
484
        server1 = "a"
417
485
        server2 = "b"
418
 
        formats = [workingtree.WorkingTreeFormat2(),
419
 
                   workingtree.WorkingTreeFormat3(),]
 
486
        formats = [("c", "C"), ("d", "D")]
420
487
        adapter = TreeTestProviderAdapter(server1, server2, formats)
421
488
        suite = adapter.adapt(input_test)
422
489
        tests = list(iter(suite))
423
 
        # XXX We should not have tests fail as we add more scenarios
424
 
        # abentley 20080412
425
 
        self.assertEqual(6, len(tests))
 
490
        self.assertEqual(4, len(tests))
426
491
        # this must match the default format setp up in
427
492
        # TreeTestProviderAdapter.adapt
428
 
        default_format = workingtree.WorkingTreeFormat3
429
 
        self.assertEqual(tests[0].workingtree_format, formats[0])
430
 
        self.assertEqual(tests[0].bzrdir_format, formats[0]._matchingbzrdir)
 
493
        default_format = WorkingTreeFormat3
 
494
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
495
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
431
496
        self.assertEqual(tests[0].transport_server, server1)
432
497
        self.assertEqual(tests[0].transport_readonly_server, server2)
433
 
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
434
 
        self.assertEqual(tests[1].workingtree_format, formats[1])
435
 
        self.assertEqual(tests[1].bzrdir_format, formats[1]._matchingbzrdir)
 
498
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
499
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
500
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
436
501
        self.assertEqual(tests[1].transport_server, server1)
437
502
        self.assertEqual(tests[1].transport_readonly_server, server2)
438
 
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
 
503
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
439
504
        self.assertIsInstance(tests[2].workingtree_format, default_format)
440
505
        #self.assertEqual(tests[2].bzrdir_format,
441
506
        #                 default_format._matchingbzrdir)
442
507
        self.assertEqual(tests[2].transport_server, server1)
443
508
        self.assertEqual(tests[2].transport_readonly_server, server2)
444
 
        self.assertEqual(tests[2]._workingtree_to_test_tree,
 
509
        self.assertEqual(tests[2].workingtree_to_test_tree,
445
510
            revision_tree_from_workingtree)
446
511
 
447
512
 
456
521
        # because each optimiser can be direction specific, we need to test
457
522
        # each optimiser in its chosen direction.
458
523
        # unlike the TestProviderAdapter we dont want to automatically add a
459
 
        # parameterized one for WorkingTree - the optimisers will tell us what
 
524
        # parameterised one for WorkingTree - the optimisers will tell us what
460
525
        # ones to add.
461
526
        from bzrlib.tests.tree_implementations import (
462
527
            return_parameter,
482
547
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
483
548
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
484
549
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
485
 
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
 
550
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
486
551
        self.assertEqual(tests[0].transport_server, server1)
487
552
        self.assertEqual(tests[0].transport_readonly_server, server2)
488
553
        self.assertEqual(tests[1].intertree_class, formats[1][0])
489
554
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
490
555
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
491
556
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
492
 
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
 
557
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
493
558
        self.assertEqual(tests[1].transport_server, server1)
494
559
        self.assertEqual(tests[1].transport_readonly_server, server2)
495
560
 
548
613
        self.assertEqual(format.repository_format.__class__,
549
614
            tree.branch.repository._format.__class__)
550
615
 
551
 
    def test_make_branch_builder(self):
552
 
        builder = self.make_branch_builder('dir')
553
 
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
554
 
        # Guard against regression into MemoryTransport leaking
555
 
        # files to disk instead of keeping them in memory.
556
 
        self.failIf(osutils.lexists('dir'))
557
 
 
558
 
    def test_make_branch_builder_with_format(self):
559
 
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
560
 
        # that the format objects are used.
561
 
        format = bzrdir.BzrDirMetaFormat1()
562
 
        repo_format = weaverepo.RepositoryFormat7()
563
 
        format.repository_format = repo_format
564
 
        builder = self.make_branch_builder('dir', format=format)
565
 
        the_branch = builder.get_branch()
566
 
        # Guard against regression into MemoryTransport leaking
567
 
        # files to disk instead of keeping them in memory.
568
 
        self.failIf(osutils.lexists('dir'))
569
 
        self.assertEqual(format.repository_format.__class__,
570
 
                         the_branch.repository._format.__class__)
571
 
        self.assertEqual(repo_format.get_format_string(),
572
 
                         self.get_transport().get_bytes(
573
 
                            'dir/.bzr/repository/format'))
574
 
 
575
 
    def test_make_branch_builder_with_format_name(self):
576
 
        builder = self.make_branch_builder('dir', format='knit')
577
 
        the_branch = builder.get_branch()
578
 
        # Guard against regression into MemoryTransport leaking
579
 
        # files to disk instead of keeping them in memory.
580
 
        self.failIf(osutils.lexists('dir'))
581
 
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
582
 
        self.assertEqual(dir_format.repository_format.__class__,
583
 
                         the_branch.repository._format.__class__)
584
 
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
585
 
                         self.get_transport().get_bytes(
586
 
                            'dir/.bzr/repository/format'))
587
 
 
588
616
    def test_safety_net(self):
589
617
        """No test should modify the safety .bzr directory.
590
618
 
619
647
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
620
648
 
621
649
    def test_get_readonly_url_http(self):
622
 
        from bzrlib.tests.http_server import HttpServer
 
650
        from bzrlib.tests.HttpServer import HttpServer
623
651
        from bzrlib.transport import get_transport
624
652
        from bzrlib.transport.local import LocalURLServer
625
653
        from bzrlib.transport.http import HttpTransportBase
643
671
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
644
672
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
645
673
 
646
 
    def test_make_branch_builder(self):
647
 
        builder = self.make_branch_builder('dir')
648
 
        rev_id = builder.build_commit()
649
 
        self.failUnlessExists('dir')
650
 
        a_dir = bzrdir.BzrDir.open('dir')
651
 
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
652
 
        a_branch = a_dir.open_branch()
653
 
        builder_branch = builder.get_branch()
654
 
        self.assertEqual(a_branch.base, builder_branch.base)
655
 
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
656
 
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
657
 
 
658
674
 
659
675
class TestTestCaseTransports(TestCaseWithTransport):
660
676
 
890
906
        test.run(result)
891
907
        self.assertEqual(
892
908
            [
893
 
            ('update', '[2 in 0s] passing_test', None, None),
 
909
            ('update', '[2 in 0s, 3 known failures] passing_test', None, None),
894
910
            ],
895
911
            pb.calls[2:])
896
912
 
966
982
        test.run(result)
967
983
        self.assertEqual(
968
984
            [
969
 
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
 
985
            ('update', '[2 in 0s, 2 missing features] passing_test', None, None),
970
986
            ],
971
987
            pb.calls[1:])
972
988
    
1017
1033
        self.assertEqual(None, result._extractBenchmarkTime(test))
1018
1034
 
1019
1035
 
1020
 
class TestUnicodeFilenameFeature(TestCase):
1021
 
 
1022
 
    def test_probe_passes(self):
1023
 
        """UnicodeFilenameFeature._probe passes."""
1024
 
        # We can't test much more than that because the behaviour depends
1025
 
        # on the platform.
1026
 
        tests.UnicodeFilenameFeature._probe()
1027
 
 
1028
 
 
1029
1036
class TestRunner(TestCase):
1030
1037
 
1031
1038
    def dummy_test(self):
1103
1110
        self.assertTrue(result.wasSuccessful())
1104
1111
 
1105
1112
    def test_skipped_from_setup(self):
1106
 
        calls = []
1107
1113
        class SkippedSetupTest(TestCase):
1108
1114
 
1109
1115
            def setUp(self):
1110
 
                calls.append('setUp')
 
1116
                self.counter = 1
1111
1117
                self.addCleanup(self.cleanup)
1112
1118
                raise TestSkipped('skipped setup')
1113
1119
 
1115
1121
                self.fail('test reached')
1116
1122
 
1117
1123
            def cleanup(self):
1118
 
                calls.append('cleanup')
 
1124
                self.counter -= 1
1119
1125
 
1120
1126
        runner = TextTestRunner(stream=self._log_file)
1121
1127
        test = SkippedSetupTest('test_skip')
1122
1128
        result = self.run_test_runner(runner, test)
1123
1129
        self.assertTrue(result.wasSuccessful())
1124
1130
        # Check if cleanup was called the right number of times.
1125
 
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1131
        self.assertEqual(0, test.counter)
1126
1132
 
1127
1133
    def test_skipped_from_test(self):
1128
 
        calls = []
1129
1134
        class SkippedTest(TestCase):
1130
1135
 
1131
1136
            def setUp(self):
1132
 
                calls.append('setUp')
 
1137
                self.counter = 1
1133
1138
                self.addCleanup(self.cleanup)
1134
1139
 
1135
1140
            def test_skip(self):
1136
1141
                raise TestSkipped('skipped test')
1137
1142
 
1138
1143
            def cleanup(self):
1139
 
                calls.append('cleanup')
 
1144
                self.counter -= 1
1140
1145
 
1141
1146
        runner = TextTestRunner(stream=self._log_file)
1142
1147
        test = SkippedTest('test_skip')
1143
1148
        result = self.run_test_runner(runner, test)
1144
1149
        self.assertTrue(result.wasSuccessful())
1145
1150
        # Check if cleanup was called the right number of times.
1146
 
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1151
        self.assertEqual(0, test.counter)
1147
1152
 
1148
1153
    def test_not_applicable(self):
1149
1154
        # run a test that is skipped because it's not applicable
1206
1211
            revision_id = workingtree.get_parent_ids()[0]
1207
1212
            self.assertEndsWith(output_string.rstrip(), revision_id)
1208
1213
 
1209
 
    def assertLogDeleted(self, test):
1210
 
        log = test._get_log()
1211
 
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1212
 
        self.assertEqual('', test._log_contents)
1213
 
        self.assertIs(None, test._log_file_name)
1214
 
 
1215
1214
    def test_success_log_deleted(self):
1216
1215
        """Successful tests have their log deleted"""
1217
1216
 
1225
1224
        test = LogTester('test_success')
1226
1225
        result = self.run_test_runner(runner, test)
1227
1226
 
1228
 
        self.assertLogDeleted(test)
1229
 
 
1230
 
    def test_skipped_log_deleted(self):
1231
 
        """Skipped tests have their log deleted"""
1232
 
 
1233
 
        class LogTester(TestCase):
1234
 
 
1235
 
            def test_skipped(self):
1236
 
                self.log('this will be removed\n')
1237
 
                raise tests.TestSkipped()
1238
 
 
1239
 
        sio = cStringIO.StringIO()
1240
 
        runner = TextTestRunner(stream=sio)
1241
 
        test = LogTester('test_skipped')
1242
 
        result = self.run_test_runner(runner, test)
1243
 
 
1244
 
        self.assertLogDeleted(test)
1245
 
 
1246
 
    def test_not_aplicable_log_deleted(self):
1247
 
        """Not applicable tests have their log deleted"""
1248
 
 
1249
 
        class LogTester(TestCase):
1250
 
 
1251
 
            def test_not_applicable(self):
1252
 
                self.log('this will be removed\n')
1253
 
                raise tests.TestNotApplicable()
1254
 
 
1255
 
        sio = cStringIO.StringIO()
1256
 
        runner = TextTestRunner(stream=sio)
1257
 
        test = LogTester('test_not_applicable')
1258
 
        result = self.run_test_runner(runner, test)
1259
 
 
1260
 
        self.assertLogDeleted(test)
1261
 
 
1262
 
    def test_known_failure_log_deleted(self):
1263
 
        """Know failure tests have their log deleted"""
1264
 
 
1265
 
        class LogTester(TestCase):
1266
 
 
1267
 
            def test_known_failure(self):
1268
 
                self.log('this will be removed\n')
1269
 
                raise tests.KnownFailure()
1270
 
 
1271
 
        sio = cStringIO.StringIO()
1272
 
        runner = TextTestRunner(stream=sio)
1273
 
        test = LogTester('test_known_failure')
1274
 
        result = self.run_test_runner(runner, test)
1275
 
 
1276
 
        self.assertLogDeleted(test)
 
1227
        log = test._get_log()
 
1228
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1229
        self.assertEqual('', test._log_contents)
 
1230
        self.assertIs(None, test._log_file_name)
1277
1231
 
1278
1232
    def test_fail_log_kept(self):
1279
1233
        """Failed tests have their log kept"""
1325
1279
    def _test_pass(self):
1326
1280
        pass
1327
1281
 
1328
 
class _TestException(Exception):
1329
 
    pass
1330
1282
 
1331
1283
class TestTestCase(TestCase):
1332
1284
    """Tests that test the core bzrlib TestCase."""
1490
1442
            ],
1491
1443
            result.calls)
1492
1444
 
1493
 
    def test_assert_list_raises_on_generator(self):
1494
 
        def generator_which_will_raise():
1495
 
            # This will not raise until after the first yield
1496
 
            yield 1
1497
 
            raise _TestException()
1498
 
 
1499
 
        e = self.assertListRaises(_TestException, generator_which_will_raise)
1500
 
        self.assertIsInstance(e, _TestException)
1501
 
 
1502
 
        e = self.assertListRaises(Exception, generator_which_will_raise)
1503
 
        self.assertIsInstance(e, _TestException)
1504
 
 
1505
 
    def test_assert_list_raises_on_plain(self):
1506
 
        def plain_exception():
1507
 
            raise _TestException()
1508
 
            return []
1509
 
 
1510
 
        e = self.assertListRaises(_TestException, plain_exception)
1511
 
        self.assertIsInstance(e, _TestException)
1512
 
 
1513
 
        e = self.assertListRaises(Exception, plain_exception)
1514
 
        self.assertIsInstance(e, _TestException)
1515
 
 
1516
 
    def test_assert_list_raises_assert_wrong_exception(self):
1517
 
        class _NotTestException(Exception):
1518
 
            pass
1519
 
 
1520
 
        def wrong_exception():
1521
 
            raise _NotTestException()
1522
 
 
1523
 
        def wrong_exception_generator():
1524
 
            yield 1
1525
 
            yield 2
1526
 
            raise _NotTestException()
1527
 
 
1528
 
        # Wrong exceptions are not intercepted
1529
 
        self.assertRaises(_NotTestException,
1530
 
            self.assertListRaises, _TestException, wrong_exception)
1531
 
        self.assertRaises(_NotTestException,
1532
 
            self.assertListRaises, _TestException, wrong_exception_generator)
1533
 
 
1534
 
    def test_assert_list_raises_no_exception(self):
1535
 
        def success():
1536
 
            return []
1537
 
 
1538
 
        def success_generator():
1539
 
            yield 1
1540
 
            yield 2
1541
 
 
1542
 
        self.assertRaises(AssertionError,
1543
 
            self.assertListRaises, _TestException, success)
1544
 
 
1545
 
        self.assertRaises(AssertionError,
1546
 
            self.assertListRaises, _TestException, success_generator)
1547
 
 
1548
1445
 
1549
1446
@symbol_versioning.deprecated_function(zero_eleven)
1550
1447
def sample_deprecated_function():
1763
1660
        self.loader = TestUtil.TestLoader()
1764
1661
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1765
1662
            'bzrlib.tests.test_selftest']))
1766
 
        self.all_names = _test_ids(self.suite)
1767
 
 
1768
 
    def test_condition_id_re(self):
1769
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1770
 
            'test_condition_id_re')
1771
 
        filtered_suite = filter_suite_by_condition(self.suite,
1772
 
            condition_id_re('test_condition_id_re'))
1773
 
        self.assertEqual([test_name], _test_ids(filtered_suite))
1774
 
 
1775
 
    def test_condition_id_in_list(self):
1776
 
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1777
 
                      'test_condition_id_in_list']
1778
 
        id_list = tests.TestIdList(test_names)
1779
 
        filtered_suite = filter_suite_by_condition(
1780
 
            self.suite, tests.condition_id_in_list(id_list))
1781
 
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1782
 
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
1783
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1784
 
 
1785
 
    def test_condition_id_startswith(self):
1786
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1787
 
        start1 = klass + 'test_condition_id_starts'
1788
 
        start2 = klass + 'test_condition_id_in'
1789
 
        test_names = [ klass + 'test_condition_id_in_list',
1790
 
                      klass + 'test_condition_id_startswith',
1791
 
                     ]
1792
 
        filtered_suite = filter_suite_by_condition(
1793
 
            self.suite, tests.condition_id_startswith([start1, start2]))
1794
 
        self.assertEqual(test_names, _test_ids(filtered_suite))
1795
 
 
1796
 
    def test_condition_isinstance(self):
1797
 
        filtered_suite = filter_suite_by_condition(self.suite,
1798
 
            condition_isinstance(self.__class__))
1799
 
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1800
 
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
1801
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1802
 
 
1803
 
    def test_exclude_tests_by_condition(self):
1804
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1805
 
            'test_exclude_tests_by_condition')
1806
 
        filtered_suite = exclude_tests_by_condition(self.suite,
1807
 
            lambda x:x.id() == excluded_name)
1808
 
        self.assertEqual(len(self.all_names) - 1,
1809
 
            filtered_suite.countTestCases())
1810
 
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
1811
 
        remaining_names = list(self.all_names)
1812
 
        remaining_names.remove(excluded_name)
1813
 
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
1814
 
 
1815
 
    def test_exclude_tests_by_re(self):
1816
 
        self.all_names = _test_ids(self.suite)
1817
 
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1818
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1819
 
            'test_exclude_tests_by_re')
1820
 
        self.assertEqual(len(self.all_names) - 1,
1821
 
            filtered_suite.countTestCases())
1822
 
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
1823
 
        remaining_names = list(self.all_names)
1824
 
        remaining_names.remove(excluded_name)
1825
 
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
1826
 
 
1827
 
    def test_filter_suite_by_condition(self):
1828
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1829
 
            'test_filter_suite_by_condition')
1830
 
        filtered_suite = filter_suite_by_condition(self.suite,
1831
 
            lambda x:x.id() == test_name)
1832
 
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1663
        self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
1833
1664
 
1834
1665
    def test_filter_suite_by_re(self):
1835
 
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1836
 
        filtered_names = _test_ids(filtered_suite)
 
1666
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
 
1667
        filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
1837
1668
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1838
1669
            'TestSelftestFiltering.test_filter_suite_by_re'])
1839
 
 
1840
 
    def test_filter_suite_by_id_list(self):
1841
 
        test_list = ['bzrlib.tests.test_selftest.'
1842
 
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
1843
 
        filtered_suite = tests.filter_suite_by_id_list(
1844
 
            self.suite, tests.TestIdList(test_list))
1845
 
        filtered_names = _test_ids(filtered_suite)
1846
 
        self.assertEqual(
1847
 
            filtered_names,
1848
 
            ['bzrlib.tests.test_selftest.'
1849
 
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
1850
 
 
1851
 
    def test_filter_suite_by_id_startswith(self):
1852
 
        # By design this test may fail if another test is added whose name also
1853
 
        # begins with one of the start value used.
1854
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1855
 
        start1 = klass + 'test_filter_suite_by_id_starts'
1856
 
        start2 = klass + 'test_filter_suite_by_id_li'
1857
 
        test_list = [klass + 'test_filter_suite_by_id_list',
1858
 
                     klass + 'test_filter_suite_by_id_startswith',
1859
 
                     ]
1860
 
        filtered_suite = tests.filter_suite_by_id_startswith(
1861
 
            self.suite, [start1, start2])
1862
 
        self.assertEqual(
1863
 
            test_list,
1864
 
            _test_ids(filtered_suite),
1865
 
            )
1866
 
 
1867
 
    def test_preserve_input(self):
1868
 
        # NB: Surely this is something in the stdlib to do this?
1869
 
        self.assertTrue(self.suite is preserve_input(self.suite))
1870
 
        self.assertTrue("@#$" is preserve_input("@#$"))
1871
 
 
1872
 
    def test_randomize_suite(self):
1873
 
        randomized_suite = randomize_suite(self.suite)
1874
 
        # randomizing should not add or remove test names.
1875
 
        self.assertEqual(set(_test_ids(self.suite)),
1876
 
                         set(_test_ids(randomized_suite)))
1877
 
        # Technically, this *can* fail, because random.shuffle(list) can be
1878
 
        # equal to list. Trying multiple times just pushes the frequency back.
1879
 
        # As its len(self.all_names)!:1, the failure frequency should be low
1880
 
        # enough to ignore. RBC 20071021.
1881
 
        # It should change the order.
1882
 
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
1883
 
        # But not the length. (Possibly redundant with the set test, but not
1884
 
        # necessarily.)
1885
 
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
1886
 
 
1887
 
    def test_split_suit_by_condition(self):
1888
 
        self.all_names = _test_ids(self.suite)
1889
 
        condition = condition_id_re('test_filter_suite_by_r')
1890
 
        split_suite = split_suite_by_condition(self.suite, condition)
1891
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1892
 
            'test_filter_suite_by_re')
1893
 
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1894
 
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
1895
 
        remaining_names = list(self.all_names)
1896
 
        remaining_names.remove(filtered_name)
1897
 
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1898
 
 
1899
 
    def test_split_suit_by_re(self):
1900
 
        self.all_names = _test_ids(self.suite)
1901
 
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
1902
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1903
 
            'test_filter_suite_by_re')
1904
 
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1905
 
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
1906
 
        remaining_names = list(self.all_names)
1907
 
        remaining_names.remove(filtered_name)
1908
 
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
1670
            
 
1671
    def test_sort_suite_by_re(self):
 
1672
        sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
 
1673
        sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
 
1674
        self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
 
1675
            'TestSelftestFiltering.test_filter_suite_by_re')
 
1676
        self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1909
1677
 
1910
1678
 
1911
1679
class TestCheckInventoryShape(TestCaseWithTransport):
1945
1713
        # code.
1946
1714
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
1947
1715
        self.assertEqual(out, '')
1948
 
        self.assertContainsRe(err,
1949
 
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1950
 
 
1951
 
 
1952
 
class TestTestLoader(TestCase):
1953
 
    """Tests for the test loader."""
1954
 
 
1955
 
    def _get_loader_and_module(self):
1956
 
        """Gets a TestLoader and a module with one test in it."""
1957
 
        loader = TestUtil.TestLoader()
1958
 
        module = {}
1959
 
        class Stub(TestCase):
1960
 
            def test_foo(self):
1961
 
                pass
1962
 
        class MyModule(object):
1963
 
            pass
1964
 
        MyModule.a_class = Stub
1965
 
        module = MyModule()
1966
 
        return loader, module
1967
 
 
1968
 
    def test_module_no_load_tests_attribute_loads_classes(self):
1969
 
        loader, module = self._get_loader_and_module()
1970
 
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
1971
 
 
1972
 
    def test_module_load_tests_attribute_gets_called(self):
1973
 
        loader, module = self._get_loader_and_module()
1974
 
        # 'self' is here because we're faking the module with a class. Regular
1975
 
        # load_tests do not need that :)
1976
 
        def load_tests(self, standard_tests, module, loader):
1977
 
            result = loader.suiteClass()
1978
 
            for test in iter_suite_tests(standard_tests):
1979
 
                result.addTests([test, test])
1980
 
            return result
1981
 
        # add a load_tests() method which multiplies the tests from the module.
1982
 
        module.__class__.load_tests = load_tests
1983
 
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
1984
 
 
1985
 
    def test_load_tests_from_module_name_smoke_test(self):
1986
 
        loader = TestUtil.TestLoader()
1987
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
1988
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
1989
 
                          _test_ids(suite))
1990
 
 
1991
 
    def test_load_tests_from_module_name_with_bogus_module_name(self):
1992
 
        loader = TestUtil.TestLoader()
1993
 
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
1994
 
 
1995
 
 
1996
 
class TestTestIdList(tests.TestCase):
1997
 
 
1998
 
    def _create_id_list(self, test_list):
1999
 
        return tests.TestIdList(test_list)
2000
 
 
2001
 
    def _create_suite(self, test_id_list):
2002
 
 
2003
 
        class Stub(TestCase):
2004
 
            def test_foo(self):
2005
 
                pass
2006
 
 
2007
 
        def _create_test_id(id):
2008
 
            return lambda: id
2009
 
 
2010
 
        suite = TestUtil.TestSuite()
2011
 
        for id in test_id_list:
2012
 
            t  = Stub('test_foo')
2013
 
            t.id = _create_test_id(id)
2014
 
            suite.addTest(t)
2015
 
        return suite
2016
 
 
2017
 
    def _test_ids(self, test_suite):
2018
 
        """Get the ids for the tests in a test suite."""
2019
 
        return [t.id() for t in iter_suite_tests(test_suite)]
2020
 
 
2021
 
    def test_empty_list(self):
2022
 
        id_list = self._create_id_list([])
2023
 
        self.assertEquals({}, id_list.tests)
2024
 
        self.assertEquals({}, id_list.modules)
2025
 
 
2026
 
    def test_valid_list(self):
2027
 
        id_list = self._create_id_list(
2028
 
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
2029
 
             'mod1.func1', 'mod1.cl2.meth2',
2030
 
             'mod1.submod1',
2031
 
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2032
 
             ])
2033
 
        self.assertTrue(id_list.refers_to('mod1'))
2034
 
        self.assertTrue(id_list.refers_to('mod1.submod1'))
2035
 
        self.assertTrue(id_list.refers_to('mod1.submod2'))
2036
 
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2037
 
        self.assertTrue(id_list.includes('mod1.submod1'))
2038
 
        self.assertTrue(id_list.includes('mod1.func1'))
2039
 
 
2040
 
    def test_bad_chars_in_params(self):
2041
 
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2042
 
        self.assertTrue(id_list.refers_to('mod1'))
2043
 
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2044
 
 
2045
 
    def test_module_used(self):
2046
 
        id_list = self._create_id_list(['mod.class.meth'])
2047
 
        self.assertTrue(id_list.refers_to('mod'))
2048
 
        self.assertTrue(id_list.refers_to('mod.class'))
2049
 
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2050
 
 
2051
 
    def test_test_suite(self):
2052
 
        # This test is slow, so we do a single test with one test in each
2053
 
        # category
2054
 
        test_list = [
2055
 
            # testmod_names
2056
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2057
 
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
2058
 
            # transport implementations
2059
 
            'bzrlib.tests.test_transport_implementations.TransportTests'
2060
 
            '.test_abspath(LocalURLServer)',
2061
 
            # modules_to_doctest
2062
 
            'bzrlib.timestamp.format_highres_date',
2063
 
            # plugins can't be tested that way since selftest may be run with
2064
 
            # --no-plugins
2065
 
            ]
2066
 
        suite = tests.test_suite(test_list)
2067
 
        self.assertEquals(test_list, _test_ids(suite))
2068
 
 
2069
 
    def test_test_suite_matches_id_list_with_unknown(self):
2070
 
        loader = TestUtil.TestLoader()
2071
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2072
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2073
 
                     'bogus']
2074
 
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2075
 
        self.assertEquals(['bogus'], not_found)
2076
 
        self.assertEquals([], duplicates)
2077
 
 
2078
 
    def test_suite_matches_id_list_with_duplicates(self):
2079
 
        loader = TestUtil.TestLoader()
2080
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2081
 
        dupes = loader.suiteClass()
2082
 
        for test in iter_suite_tests(suite):
2083
 
            dupes.addTest(test)
2084
 
            dupes.addTest(test) # Add it again
2085
 
 
2086
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2087
 
        not_found, duplicates = tests.suite_matches_id_list(
2088
 
            dupes, test_list)
2089
 
        self.assertEquals([], not_found)
2090
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2091
 
                          duplicates)
2092
 
 
2093
 
 
2094
 
class TestLoadTestIdList(tests.TestCaseInTempDir):
2095
 
 
2096
 
    def _create_test_list_file(self, file_name, content):
2097
 
        fl = open(file_name, 'wt')
2098
 
        fl.write(content)
2099
 
        fl.close()
2100
 
 
2101
 
    def test_load_unknown(self):
2102
 
        self.assertRaises(errors.NoSuchFile,
2103
 
                          tests.load_test_id_list, 'i_do_not_exist')
2104
 
 
2105
 
    def test_load_test_list(self):
2106
 
        test_list_fname = 'test.list'
2107
 
        self._create_test_list_file(test_list_fname,
2108
 
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2109
 
        tlist = tests.load_test_id_list(test_list_fname)
2110
 
        self.assertEquals(2, len(tlist))
2111
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2112
 
        self.assertEquals('mod2.cl2.meth2', tlist[1])
2113
 
 
2114
 
    def test_load_dirty_file(self):
2115
 
        test_list_fname = 'test.list'
2116
 
        self._create_test_list_file(test_list_fname,
2117
 
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
2118
 
                                    'bar baz\n')
2119
 
        tlist = tests.load_test_id_list(test_list_fname)
2120
 
        self.assertEquals(4, len(tlist))
2121
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2122
 
        self.assertEquals('', tlist[1])
2123
 
        self.assertEquals('mod2.cl2.meth2', tlist[2])
2124
 
        self.assertEquals('bar baz', tlist[3])
2125
 
 
2126
 
 
2127
 
class TestFilteredByModuleTestLoader(tests.TestCase):
2128
 
 
2129
 
    def _create_loader(self, test_list):
2130
 
        id_filter = tests.TestIdList(test_list)
2131
 
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2132
 
        return loader
2133
 
 
2134
 
    def test_load_tests(self):
2135
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2136
 
        loader = self._create_loader(test_list)
2137
 
 
2138
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2139
 
        self.assertEquals(test_list, _test_ids(suite))
2140
 
 
2141
 
    def test_exclude_tests(self):
2142
 
        test_list = ['bogus']
2143
 
        loader = self._create_loader(test_list)
2144
 
 
2145
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2146
 
        self.assertEquals([], _test_ids(suite))
2147
 
 
2148
 
 
2149
 
class TestFilteredByNameStartTestLoader(tests.TestCase):
2150
 
 
2151
 
    def _create_loader(self, name_start):
2152
 
        def needs_module(name):
2153
 
            return name.startswith(name_start) or name_start.startswith(name)
2154
 
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2155
 
        return loader
2156
 
 
2157
 
    def test_load_tests(self):
2158
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2159
 
        loader = self._create_loader('bzrlib.tests.test_samp')
2160
 
 
2161
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2162
 
        self.assertEquals(test_list, _test_ids(suite))
2163
 
 
2164
 
    def test_load_tests_inside_module(self):
2165
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2166
 
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2167
 
 
2168
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2169
 
        self.assertEquals(test_list, _test_ids(suite))
2170
 
 
2171
 
    def test_exclude_tests(self):
2172
 
        test_list = ['bogus']
2173
 
        loader = self._create_loader('bogus')
2174
 
 
2175
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2176
 
        self.assertEquals([], _test_ids(suite))
2177
 
 
2178
 
 
2179
 
class TestTestPrefixRegistry(tests.TestCase):
2180
 
 
2181
 
    def _get_registry(self):
2182
 
        tp_registry = tests.TestPrefixAliasRegistry()
2183
 
        return tp_registry
2184
 
 
2185
 
    def test_register_new_prefix(self):
2186
 
        tpr = self._get_registry()
2187
 
        tpr.register('foo', 'fff.ooo.ooo')
2188
 
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2189
 
 
2190
 
    def test_register_existing_prefix(self):
2191
 
        tpr = self._get_registry()
2192
 
        tpr.register('bar', 'bbb.aaa.rrr')
2193
 
        tpr.register('bar', 'bBB.aAA.rRR')
2194
 
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2195
 
        self.assertContainsRe(self._get_log(keep_log_file=True),
2196
 
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2197
 
 
2198
 
    def test_get_unknown_prefix(self):
2199
 
        tpr = self._get_registry()
2200
 
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2201
 
 
2202
 
    def test_resolve_prefix(self):
2203
 
        tpr = self._get_registry()
2204
 
        tpr.register('bar', 'bb.aa.rr')
2205
 
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2206
 
 
2207
 
    def test_resolve_unknown_alias(self):
2208
 
        tpr = self._get_registry()
2209
 
        self.assertRaises(errors.BzrCommandError,
2210
 
                          tpr.resolve_alias, 'I am not a prefix')
2211
 
 
2212
 
    def test_predefined_prefixes(self):
2213
 
        tpr = tests.test_prefix_alias_registry
2214
 
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2215
 
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2216
 
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2217
 
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2218
 
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2219
 
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
1716
        self.assertEqual(err, 'bzr: ERROR: Not a branch: "/nonexistantpath/".\n')