~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Ian Clatworthy
  • Date: 2007-08-13 14:16:53 UTC
  • mto: (2733.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 2734.
  • Revision ID: ian.clatworthy@internode.on.net-20070813141653-3cbrp00xowq58zv1
Added mini tutorial

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the test framework."""
18
18
 
19
 
from cStringIO import StringIO
 
19
import cStringIO
20
20
import os
 
21
from StringIO import StringIO
21
22
import sys
22
23
import time
23
24
import unittest
25
26
 
26
27
import bzrlib
27
28
from bzrlib import (
28
 
    branchbuilder,
29
29
    bzrdir,
30
 
    debug,
31
30
    errors,
32
 
    lockdir,
33
31
    memorytree,
34
32
    osutils,
35
 
    progress,
36
 
    remote,
37
33
    repository,
38
34
    symbol_versioning,
39
 
    tests,
40
 
    workingtree,
41
 
    )
42
 
from bzrlib.repofmt import (
43
 
    pack_repo,
44
 
    weaverepo,
45
 
    )
46
 
from bzrlib.symbol_versioning import (
47
 
    deprecated_function,
48
 
    deprecated_in,
49
 
    deprecated_method,
50
 
    )
 
35
    )
 
36
from bzrlib.progress import _BaseProgressBar
 
37
from bzrlib.repofmt import weaverepo
 
38
from bzrlib.symbol_versioning import zero_ten, zero_eleven
51
39
from bzrlib.tests import (
52
 
    test_lsprof,
53
 
    test_sftp_transport,
54
 
    TestUtil,
55
 
    )
 
40
                          ChrootedTestCase,
 
41
                          ExtendedTestResult,
 
42
                          Feature,
 
43
                          KnownFailure,
 
44
                          TestCase,
 
45
                          TestCaseInTempDir,
 
46
                          TestCaseWithMemoryTransport,
 
47
                          TestCaseWithTransport,
 
48
                          TestSkipped,
 
49
                          TestSuite,
 
50
                          TestUtil,
 
51
                          TextTestRunner,
 
52
                          UnavailableFeature,
 
53
                          iter_suite_tests,
 
54
                          filter_suite_by_re,
 
55
                          sort_suite_by_re,
 
56
                          test_lsprof,
 
57
                          test_suite,
 
58
                          )
 
59
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
 
60
from bzrlib.tests.TestUtil import _load_module_by_name
56
61
from bzrlib.trace import note
57
62
from bzrlib.transport.memory import MemoryServer, MemoryTransport
58
63
from bzrlib.version import _get_bzr_source_tree
59
64
 
60
65
 
61
 
def _test_ids(test_suite):
62
 
    """Get the ids for the tests in a test suite."""
63
 
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
64
 
 
65
 
 
66
 
class SelftestTests(tests.TestCase):
 
66
class SelftestTests(TestCase):
67
67
 
68
68
    def test_import_tests(self):
69
 
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
69
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
70
70
        self.assertEqual(mod.SelftestTests, SelftestTests)
71
71
 
72
72
    def test_import_test_failure(self):
73
73
        self.assertRaises(ImportError,
74
 
                          TestUtil._load_module_by_name,
 
74
                          _load_module_by_name,
75
75
                          'bzrlib.no-name-yet')
76
76
 
77
 
class MetaTestLog(tests.TestCase):
 
77
class MetaTestLog(TestCase):
78
78
 
79
79
    def test_logging(self):
80
80
        """Test logs are captured when a test fails."""
84
84
                              'a test message\n')
85
85
 
86
86
 
87
 
class TestUnicodeFilename(tests.TestCase):
88
 
 
89
 
    def test_probe_passes(self):
90
 
        """UnicodeFilename._probe passes."""
91
 
        # We can't test much more than that because the behaviour depends
92
 
        # on the platform.
93
 
        tests.UnicodeFilename._probe()
94
 
 
95
 
 
96
 
class TestTreeShape(tests.TestCaseInTempDir):
 
87
class TestTreeShape(TestCaseInTempDir):
97
88
 
98
89
    def test_unicode_paths(self):
99
 
        self.requireFeature(tests.UnicodeFilename)
100
 
 
101
90
        filename = u'hell\u00d8'
102
 
        self.build_tree_contents([(filename, 'contents of hello')])
 
91
        try:
 
92
            self.build_tree_contents([(filename, 'contents of hello')])
 
93
        except UnicodeEncodeError:
 
94
            raise TestSkipped("can't build unicode working tree in "
 
95
                "filesystem encoding %s" % sys.getfilesystemencoding())
103
96
        self.failUnlessExists(filename)
104
97
 
105
98
 
106
 
class TestTransportScenarios(tests.TestCase):
 
99
class TestTransportProviderAdapter(TestCase):
107
100
    """A group of tests that test the transport implementation adaption core.
108
101
 
109
 
    This is a meta test that the tests are applied to all available
 
102
    This is a meta test that the tests are applied to all available 
110
103
    transports.
111
104
 
112
 
    This will be generalised in the future which is why it is in this
 
105
    This will be generalised in the future which is why it is in this 
113
106
    test file even though it is specific to transport tests at the moment.
114
107
    """
115
108
 
116
109
    def test_get_transport_permutations(self):
117
 
        # this checks that get_test_permutations defined by the module is
118
 
        # called by the get_transport_test_permutations function.
 
110
        # this checks that we the module get_test_permutations call
 
111
        # is made by the adapter get_transport_test_permitations method.
119
112
        class MockModule(object):
120
113
            def get_test_permutations(self):
121
114
                return sample_permutation
122
115
        sample_permutation = [(1,2), (3,4)]
123
 
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
116
        from bzrlib.tests.test_transport_implementations \
 
117
            import TransportTestProviderAdapter
 
118
        adapter = TransportTestProviderAdapter()
124
119
        self.assertEqual(sample_permutation,
125
 
                         get_transport_test_permutations(MockModule()))
 
120
                         adapter.get_transport_test_permutations(MockModule()))
126
121
 
127
 
    def test_scenarios_invlude_all_modules(self):
128
 
        # this checks that the scenario generator returns as many permutations
129
 
        # as there are in all the registered transport modules - we assume if
130
 
        # this matches its probably doing the right thing especially in
131
 
        # combination with the tests for setting the right classes below.
132
 
        from bzrlib.tests.per_transport import transport_test_permutations
 
122
    def test_adapter_checks_all_modules(self):
 
123
        # this checks that the adapter returns as many permurtations as
 
124
        # there are in all the registered# transport modules for there
 
125
        # - we assume if this matches its probably doing the right thing
 
126
        # especially in combination with the tests for setting the right
 
127
        # classes below.
 
128
        from bzrlib.tests.test_transport_implementations \
 
129
            import TransportTestProviderAdapter
133
130
        from bzrlib.transport import _get_transport_modules
134
131
        modules = _get_transport_modules()
135
132
        permutation_count = 0
136
133
        for module in modules:
137
134
            try:
138
 
                permutation_count += len(reduce(getattr,
 
135
                permutation_count += len(reduce(getattr, 
139
136
                    (module + ".get_test_permutations").split('.')[1:],
140
137
                     __import__(module))())
141
138
            except errors.DependencyNotPresent:
142
139
                pass
143
 
        scenarios = transport_test_permutations()
144
 
        self.assertEqual(permutation_count, len(scenarios))
 
140
        input_test = TestTransportProviderAdapter(
 
141
            "test_adapter_sets_transport_class")
 
142
        adapter = TransportTestProviderAdapter()
 
143
        self.assertEqual(permutation_count,
 
144
                         len(list(iter(adapter.adapt(input_test)))))
145
145
 
146
 
    def test_scenarios_include_transport_class(self):
 
146
    def test_adapter_sets_transport_class(self):
 
147
        # Check that the test adapter inserts a transport and server into the
 
148
        # generated test.
 
149
        #
147
150
        # This test used to know about all the possible transports and the
148
151
        # order they were returned but that seems overly brittle (mbp
149
152
        # 20060307)
150
 
        from bzrlib.tests.per_transport import transport_test_permutations
151
 
        scenarios = transport_test_permutations()
 
153
        from bzrlib.tests.test_transport_implementations \
 
154
            import TransportTestProviderAdapter
 
155
        scenarios = TransportTestProviderAdapter().scenarios
152
156
        # there are at least that many builtin transports
153
157
        self.assertTrue(len(scenarios) > 6)
154
158
        one_scenario = scenarios[0]
159
163
                                   bzrlib.transport.Server))
160
164
 
161
165
 
162
 
class TestBranchScenarios(tests.TestCase):
 
166
class TestBranchProviderAdapter(TestCase):
 
167
    """A group of tests that test the branch implementation test adapter."""
163
168
 
164
 
    def test_scenarios(self):
 
169
    def test_constructor(self):
165
170
        # check that constructor parameters are passed through to the adapted
166
171
        # test.
167
 
        from bzrlib.tests.per_branch import make_scenarios
 
172
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
168
173
        server1 = "a"
169
174
        server2 = "b"
170
175
        formats = [("c", "C"), ("d", "D")]
171
 
        scenarios = make_scenarios(server1, server2, formats)
172
 
        self.assertEqual(2, len(scenarios))
 
176
        adapter = BranchTestProviderAdapter(server1, server2, formats)
 
177
        self.assertEqual(2, len(adapter.scenarios))
173
178
        self.assertEqual([
174
179
            ('str',
175
180
             {'branch_format': 'c',
181
186
              'bzrdir_format': 'D',
182
187
              'transport_readonly_server': 'b',
183
188
              'transport_server': 'a'})],
184
 
            scenarios)
185
 
 
186
 
 
187
 
class TestBzrDirScenarios(tests.TestCase):
188
 
 
189
 
    def test_scenarios(self):
 
189
            adapter.scenarios)
 
190
 
 
191
 
 
192
class TestBzrDirProviderAdapter(TestCase):
 
193
    """A group of tests that test the bzr dir implementation test adapter."""
 
194
 
 
195
    def test_adapted_tests(self):
190
196
        # check that constructor parameters are passed through to the adapted
191
197
        # test.
192
 
        from bzrlib.tests.per_bzrdir import make_scenarios
 
198
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
193
199
        vfs_factory = "v"
194
200
        server1 = "a"
195
201
        server2 = "b"
196
202
        formats = ["c", "d"]
197
 
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
 
203
        adapter = BzrDirTestProviderAdapter(vfs_factory,
 
204
            server1, server2, formats)
198
205
        self.assertEqual([
199
206
            ('str',
200
207
             {'bzrdir_format': 'c',
206
213
              'transport_readonly_server': 'b',
207
214
              'transport_server': 'a',
208
215
              'vfs_transport_factory': 'v'})],
209
 
            scenarios)
210
 
 
211
 
 
212
 
class TestRepositoryScenarios(tests.TestCase):
 
216
            adapter.scenarios)
 
217
 
 
218
 
 
219
class TestRepositoryProviderAdapter(TestCase):
 
220
    """A group of tests that test the repository implementation test adapter."""
 
221
 
 
222
    def test_constructor(self):
 
223
        # check that constructor parameters are passed through to the
 
224
        # scenarios.
 
225
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
226
        server1 = "a"
 
227
        server2 = "b"
 
228
        formats = [("c", "C"), ("d", "D")]
 
229
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
 
230
        self.assertEqual([
 
231
            ('str',
 
232
             {'bzrdir_format': 'C',
 
233
              'repository_format': 'c',
 
234
              'transport_readonly_server': 'b',
 
235
              'transport_server': 'a'}),
 
236
            ('str',
 
237
             {'bzrdir_format': 'D',
 
238
              'repository_format': 'd',
 
239
              'transport_readonly_server': 'b',
 
240
              'transport_server': 'a'})],
 
241
            adapter.scenarios)
 
242
 
 
243
    def test_setting_vfs_transport(self):
 
244
        """The vfs_transport_factory can be set optionally."""
 
245
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
246
        formats = [("a", "b"), ("c", "d")]
 
247
        adapter = RepositoryTestProviderAdapter(None, None, formats,
 
248
            vfs_transport_factory="vfs")
 
249
        self.assertEqual([
 
250
            ('str',
 
251
             {'bzrdir_format': 'b',
 
252
              'repository_format': 'a',
 
253
              'transport_readonly_server': None,
 
254
              'transport_server': None,
 
255
              'vfs_transport_factory': 'vfs'}),
 
256
            ('str',
 
257
             {'bzrdir_format': 'd',
 
258
              'repository_format': 'c',
 
259
              'transport_readonly_server': None,
 
260
              'transport_server': None,
 
261
              'vfs_transport_factory': 'vfs'})],
 
262
            adapter.scenarios)
213
263
 
214
264
    def test_formats_to_scenarios(self):
215
 
        from bzrlib.tests.per_repository import formats_to_scenarios
216
 
        formats = [("(c)", remote.RemoteRepositoryFormat()),
217
 
                   ("(d)", repository.format_registry.get(
218
 
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
219
 
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
220
 
            None)
221
 
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
222
 
            vfs_transport_factory="vfs")
223
 
        # no_vfs generate scenarios without vfs_transport_factory
 
265
        """The adapter can generate all the scenarios needed."""
 
266
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
267
        no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
 
268
            [], None)
 
269
        vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
 
270
            [], vfs_transport_factory="vfs")
 
271
        # no_vfs generate scenarios without vfs_transport_factor
 
272
        formats = [("c", "C"), (1, "D")]
224
273
        self.assertEqual([
225
 
            ('RemoteRepositoryFormat(c)',
226
 
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
227
 
              'repository_format': remote.RemoteRepositoryFormat(),
 
274
            ('str',
 
275
             {'bzrdir_format': 'C',
 
276
              'repository_format': 'c',
228
277
              'transport_readonly_server': 'readonly',
229
278
              'transport_server': 'server'}),
230
 
            ('RepositoryFormatKnitPack1(d)',
231
 
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
232
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
279
            ('int',
 
280
             {'bzrdir_format': 'D',
 
281
              'repository_format': 1,
233
282
              'transport_readonly_server': 'readonly',
234
283
              'transport_server': 'server'})],
235
 
            no_vfs_scenarios)
 
284
            no_vfs_adapter.formats_to_scenarios(formats))
236
285
        self.assertEqual([
237
 
            ('RemoteRepositoryFormat(c)',
238
 
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
239
 
              'repository_format': remote.RemoteRepositoryFormat(),
 
286
            ('str',
 
287
             {'bzrdir_format': 'C',
 
288
              'repository_format': 'c',
240
289
              'transport_readonly_server': 'readonly',
241
290
              'transport_server': 'server',
242
291
              'vfs_transport_factory': 'vfs'}),
243
 
            ('RepositoryFormatKnitPack1(d)',
244
 
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
245
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
292
            ('int',
 
293
             {'bzrdir_format': 'D',
 
294
              'repository_format': 1,
246
295
              'transport_readonly_server': 'readonly',
247
296
              'transport_server': 'server',
248
297
              'vfs_transport_factory': 'vfs'})],
249
 
            vfs_scenarios)
250
 
 
251
 
 
252
 
class TestTestScenarioApplication(tests.TestCase):
 
298
            vfs_adapter.formats_to_scenarios(formats))
 
299
 
 
300
 
 
301
class TestTestScenarioApplier(TestCase):
253
302
    """Tests for the test adaption facilities."""
254
303
 
255
 
    def test_apply_scenario(self):
256
 
        from bzrlib.tests import apply_scenario
257
 
        input_test = TestTestScenarioApplication("test_apply_scenario")
 
304
    def test_adapt_applies_scenarios(self):
 
305
        from bzrlib.tests.repository_implementations import TestScenarioApplier
 
306
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
307
        adapter = TestScenarioApplier()
 
308
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
 
309
        calls = []
 
310
        def capture_call(test, scenario):
 
311
            calls.append((test, scenario))
 
312
            return test
 
313
        adapter.adapt_test_to_scenario = capture_call
 
314
        adapter.adapt(input_test)
 
315
        self.assertEqual([(input_test, ("1", "dict")),
 
316
            (input_test, ("2", "settings"))], calls)
 
317
 
 
318
    def test_adapt_test_to_scenario(self):
 
319
        from bzrlib.tests.repository_implementations import TestScenarioApplier
 
320
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
321
        adapter = TestScenarioApplier()
258
322
        # setup two adapted tests
259
 
        adapted_test1 = apply_scenario(input_test,
 
323
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
260
324
            ("new id",
261
325
            {"bzrdir_format":"bzr_format",
262
326
             "repository_format":"repo_fmt",
263
327
             "transport_server":"transport_server",
264
328
             "transport_readonly_server":"readonly-server"}))
265
 
        adapted_test2 = apply_scenario(input_test,
 
329
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
266
330
            ("new id 2", {"bzrdir_format":None}))
267
331
        # input_test should have been altered.
268
332
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
269
 
        # the new tests are mutually incompatible, ensuring it has
 
333
        # the new tests are mutually incompatible, ensuring it has 
270
334
        # made new ones, and unspecified elements in the scenario
271
335
        # should not have been altered.
272
336
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
275
339
        self.assertEqual("readonly-server",
276
340
            adapted_test1.transport_readonly_server)
277
341
        self.assertEqual(
278
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
279
 
            "test_apply_scenario(new id)",
 
342
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
343
            "test_adapt_test_to_scenario(new id)",
280
344
            adapted_test1.id())
281
345
        self.assertEqual(None, adapted_test2.bzrdir_format)
282
346
        self.assertEqual(
283
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
284
 
            "test_apply_scenario(new id 2)",
 
347
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
348
            "test_adapt_test_to_scenario(new id 2)",
285
349
            adapted_test2.id())
286
350
 
287
351
 
288
 
class TestInterRepositoryScenarios(tests.TestCase):
 
352
class TestInterRepositoryProviderAdapter(TestCase):
 
353
    """A group of tests that test the InterRepository test adapter."""
289
354
 
290
 
    def test_scenarios(self):
 
355
    def test_adapted_tests(self):
291
356
        # check that constructor parameters are passed through to the adapted
292
357
        # test.
293
 
        from bzrlib.tests.per_interrepository import make_scenarios
 
358
        from bzrlib.tests.interrepository_implementations import \
 
359
            InterRepositoryTestProviderAdapter
294
360
        server1 = "a"
295
361
        server2 = "b"
296
362
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
297
 
        scenarios = make_scenarios(server1, server2, formats)
 
363
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
298
364
        self.assertEqual([
299
 
            ('str,str,str',
 
365
            ('str',
300
366
             {'interrepo_class': str,
301
367
              'repository_format': 'C1',
302
368
              'repository_format_to': 'C2',
303
369
              'transport_readonly_server': 'b',
304
370
              'transport_server': 'a'}),
305
 
            ('int,str,str',
 
371
            ('int',
306
372
             {'interrepo_class': int,
307
373
              'repository_format': 'D1',
308
374
              'repository_format_to': 'D2',
309
375
              'transport_readonly_server': 'b',
310
376
              'transport_server': 'a'})],
311
 
            scenarios)
312
 
 
313
 
 
314
 
class TestWorkingTreeScenarios(tests.TestCase):
315
 
 
316
 
    def test_scenarios(self):
317
 
        # check that constructor parameters are passed through to the adapted
318
 
        # test.
319
 
        from bzrlib.tests.per_workingtree import make_scenarios
320
 
        server1 = "a"
321
 
        server2 = "b"
322
 
        formats = [workingtree.WorkingTreeFormat2(),
323
 
                   workingtree.WorkingTreeFormat3(),]
324
 
        scenarios = make_scenarios(server1, server2, formats)
325
 
        self.assertEqual([
326
 
            ('WorkingTreeFormat2',
327
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
328
 
              'transport_readonly_server': 'b',
329
 
              'transport_server': 'a',
330
 
              'workingtree_format': formats[0]}),
331
 
            ('WorkingTreeFormat3',
332
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
333
 
              'transport_readonly_server': 'b',
334
 
              'transport_server': 'a',
335
 
              'workingtree_format': formats[1]})],
336
 
            scenarios)
337
 
 
338
 
 
339
 
class TestTreeScenarios(tests.TestCase):
340
 
 
341
 
    def test_scenarios(self):
342
 
        # the tree implementation scenario generator is meant to setup one
343
 
        # instance for each working tree format, and one additional instance
344
 
        # that will use the default wt format, but create a revision tree for
345
 
        # the tests.  this means that the wt ones should have the
346
 
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
347
 
        # revision one set to revision_tree_from_workingtree.
348
 
 
349
 
        from bzrlib.tests.per_tree import (
350
 
            _dirstate_tree_from_workingtree,
351
 
            make_scenarios,
352
 
            preview_tree_pre,
353
 
            preview_tree_post,
 
377
            adapter.formats_to_scenarios(formats))
 
378
 
 
379
 
 
380
class TestInterVersionedFileProviderAdapter(TestCase):
 
381
    """A group of tests that test the InterVersionedFile test adapter."""
 
382
 
 
383
    def test_scenarios(self):
 
384
        # check that constructor parameters are passed through to the adapted
 
385
        # test.
 
386
        from bzrlib.tests.interversionedfile_implementations \
 
387
            import InterVersionedFileTestProviderAdapter
 
388
        server1 = "a"
 
389
        server2 = "b"
 
390
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
391
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
 
392
        self.assertEqual([
 
393
            ('str',
 
394
             {'interversionedfile_class':str,
 
395
              'transport_readonly_server': 'b',
 
396
              'transport_server': 'a',
 
397
              'versionedfile_factory': 'C1',
 
398
              'versionedfile_factory_to': 'C2'}),
 
399
            ('int',
 
400
             {'interversionedfile_class': int,
 
401
              'transport_readonly_server': 'b',
 
402
              'transport_server': 'a',
 
403
              'versionedfile_factory': 'D1',
 
404
              'versionedfile_factory_to': 'D2'})],
 
405
            adapter.scenarios)
 
406
 
 
407
 
 
408
class TestRevisionStoreProviderAdapter(TestCase):
 
409
    """A group of tests that test the RevisionStore test adapter."""
 
410
 
 
411
    def test_scenarios(self):
 
412
        # check that constructor parameters are passed through to the adapted
 
413
        # test.
 
414
        from bzrlib.tests.revisionstore_implementations \
 
415
            import RevisionStoreTestProviderAdapter
 
416
        # revision stores need a store factory - i.e. RevisionKnit
 
417
        #, a readonly and rw transport 
 
418
        # transport servers:
 
419
        server1 = "a"
 
420
        server2 = "b"
 
421
        store_factories = ["c", "d"]
 
422
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
 
423
        self.assertEqual([
 
424
            ('c',
 
425
             {'store_factory': 'c',
 
426
              'transport_readonly_server': 'b',
 
427
              'transport_server': 'a'}),
 
428
            ('d',
 
429
             {'store_factory': 'd',
 
430
              'transport_readonly_server': 'b',
 
431
              'transport_server': 'a'})],
 
432
            adapter.scenarios)
 
433
 
 
434
 
 
435
class TestWorkingTreeProviderAdapter(TestCase):
 
436
    """A group of tests that test the workingtree implementation test adapter."""
 
437
 
 
438
    def test_scenarios(self):
 
439
        # check that constructor parameters are passed through to the adapted
 
440
        # test.
 
441
        from bzrlib.tests.workingtree_implementations \
 
442
            import WorkingTreeTestProviderAdapter
 
443
        server1 = "a"
 
444
        server2 = "b"
 
445
        formats = [("c", "C"), ("d", "D")]
 
446
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
447
        self.assertEqual([
 
448
            ('str',
 
449
             {'bzrdir_format': 'C',
 
450
              'transport_readonly_server': 'b',
 
451
              'transport_server': 'a',
 
452
              'workingtree_format': 'c'}),
 
453
            ('str',
 
454
             {'bzrdir_format': 'D',
 
455
              'transport_readonly_server': 'b',
 
456
              'transport_server': 'a',
 
457
              'workingtree_format': 'd'})],
 
458
            adapter.scenarios)
 
459
 
 
460
 
 
461
class TestTreeProviderAdapter(TestCase):
 
462
    """Test the setup of tree_implementation tests."""
 
463
 
 
464
    def test_adapted_tests(self):
 
465
        # the tree implementation adapter is meant to setup one instance for
 
466
        # each working tree format, and one additional instance that will
 
467
        # use the default wt format, but create a revision tree for the tests.
 
468
        # this means that the wt ones should have the workingtree_to_test_tree
 
469
        # attribute set to 'return_parameter' and the revision one set to
 
470
        # revision_tree_from_workingtree.
 
471
 
 
472
        from bzrlib.tests.tree_implementations import (
 
473
            TreeTestProviderAdapter,
354
474
            return_parameter,
355
475
            revision_tree_from_workingtree
356
476
            )
 
477
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
 
478
        input_test = TestTreeProviderAdapter(
 
479
            "test_adapted_tests")
357
480
        server1 = "a"
358
481
        server2 = "b"
359
 
        formats = [workingtree.WorkingTreeFormat2(),
360
 
                   workingtree.WorkingTreeFormat3(),]
361
 
        scenarios = make_scenarios(server1, server2, formats)
362
 
        self.assertEqual(7, len(scenarios))
363
 
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
364
 
        wt4_format = workingtree.WorkingTreeFormat4()
365
 
        wt5_format = workingtree.WorkingTreeFormat5()
366
 
        expected_scenarios = [
367
 
            ('WorkingTreeFormat2',
368
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
369
 
              'transport_readonly_server': 'b',
370
 
              'transport_server': 'a',
371
 
              'workingtree_format': formats[0],
372
 
              '_workingtree_to_test_tree': return_parameter,
373
 
              }),
374
 
            ('WorkingTreeFormat3',
375
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
376
 
              'transport_readonly_server': 'b',
377
 
              'transport_server': 'a',
378
 
              'workingtree_format': formats[1],
379
 
              '_workingtree_to_test_tree': return_parameter,
380
 
             }),
381
 
            ('RevisionTree',
382
 
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
383
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
384
 
              'transport_readonly_server': 'b',
385
 
              'transport_server': 'a',
386
 
              'workingtree_format': default_wt_format,
387
 
             }),
388
 
            ('DirStateRevisionTree,WT4',
389
 
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
390
 
              'bzrdir_format': wt4_format._matchingbzrdir,
391
 
              'transport_readonly_server': 'b',
392
 
              'transport_server': 'a',
393
 
              'workingtree_format': wt4_format,
394
 
             }),
395
 
            ('DirStateRevisionTree,WT5',
396
 
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
397
 
              'bzrdir_format': wt5_format._matchingbzrdir,
398
 
              'transport_readonly_server': 'b',
399
 
              'transport_server': 'a',
400
 
              'workingtree_format': wt5_format,
401
 
             }),
402
 
            ('PreviewTree',
403
 
             {'_workingtree_to_test_tree': preview_tree_pre,
404
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
405
 
              'transport_readonly_server': 'b',
406
 
              'transport_server': 'a',
407
 
              'workingtree_format': default_wt_format}),
408
 
            ('PreviewTreePost',
409
 
             {'_workingtree_to_test_tree': preview_tree_post,
410
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
411
 
              'transport_readonly_server': 'b',
412
 
              'transport_server': 'a',
413
 
              'workingtree_format': default_wt_format}),
414
 
             ]
415
 
        self.assertEqual(expected_scenarios, scenarios)
416
 
 
417
 
 
418
 
class TestInterTreeScenarios(tests.TestCase):
 
482
        formats = [("c", "C"), ("d", "D")]
 
483
        adapter = TreeTestProviderAdapter(server1, server2, formats)
 
484
        suite = adapter.adapt(input_test)
 
485
        tests = list(iter(suite))
 
486
        self.assertEqual(4, len(tests))
 
487
        # this must match the default format setp up in
 
488
        # TreeTestProviderAdapter.adapt
 
489
        default_format = WorkingTreeFormat3
 
490
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
491
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
492
        self.assertEqual(tests[0].transport_server, server1)
 
493
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
494
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
495
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
496
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
497
        self.assertEqual(tests[1].transport_server, server1)
 
498
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
499
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
500
        self.assertIsInstance(tests[2].workingtree_format, default_format)
 
501
        #self.assertEqual(tests[2].bzrdir_format,
 
502
        #                 default_format._matchingbzrdir)
 
503
        self.assertEqual(tests[2].transport_server, server1)
 
504
        self.assertEqual(tests[2].transport_readonly_server, server2)
 
505
        self.assertEqual(tests[2].workingtree_to_test_tree,
 
506
            revision_tree_from_workingtree)
 
507
 
 
508
 
 
509
class TestInterTreeProviderAdapter(TestCase):
419
510
    """A group of tests that test the InterTreeTestAdapter."""
420
511
 
421
 
    def test_scenarios(self):
 
512
    def test_adapted_tests(self):
422
513
        # check that constructor parameters are passed through to the adapted
423
514
        # test.
424
515
        # for InterTree tests we want the machinery to bring up two trees in
426
517
        # because each optimiser can be direction specific, we need to test
427
518
        # each optimiser in its chosen direction.
428
519
        # unlike the TestProviderAdapter we dont want to automatically add a
429
 
        # parameterized one for WorkingTree - the optimisers will tell us what
 
520
        # parameterised one for WorkingTree - the optimisers will tell us what
430
521
        # ones to add.
431
 
        from bzrlib.tests.per_tree import (
 
522
        from bzrlib.tests.tree_implementations import (
432
523
            return_parameter,
433
524
            revision_tree_from_workingtree
434
525
            )
435
 
        from bzrlib.tests.per_intertree import (
436
 
            make_scenarios,
 
526
        from bzrlib.tests.intertree_implementations import (
 
527
            InterTreeTestProviderAdapter,
437
528
            )
438
529
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
439
 
        input_test = TestInterTreeScenarios(
440
 
            "test_scenarios")
 
530
        input_test = TestInterTreeProviderAdapter(
 
531
            "test_adapted_tests")
441
532
        server1 = "a"
442
533
        server2 = "b"
443
534
        format1 = WorkingTreeFormat2()
444
535
        format2 = WorkingTreeFormat3()
445
 
        formats = [("1", str, format1, format2, "converter1"),
446
 
            ("2", int, format2, format1, "converter2")]
447
 
        scenarios = make_scenarios(server1, server2, formats)
448
 
        self.assertEqual(2, len(scenarios))
449
 
        expected_scenarios = [
450
 
            ("1", {
451
 
                "bzrdir_format": format1._matchingbzrdir,
452
 
                "intertree_class": formats[0][1],
453
 
                "workingtree_format": formats[0][2],
454
 
                "workingtree_format_to": formats[0][3],
455
 
                "mutable_trees_to_test_trees": formats[0][4],
456
 
                "_workingtree_to_test_tree": return_parameter,
457
 
                "transport_server": server1,
458
 
                "transport_readonly_server": server2,
459
 
                }),
460
 
            ("2", {
461
 
                "bzrdir_format": format2._matchingbzrdir,
462
 
                "intertree_class": formats[1][1],
463
 
                "workingtree_format": formats[1][2],
464
 
                "workingtree_format_to": formats[1][3],
465
 
                "mutable_trees_to_test_trees": formats[1][4],
466
 
                "_workingtree_to_test_tree": return_parameter,
467
 
                "transport_server": server1,
468
 
                "transport_readonly_server": server2,
469
 
                }),
470
 
            ]
471
 
        self.assertEqual(scenarios, expected_scenarios)
472
 
 
473
 
 
474
 
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
 
536
        formats = [(str, format1, format2, "converter1"),
 
537
            (int, format2, format1, "converter2")]
 
538
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
 
539
        suite = adapter.adapt(input_test)
 
540
        tests = list(iter(suite))
 
541
        self.assertEqual(2, len(tests))
 
542
        self.assertEqual(tests[0].intertree_class, formats[0][0])
 
543
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
 
544
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
 
545
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
 
546
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
547
        self.assertEqual(tests[0].transport_server, server1)
 
548
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
549
        self.assertEqual(tests[1].intertree_class, formats[1][0])
 
550
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
 
551
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
 
552
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
 
553
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
554
        self.assertEqual(tests[1].transport_server, server1)
 
555
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
556
 
 
557
 
 
558
class TestTestCaseInTempDir(TestCaseInTempDir):
475
559
 
476
560
    def test_home_is_not_working(self):
477
561
        self.assertNotEqual(self.test_dir, self.test_home_dir)
478
562
        cwd = osutils.getcwd()
479
 
        self.assertIsSameRealPath(self.test_dir, cwd)
480
 
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
481
 
 
482
 
    def test_assertEqualStat_equal(self):
483
 
        from bzrlib.tests.test_dirstate import _FakeStat
484
 
        self.build_tree(["foo"])
485
 
        real = os.lstat("foo")
486
 
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
487
 
            real.st_dev, real.st_ino, real.st_mode)
488
 
        self.assertEqualStat(real, fake)
489
 
 
490
 
    def test_assertEqualStat_notequal(self):
491
 
        self.build_tree(["foo", "bar"])
492
 
        self.assertRaises(AssertionError, self.assertEqualStat,
493
 
            os.lstat("foo"), os.lstat("bar"))
494
 
 
495
 
 
496
 
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
 
563
        self.assertEqual(self.test_dir, cwd)
 
564
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
565
 
 
566
 
 
567
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
497
568
 
498
569
    def test_home_is_non_existant_dir_under_root(self):
499
570
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
500
571
 
501
572
        This is because TestCaseWithMemoryTransport is for tests that do not
502
 
        need any disk resources: they should be hooked into bzrlib in such a
503
 
        way that no global settings are being changed by the test (only a
 
573
        need any disk resources: they should be hooked into bzrlib in such a 
 
574
        way that no global settings are being changed by the test (only a 
504
575
        few tests should need to do that), and having a missing dir as home is
505
576
        an effective way to ensure that this is the case.
506
577
        """
507
 
        self.assertIsSameRealPath(
508
 
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
578
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
509
579
            self.test_home_dir)
510
 
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
511
 
 
 
580
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
581
        
512
582
    def test_cwd_is_TEST_ROOT(self):
513
 
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
583
        self.assertEqual(self.test_dir, self.TEST_ROOT)
514
584
        cwd = osutils.getcwd()
515
 
        self.assertIsSameRealPath(self.test_dir, cwd)
 
585
        self.assertEqual(self.test_dir, cwd)
516
586
 
517
587
    def test_make_branch_and_memory_tree(self):
518
588
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
538
608
        self.assertEqual(format.repository_format.__class__,
539
609
            tree.branch.repository._format.__class__)
540
610
 
541
 
    def test_make_branch_builder(self):
542
 
        builder = self.make_branch_builder('dir')
543
 
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
544
 
        # Guard against regression into MemoryTransport leaking
545
 
        # files to disk instead of keeping them in memory.
546
 
        self.failIf(osutils.lexists('dir'))
547
 
 
548
 
    def test_make_branch_builder_with_format(self):
549
 
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
550
 
        # that the format objects are used.
551
 
        format = bzrdir.BzrDirMetaFormat1()
552
 
        repo_format = weaverepo.RepositoryFormat7()
553
 
        format.repository_format = repo_format
554
 
        builder = self.make_branch_builder('dir', format=format)
555
 
        the_branch = builder.get_branch()
556
 
        # Guard against regression into MemoryTransport leaking
557
 
        # files to disk instead of keeping them in memory.
558
 
        self.failIf(osutils.lexists('dir'))
559
 
        self.assertEqual(format.repository_format.__class__,
560
 
                         the_branch.repository._format.__class__)
561
 
        self.assertEqual(repo_format.get_format_string(),
562
 
                         self.get_transport().get_bytes(
563
 
                            'dir/.bzr/repository/format'))
564
 
 
565
 
    def test_make_branch_builder_with_format_name(self):
566
 
        builder = self.make_branch_builder('dir', format='knit')
567
 
        the_branch = builder.get_branch()
568
 
        # Guard against regression into MemoryTransport leaking
569
 
        # files to disk instead of keeping them in memory.
570
 
        self.failIf(osutils.lexists('dir'))
571
 
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
572
 
        self.assertEqual(dir_format.repository_format.__class__,
573
 
                         the_branch.repository._format.__class__)
574
 
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
575
 
                         self.get_transport().get_bytes(
576
 
                            'dir/.bzr/repository/format'))
577
 
 
578
 
    def test_safety_net(self):
579
 
        """No test should modify the safety .bzr directory.
580
 
 
581
 
        We just test that the _check_safety_net private method raises
582
 
        AssertionError, it's easier than building a test suite with the same
583
 
        test.
584
 
        """
585
 
        # Oops, a commit in the current directory (i.e. without local .bzr
586
 
        # directory) will crawl up the hierarchy to find a .bzr directory.
587
 
        self.run_bzr(['commit', '-mfoo', '--unchanged'])
588
 
        # But we have a safety net in place.
589
 
        self.assertRaises(AssertionError, self._check_safety_net)
590
 
 
591
 
    def test_dangling_locks_cause_failures(self):
592
 
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
593
 
            def test_function(self):
594
 
                t = self.get_transport('.')
595
 
                l = lockdir.LockDir(t, 'lock')
596
 
                l.create()
597
 
                l.attempt_lock()
598
 
        test = TestDanglingLock('test_function')
599
 
        result = test.run()
600
 
        self.assertEqual(1, len(result.errors))
601
 
 
602
 
 
603
 
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
 
611
 
 
612
class TestTestCaseWithTransport(TestCaseWithTransport):
604
613
    """Tests for the convenience functions TestCaseWithTransport introduces."""
605
614
 
606
615
    def test_get_readonly_url_none(self):
620
629
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
621
630
 
622
631
    def test_get_readonly_url_http(self):
623
 
        from bzrlib.tests.http_server import HttpServer
 
632
        from bzrlib.tests.HttpServer import HttpServer
624
633
        from bzrlib.transport import get_transport
625
634
        from bzrlib.transport.local import LocalURLServer
626
635
        from bzrlib.transport.http import HttpTransportBase
644
653
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
645
654
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
646
655
 
647
 
    def test_make_branch_builder(self):
648
 
        builder = self.make_branch_builder('dir')
649
 
        rev_id = builder.build_commit()
650
 
        self.failUnlessExists('dir')
651
 
        a_dir = bzrdir.BzrDir.open('dir')
652
 
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
653
 
        a_branch = a_dir.open_branch()
654
 
        builder_branch = builder.get_branch()
655
 
        self.assertEqual(a_branch.base, builder_branch.base)
656
 
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
657
 
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
658
 
 
659
 
 
660
 
class TestTestCaseTransports(tests.TestCaseWithTransport):
 
656
 
 
657
class TestTestCaseTransports(TestCaseWithTransport):
661
658
 
662
659
    def setUp(self):
663
660
        super(TestTestCaseTransports, self).setUp()
666
663
    def test_make_bzrdir_preserves_transport(self):
667
664
        t = self.get_transport()
668
665
        result_bzrdir = self.make_bzrdir('subdir')
669
 
        self.assertIsInstance(result_bzrdir.transport,
 
666
        self.assertIsInstance(result_bzrdir.transport, 
670
667
                              MemoryTransport)
671
668
        # should not be on disk, should only be in memory
672
669
        self.failIfExists('subdir')
673
670
 
674
671
 
675
 
class TestChrootedTest(tests.ChrootedTestCase):
 
672
class TestChrootedTest(ChrootedTestCase):
676
673
 
677
674
    def test_root_is_root(self):
678
675
        from bzrlib.transport import get_transport
681
678
        self.assertEqual(url, t.clone('..').base)
682
679
 
683
680
 
684
 
class MockProgress(progress._BaseProgressBar):
 
681
class MockProgress(_BaseProgressBar):
685
682
    """Progress-bar standin that records calls.
686
683
 
687
684
    Useful for testing pb using code.
688
685
    """
689
686
 
690
687
    def __init__(self):
691
 
        progress._BaseProgressBar.__init__(self)
 
688
        _BaseProgressBar.__init__(self)
692
689
        self.calls = []
693
690
 
694
691
    def tick(self):
704
701
        self.calls.append(('note', msg, args))
705
702
 
706
703
 
707
 
class TestTestResult(tests.TestCase):
 
704
class TestTestResult(TestCase):
708
705
 
709
 
    def check_timing(self, test_case, expected_re):
 
706
    def test_elapsed_time_with_benchmarking(self):
710
707
        result = bzrlib.tests.TextTestResult(self._log_file,
711
 
                descriptions=0,
712
 
                verbosity=1,
713
 
                )
714
 
        test_case.run(result)
715
 
        timed_string = result._testTimeString(test_case)
716
 
        self.assertContainsRe(timed_string, expected_re)
717
 
 
718
 
    def test_test_reporting(self):
719
 
        class ShortDelayTestCase(tests.TestCase):
720
 
            def test_short_delay(self):
721
 
                time.sleep(0.003)
722
 
            def test_short_benchmark(self):
723
 
                self.time(time.sleep, 0.003)
724
 
        self.check_timing(ShortDelayTestCase('test_short_delay'),
725
 
                          r"^ +[0-9]+ms$")
726
 
        # if a benchmark time is given, we now show just that time followed by
727
 
        # a star
728
 
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
729
 
                          r"^ +[0-9]+ms\*$")
730
 
 
731
 
    def test_unittest_reporting_unittest_class(self):
732
 
        # getting the time from a non-bzrlib test works ok
733
 
        class ShortDelayTestCase(unittest.TestCase):
734
 
            def test_short_delay(self):
735
 
                time.sleep(0.003)
736
 
        self.check_timing(ShortDelayTestCase('test_short_delay'),
737
 
                          r"^ +[0-9]+ms$")
 
708
                                        descriptions=0,
 
709
                                        verbosity=1,
 
710
                                        )
 
711
        result._recordTestStartTime()
 
712
        time.sleep(0.003)
 
713
        result.extractBenchmarkTime(self)
 
714
        timed_string = result._testTimeString()
 
715
        # without explicit benchmarking, we should get a simple time.
 
716
        self.assertContainsRe(timed_string, "^ +[0-9]+ms$")
 
717
        # if a benchmark time is given, we want a x of y style result.
 
718
        self.time(time.sleep, 0.001)
 
719
        result.extractBenchmarkTime(self)
 
720
        timed_string = result._testTimeString()
 
721
        self.assertContainsRe(
 
722
            timed_string, "^ +[0-9]+ms/ +[0-9]+ms$")
 
723
        # extracting the time from a non-bzrlib testcase sets to None
 
724
        result._recordTestStartTime()
 
725
        result.extractBenchmarkTime(
 
726
            unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
 
727
        timed_string = result._testTimeString()
 
728
        self.assertContainsRe(timed_string, "^ +[0-9]+ms$")
 
729
        # cheat. Yes, wash thy mouth out with soap.
 
730
        self._benchtime = None
738
731
 
739
732
    def test_assigned_benchmark_file_stores_date(self):
740
733
        output = StringIO()
744
737
                                        bench_history=output
745
738
                                        )
746
739
        output_string = output.getvalue()
 
740
        
747
741
        # if you are wondering about the regexp please read the comment in
748
742
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
749
743
        # XXX: what comment?  -- Andrew Bennetts
768
762
        self.assertContainsRe(lines[1],
769
763
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
770
764
            "._time_hello_world_encoding")
771
 
 
 
765
 
772
766
    def _time_hello_world_encoding(self):
773
767
        """Profile two sleep calls
774
 
 
 
768
        
775
769
        This is used to exercise the test framework.
776
770
        """
777
771
        self.time(unicode, 'hello', errors='replace')
795
789
        # execute the test, which should succeed and record profiles
796
790
        example_test_case.run(result)
797
791
        # lsprofile_something()
798
 
        # if this worked we want
 
792
        # if this worked we want 
799
793
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
800
794
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
801
795
        # (the lsprof header)
802
796
        # ... an arbitrary number of lines
803
797
        # and the function call which is time.sleep.
804
 
        #           1        0            ???         ???       ???(sleep)
 
798
        #           1        0            ???         ???       ???(sleep) 
805
799
        # and then repeated but with 'world', rather than 'hello'.
806
800
        # this should appear in the output stream of our test result.
807
801
        output = result_stream.getvalue()
816
810
 
817
811
    def test_known_failure(self):
818
812
        """A KnownFailure being raised should trigger several result actions."""
819
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
820
 
            def done(self): pass
821
 
            def startTests(self): pass
 
813
        class InstrumentedTestResult(ExtendedTestResult):
 
814
 
822
815
            def report_test_start(self, test): pass
823
816
            def report_known_failure(self, test, err):
824
817
                self._call = test, err
825
818
        result = InstrumentedTestResult(None, None, None, None)
826
819
        def test_function():
827
 
            raise tests.KnownFailure('failed!')
 
820
            raise KnownFailure('failed!')
828
821
        test = unittest.FunctionTestCase(test_function)
829
822
        test.run(result)
830
823
        # it should invoke 'report_known_failure'.
831
824
        self.assertEqual(2, len(result._call))
832
825
        self.assertEqual(test, result._call[0])
833
 
        self.assertEqual(tests.KnownFailure, result._call[1][0])
834
 
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
826
        self.assertEqual(KnownFailure, result._call[1][0])
 
827
        self.assertIsInstance(result._call[1][1], KnownFailure)
835
828
        # we dont introspec the traceback, if the rest is ok, it would be
836
829
        # exceptional for it not to be.
837
830
        # it should update the known_failure_count on the object.
849
842
            )
850
843
        test = self.get_passing_test()
851
844
        result.startTest(test)
 
845
        result.extractBenchmarkTime(test)
852
846
        prefix = len(result_stream.getvalue())
853
847
        # the err parameter has the shape:
854
848
        # (class, exception object, traceback)
855
849
        # KnownFailures dont get their tracebacks shown though, so we
856
850
        # can skip that.
857
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
851
        err = (KnownFailure, KnownFailure('foo'), None)
858
852
        result.report_known_failure(test, err)
859
853
        output = result_stream.getvalue()[prefix:]
860
854
        lines = output.splitlines()
866
860
        # text test output formatting
867
861
        pb = MockProgress()
868
862
        result = bzrlib.tests.TextTestResult(
869
 
            StringIO(),
 
863
            None,
870
864
            descriptions=0,
871
865
            verbosity=1,
872
866
            pb=pb,
874
868
        test = self.get_passing_test()
875
869
        # this seeds the state to handle reporting the test.
876
870
        result.startTest(test)
 
871
        result.extractBenchmarkTime(test)
877
872
        # the err parameter has the shape:
878
873
        # (class, exception object, traceback)
879
874
        # KnownFailures dont get their tracebacks shown though, so we
880
875
        # can skip that.
881
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
876
        err = (KnownFailure, KnownFailure('foo'), None)
882
877
        result.report_known_failure(test, err)
883
878
        self.assertEqual(
884
879
            [
893
888
        test.run(result)
894
889
        self.assertEqual(
895
890
            [
896
 
            ('update', '[2 in 0s] passing_test', None, None),
 
891
            ('update', '[2 in 0s, 3 known failures] passing_test', None, None),
897
892
            ],
898
893
            pb.calls[2:])
899
894
 
905
900
 
906
901
    def test_add_not_supported(self):
907
902
        """Test the behaviour of invoking addNotSupported."""
908
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
909
 
            def done(self): pass
910
 
            def startTests(self): pass
 
903
        class InstrumentedTestResult(ExtendedTestResult):
911
904
            def report_test_start(self, test): pass
912
905
            def report_unsupported(self, test, feature):
913
906
                self._call = test, feature
914
907
        result = InstrumentedTestResult(None, None, None, None)
915
908
        test = SampleTestCase('_test_pass')
916
 
        feature = tests.Feature()
 
909
        feature = Feature()
917
910
        result.startTest(test)
918
911
        result.addNotSupported(test, feature)
919
912
        # it should invoke 'report_unsupported'.
938
931
            verbosity=2,
939
932
            )
940
933
        test = self.get_passing_test()
941
 
        feature = tests.Feature()
 
934
        feature = Feature()
942
935
        result.startTest(test)
 
936
        result.extractBenchmarkTime(test)
943
937
        prefix = len(result_stream.getvalue())
944
938
        result.report_unsupported(test, feature)
945
939
        output = result_stream.getvalue()[prefix:]
946
940
        lines = output.splitlines()
947
 
        self.assertEqual(lines, ['NODEP        0ms',
948
 
                                 "    The feature 'Feature' is not available."])
949
 
 
 
941
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
 
942
    
950
943
    def test_text_report_unsupported(self):
951
944
        # text test output formatting
952
945
        pb = MockProgress()
953
946
        result = bzrlib.tests.TextTestResult(
954
 
            StringIO(),
 
947
            None,
955
948
            descriptions=0,
956
949
            verbosity=1,
957
950
            pb=pb,
958
951
            )
959
952
        test = self.get_passing_test()
960
 
        feature = tests.Feature()
 
953
        feature = Feature()
961
954
        # this seeds the state to handle reporting the test.
962
955
        result.startTest(test)
 
956
        result.extractBenchmarkTime(test)
963
957
        result.report_unsupported(test, feature)
964
958
        # no output on unsupported features
965
959
        self.assertEqual(
972
966
        test.run(result)
973
967
        self.assertEqual(
974
968
            [
975
 
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
 
969
            ('update', '[2 in 0s, 2 missing features] passing_test', None, None),
976
970
            ],
977
971
            pb.calls[1:])
978
 
 
 
972
    
979
973
    def test_unavailable_exception(self):
980
974
        """An UnavailableFeature being raised should invoke addNotSupported."""
981
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
982
 
            def done(self): pass
983
 
            def startTests(self): pass
 
975
        class InstrumentedTestResult(ExtendedTestResult):
 
976
 
984
977
            def report_test_start(self, test): pass
985
978
            def addNotSupported(self, test, feature):
986
979
                self._call = test, feature
987
980
        result = InstrumentedTestResult(None, None, None, None)
988
 
        feature = tests.Feature()
 
981
        feature = Feature()
989
982
        def test_function():
990
 
            raise tests.UnavailableFeature(feature)
 
983
            raise UnavailableFeature(feature)
991
984
        test = unittest.FunctionTestCase(test_function)
992
985
        test.run(result)
993
986
        # it should invoke 'addNotSupported'.
999
992
 
1000
993
    def test_strict_with_unsupported_feature(self):
1001
994
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1002
 
                                             verbosity=1)
 
995
                                                verbosity=1)
1003
996
        test = self.get_passing_test()
1004
997
        feature = "Unsupported Feature"
1005
998
        result.addNotSupported(test, feature)
1006
999
        self.assertFalse(result.wasStrictlySuccessful())
1007
 
        self.assertEqual(None, result._extractBenchmarkTime(test))
1008
1000
 
1009
1001
    def test_strict_with_known_failure(self):
1010
1002
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1011
 
                                             verbosity=1)
 
1003
                                                verbosity=1)
1012
1004
        test = self.get_passing_test()
1013
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
1014
 
        result._addKnownFailure(test, err)
 
1005
        err = (KnownFailure, KnownFailure('foo'), None)
 
1006
        result.addKnownFailure(test, err)
1015
1007
        self.assertFalse(result.wasStrictlySuccessful())
1016
 
        self.assertEqual(None, result._extractBenchmarkTime(test))
1017
1008
 
1018
1009
    def test_strict_with_success(self):
1019
1010
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1020
 
                                             verbosity=1)
 
1011
                                                verbosity=1)
1021
1012
        test = self.get_passing_test()
1022
1013
        result.addSuccess(test)
1023
1014
        self.assertTrue(result.wasStrictlySuccessful())
1024
 
        self.assertEqual(None, result._extractBenchmarkTime(test))
1025
 
 
1026
 
    def test_startTests(self):
1027
 
        """Starting the first test should trigger startTests."""
1028
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
1029
 
            calls = 0
1030
 
            def startTests(self): self.calls += 1
1031
 
            def report_test_start(self, test): pass
1032
 
        result = InstrumentedTestResult(None, None, None, None)
1033
 
        def test_function():
1034
 
            pass
1035
 
        test = unittest.FunctionTestCase(test_function)
1036
 
        test.run(result)
1037
 
        self.assertEquals(1, result.calls)
1038
 
 
1039
 
 
1040
 
class TestUnicodeFilenameFeature(tests.TestCase):
1041
 
 
1042
 
    def test_probe_passes(self):
1043
 
        """UnicodeFilenameFeature._probe passes."""
1044
 
        # We can't test much more than that because the behaviour depends
1045
 
        # on the platform.
1046
 
        tests.UnicodeFilenameFeature._probe()
1047
 
 
1048
 
 
1049
 
class TestRunner(tests.TestCase):
 
1015
 
 
1016
 
 
1017
class TestRunner(TestCase):
1050
1018
 
1051
1019
    def dummy_test(self):
1052
1020
        pass
1056
1024
 
1057
1025
        This current saves and restores:
1058
1026
        TestCaseInTempDir.TEST_ROOT
1059
 
 
1060
 
        There should be no tests in this file that use
1061
 
        bzrlib.tests.TextTestRunner without using this convenience method,
1062
 
        because of our use of global state.
 
1027
        
 
1028
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
 
1029
        without using this convenience method, because of our use of global state.
1063
1030
        """
1064
 
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1031
        old_root = TestCaseInTempDir.TEST_ROOT
1065
1032
        try:
1066
 
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1033
            TestCaseInTempDir.TEST_ROOT = None
1067
1034
            return testrunner.run(test)
1068
1035
        finally:
1069
 
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1036
            TestCaseInTempDir.TEST_ROOT = old_root
1070
1037
 
1071
1038
    def test_known_failure_failed_run(self):
1072
1039
        # run a test that generates a known failure which should be printed in
1073
1040
        # the final output when real failures occur.
1074
1041
        def known_failure_test():
1075
 
            raise tests.KnownFailure('failed')
 
1042
            raise KnownFailure('failed')
1076
1043
        test = unittest.TestSuite()
1077
1044
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1078
1045
        def failing_test():
1079
1046
            raise AssertionError('foo')
1080
1047
        test.addTest(unittest.FunctionTestCase(failing_test))
1081
1048
        stream = StringIO()
1082
 
        runner = tests.TextTestRunner(stream=stream)
 
1049
        runner = TextTestRunner(stream=stream)
1083
1050
        result = self.run_test_runner(runner, test)
1084
1051
        lines = stream.getvalue().splitlines()
1085
1052
        self.assertEqual([
1094
1061
            '----------------------------------------------------------------------',
1095
1062
            '',
1096
1063
            'FAILED (failures=1, known_failure_count=1)'],
1097
 
            lines[3:8] + lines[9:13] + lines[14:])
 
1064
            lines[0:5] + lines[6:10] + lines[11:])
1098
1065
 
1099
1066
    def test_known_failure_ok_run(self):
1100
1067
        # run a test that generates a known failure which should be printed in the final output.
1101
1068
        def known_failure_test():
1102
 
            raise tests.KnownFailure('failed')
 
1069
            raise KnownFailure('failed')
1103
1070
        test = unittest.FunctionTestCase(known_failure_test)
1104
1071
        stream = StringIO()
1105
 
        runner = tests.TextTestRunner(stream=stream)
 
1072
        runner = TextTestRunner(stream=stream)
1106
1073
        result = self.run_test_runner(runner, test)
1107
1074
        self.assertContainsRe(stream.getvalue(),
1108
1075
            '\n'
1115
1082
        # run a test that is skipped, and check the suite as a whole still
1116
1083
        # succeeds.
1117
1084
        # skipping_test must be hidden in here so it's not run as a real test
1118
 
        class SkippingTest(tests.TestCase):
1119
 
            def skipping_test(self):
1120
 
                raise tests.TestSkipped('test intentionally skipped')
1121
 
        runner = tests.TextTestRunner(stream=self._log_file)
1122
 
        test = SkippingTest("skipping_test")
 
1085
        def skipping_test():
 
1086
            raise TestSkipped('test intentionally skipped')
 
1087
 
 
1088
        runner = TextTestRunner(stream=self._log_file)
 
1089
        test = unittest.FunctionTestCase(skipping_test)
1123
1090
        result = self.run_test_runner(runner, test)
1124
1091
        self.assertTrue(result.wasSuccessful())
1125
1092
 
1126
1093
    def test_skipped_from_setup(self):
1127
 
        calls = []
1128
 
        class SkippedSetupTest(tests.TestCase):
 
1094
        class SkippedSetupTest(TestCase):
1129
1095
 
1130
1096
            def setUp(self):
1131
 
                calls.append('setUp')
 
1097
                self.counter = 1
1132
1098
                self.addCleanup(self.cleanup)
1133
 
                raise tests.TestSkipped('skipped setup')
 
1099
                raise TestSkipped('skipped setup')
1134
1100
 
1135
1101
            def test_skip(self):
1136
1102
                self.fail('test reached')
1137
1103
 
1138
1104
            def cleanup(self):
1139
 
                calls.append('cleanup')
 
1105
                self.counter -= 1
1140
1106
 
1141
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1107
        runner = TextTestRunner(stream=self._log_file)
1142
1108
        test = SkippedSetupTest('test_skip')
1143
1109
        result = self.run_test_runner(runner, test)
1144
1110
        self.assertTrue(result.wasSuccessful())
1145
1111
        # Check if cleanup was called the right number of times.
1146
 
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1112
        self.assertEqual(0, test.counter)
1147
1113
 
1148
1114
    def test_skipped_from_test(self):
1149
 
        calls = []
1150
 
        class SkippedTest(tests.TestCase):
 
1115
        class SkippedTest(TestCase):
1151
1116
 
1152
1117
            def setUp(self):
1153
 
                tests.TestCase.setUp(self)
1154
 
                calls.append('setUp')
 
1118
                self.counter = 1
1155
1119
                self.addCleanup(self.cleanup)
1156
1120
 
1157
1121
            def test_skip(self):
1158
 
                raise tests.TestSkipped('skipped test')
 
1122
                raise TestSkipped('skipped test')
1159
1123
 
1160
1124
            def cleanup(self):
1161
 
                calls.append('cleanup')
 
1125
                self.counter -= 1
1162
1126
 
1163
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1127
        runner = TextTestRunner(stream=self._log_file)
1164
1128
        test = SkippedTest('test_skip')
1165
1129
        result = self.run_test_runner(runner, test)
1166
1130
        self.assertTrue(result.wasSuccessful())
1167
1131
        # Check if cleanup was called the right number of times.
1168
 
        self.assertEqual(['setUp', 'cleanup'], calls)
1169
 
 
1170
 
    def test_not_applicable(self):
1171
 
        # run a test that is skipped because it's not applicable
1172
 
        def not_applicable_test():
1173
 
            raise tests.TestNotApplicable('this test never runs')
1174
 
        out = StringIO()
1175
 
        runner = tests.TextTestRunner(stream=out, verbosity=2)
1176
 
        test = unittest.FunctionTestCase(not_applicable_test)
1177
 
        result = self.run_test_runner(runner, test)
1178
 
        self._log_file.write(out.getvalue())
1179
 
        self.assertTrue(result.wasSuccessful())
1180
 
        self.assertTrue(result.wasStrictlySuccessful())
1181
 
        self.assertContainsRe(out.getvalue(),
1182
 
                r'(?m)not_applicable_test   * N/A')
1183
 
        self.assertContainsRe(out.getvalue(),
1184
 
                r'(?m)^    this test never runs')
1185
 
 
1186
 
    def test_not_applicable_demo(self):
1187
 
        # just so you can see it in the test output
1188
 
        raise tests.TestNotApplicable('this test is just a demonstation')
 
1132
        self.assertEqual(0, test.counter)
1189
1133
 
1190
1134
    def test_unsupported_features_listed(self):
1191
1135
        """When unsupported features are encountered they are detailed."""
1192
 
        class Feature1(tests.Feature):
 
1136
        class Feature1(Feature):
1193
1137
            def _probe(self): return False
1194
 
        class Feature2(tests.Feature):
 
1138
        class Feature2(Feature):
1195
1139
            def _probe(self): return False
1196
1140
        # create sample tests
1197
1141
        test1 = SampleTestCase('_test_pass')
1202
1146
        test.addTest(test1)
1203
1147
        test.addTest(test2)
1204
1148
        stream = StringIO()
1205
 
        runner = tests.TextTestRunner(stream=stream)
 
1149
        runner = TextTestRunner(stream=stream)
1206
1150
        result = self.run_test_runner(runner, test)
1207
1151
        lines = stream.getvalue().splitlines()
1208
1152
        self.assertEqual([
1219
1163
        workingtree = _get_bzr_source_tree()
1220
1164
        test = TestRunner('dummy_test')
1221
1165
        output = StringIO()
1222
 
        runner = tests.TextTestRunner(stream=self._log_file,
1223
 
                                      bench_history=output)
 
1166
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
1224
1167
        result = self.run_test_runner(runner, test)
1225
1168
        output_string = output.getvalue()
1226
1169
        self.assertContainsRe(output_string, "--date [0-9.]+")
1228
1171
            revision_id = workingtree.get_parent_ids()[0]
1229
1172
            self.assertEndsWith(output_string.rstrip(), revision_id)
1230
1173
 
1231
 
    def assertLogDeleted(self, test):
1232
 
        log = test._get_log()
1233
 
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1234
 
        self.assertEqual('', test._log_contents)
1235
 
        self.assertIs(None, test._log_file_name)
1236
 
 
1237
1174
    def test_success_log_deleted(self):
1238
1175
        """Successful tests have their log deleted"""
1239
1176
 
1240
 
        class LogTester(tests.TestCase):
 
1177
        class LogTester(TestCase):
1241
1178
 
1242
1179
            def test_success(self):
1243
1180
                self.log('this will be removed\n')
1244
1181
 
1245
 
        sio = StringIO()
1246
 
        runner = tests.TextTestRunner(stream=sio)
 
1182
        sio = cStringIO.StringIO()
 
1183
        runner = TextTestRunner(stream=sio)
1247
1184
        test = LogTester('test_success')
1248
1185
        result = self.run_test_runner(runner, test)
1249
1186
 
1250
 
        self.assertLogDeleted(test)
1251
 
 
1252
 
    def test_skipped_log_deleted(self):
1253
 
        """Skipped tests have their log deleted"""
1254
 
 
1255
 
        class LogTester(tests.TestCase):
1256
 
 
1257
 
            def test_skipped(self):
1258
 
                self.log('this will be removed\n')
1259
 
                raise tests.TestSkipped()
1260
 
 
1261
 
        sio = StringIO()
1262
 
        runner = tests.TextTestRunner(stream=sio)
1263
 
        test = LogTester('test_skipped')
1264
 
        result = self.run_test_runner(runner, test)
1265
 
 
1266
 
        self.assertLogDeleted(test)
1267
 
 
1268
 
    def test_not_aplicable_log_deleted(self):
1269
 
        """Not applicable tests have their log deleted"""
1270
 
 
1271
 
        class LogTester(tests.TestCase):
1272
 
 
1273
 
            def test_not_applicable(self):
1274
 
                self.log('this will be removed\n')
1275
 
                raise tests.TestNotApplicable()
1276
 
 
1277
 
        sio = StringIO()
1278
 
        runner = tests.TextTestRunner(stream=sio)
1279
 
        test = LogTester('test_not_applicable')
1280
 
        result = self.run_test_runner(runner, test)
1281
 
 
1282
 
        self.assertLogDeleted(test)
1283
 
 
1284
 
    def test_known_failure_log_deleted(self):
1285
 
        """Know failure tests have their log deleted"""
1286
 
 
1287
 
        class LogTester(tests.TestCase):
1288
 
 
1289
 
            def test_known_failure(self):
1290
 
                self.log('this will be removed\n')
1291
 
                raise tests.KnownFailure()
1292
 
 
1293
 
        sio = StringIO()
1294
 
        runner = tests.TextTestRunner(stream=sio)
1295
 
        test = LogTester('test_known_failure')
1296
 
        result = self.run_test_runner(runner, test)
1297
 
 
1298
 
        self.assertLogDeleted(test)
 
1187
        log = test._get_log()
 
1188
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1189
        self.assertEqual('', test._log_contents)
 
1190
        self.assertIs(None, test._log_file_name)
1299
1191
 
1300
1192
    def test_fail_log_kept(self):
1301
1193
        """Failed tests have their log kept"""
1302
1194
 
1303
 
        class LogTester(tests.TestCase):
 
1195
        class LogTester(TestCase):
1304
1196
 
1305
1197
            def test_fail(self):
1306
1198
                self.log('this will be kept\n')
1307
1199
                self.fail('this test fails')
1308
1200
 
1309
 
        sio = StringIO()
1310
 
        runner = tests.TextTestRunner(stream=sio)
 
1201
        sio = cStringIO.StringIO()
 
1202
        runner = TextTestRunner(stream=sio)
1311
1203
        test = LogTester('test_fail')
1312
1204
        result = self.run_test_runner(runner, test)
1313
1205
 
1322
1214
    def test_error_log_kept(self):
1323
1215
        """Tests with errors have their log kept"""
1324
1216
 
1325
 
        class LogTester(tests.TestCase):
 
1217
        class LogTester(TestCase):
1326
1218
 
1327
1219
            def test_error(self):
1328
1220
                self.log('this will be kept\n')
1329
1221
                raise ValueError('random exception raised')
1330
1222
 
1331
 
        sio = StringIO()
1332
 
        runner = tests.TextTestRunner(stream=sio)
 
1223
        sio = cStringIO.StringIO()
 
1224
        runner = TextTestRunner(stream=sio)
1333
1225
        test = LogTester('test_error')
1334
1226
        result = self.run_test_runner(runner, test)
1335
1227
 
1342
1234
        self.assertEqual(log, test._log_contents)
1343
1235
 
1344
1236
 
1345
 
class SampleTestCase(tests.TestCase):
 
1237
class SampleTestCase(TestCase):
1346
1238
 
1347
1239
    def _test_pass(self):
1348
1240
        pass
1349
1241
 
1350
 
class _TestException(Exception):
1351
 
    pass
1352
1242
 
1353
 
class TestTestCase(tests.TestCase):
 
1243
class TestTestCase(TestCase):
1354
1244
    """Tests that test the core bzrlib TestCase."""
1355
1245
 
1356
 
    def test_assertLength_matches_empty(self):
1357
 
        a_list = []
1358
 
        self.assertLength(0, a_list)
1359
 
 
1360
 
    def test_assertLength_matches_nonempty(self):
1361
 
        a_list = [1, 2, 3]
1362
 
        self.assertLength(3, a_list)
1363
 
 
1364
 
    def test_assertLength_fails_different(self):
1365
 
        a_list = []
1366
 
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1367
 
 
1368
 
    def test_assertLength_shows_sequence_in_failure(self):
1369
 
        a_list = [1, 2, 3]
1370
 
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
1371
 
            a_list)
1372
 
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1373
 
            exception.args[0])
1374
 
 
1375
 
    def test_base_setUp_not_called_causes_failure(self):
1376
 
        class TestCaseWithBrokenSetUp(tests.TestCase):
1377
 
            def setUp(self):
1378
 
                pass # does not call TestCase.setUp
1379
 
            def test_foo(self):
1380
 
                pass
1381
 
        test = TestCaseWithBrokenSetUp('test_foo')
1382
 
        result = unittest.TestResult()
1383
 
        test.run(result)
1384
 
        self.assertFalse(result.wasSuccessful())
1385
 
        self.assertEqual(1, result.testsRun)
1386
 
 
1387
 
    def test_base_tearDown_not_called_causes_failure(self):
1388
 
        class TestCaseWithBrokenTearDown(tests.TestCase):
1389
 
            def tearDown(self):
1390
 
                pass # does not call TestCase.tearDown
1391
 
            def test_foo(self):
1392
 
                pass
1393
 
        test = TestCaseWithBrokenTearDown('test_foo')
1394
 
        result = unittest.TestResult()
1395
 
        test.run(result)
1396
 
        self.assertFalse(result.wasSuccessful())
1397
 
        self.assertEqual(1, result.testsRun)
1398
 
 
1399
1246
    def test_debug_flags_sanitised(self):
1400
1247
        """The bzrlib debug flags should be sanitised by setUp."""
1401
 
        if 'allow_debug' in tests.selftest_debug_flags:
1402
 
            raise tests.TestNotApplicable(
1403
 
                '-Eallow_debug option prevents debug flag sanitisation')
1404
1248
        # we could set something and run a test that will check
1405
1249
        # it gets santised, but this is probably sufficient for now:
1406
1250
        # if someone runs the test with -Dsomething it will error.
1407
1251
        self.assertEqual(set(), bzrlib.debug.debug_flags)
1408
1252
 
1409
 
    def change_selftest_debug_flags(self, new_flags):
1410
 
        orig_selftest_flags = tests.selftest_debug_flags
1411
 
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1412
 
        tests.selftest_debug_flags = set(new_flags)
1413
 
 
1414
 
    def _restore_selftest_debug_flags(self, flags):
1415
 
        tests.selftest_debug_flags = flags
1416
 
 
1417
 
    def test_allow_debug_flag(self):
1418
 
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1419
 
        sanitised (i.e. cleared) before running a test.
1420
 
        """
1421
 
        self.change_selftest_debug_flags(set(['allow_debug']))
1422
 
        bzrlib.debug.debug_flags = set(['a-flag'])
1423
 
        class TestThatRecordsFlags(tests.TestCase):
1424
 
            def test_foo(nested_self):
1425
 
                self.flags = set(bzrlib.debug.debug_flags)
1426
 
        test = TestThatRecordsFlags('test_foo')
1427
 
        test.run(self.make_test_result())
1428
 
        self.assertEqual(set(['a-flag']), self.flags)
1429
 
 
1430
 
    def test_debug_flags_restored(self):
1431
 
        """The bzrlib debug flags should be restored to their original state
1432
 
        after the test was run, even if allow_debug is set.
1433
 
        """
1434
 
        self.change_selftest_debug_flags(set(['allow_debug']))
1435
 
        # Now run a test that modifies debug.debug_flags.
1436
 
        bzrlib.debug.debug_flags = set(['original-state'])
1437
 
        class TestThatModifiesFlags(tests.TestCase):
1438
 
            def test_foo(self):
1439
 
                bzrlib.debug.debug_flags = set(['modified'])
1440
 
        test = TestThatModifiesFlags('test_foo')
1441
 
        test.run(self.make_test_result())
1442
 
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1443
 
 
1444
 
    def make_test_result(self):
1445
 
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1446
 
 
1447
1253
    def inner_test(self):
1448
1254
        # the inner child test
1449
1255
        note("inner_test")
1452
1258
        # the outer child test
1453
1259
        note("outer_start")
1454
1260
        self.inner_test = TestTestCase("inner_child")
1455
 
        result = self.make_test_result()
 
1261
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1262
                                        descriptions=0,
 
1263
                                        verbosity=1)
1456
1264
        self.inner_test.run(result)
1457
1265
        note("outer finish")
1458
1266
 
1462
1270
        # should setup a new log, log content to it, setup a child case (B),
1463
1271
        # which should log independently, then case (A) should log a trailer
1464
1272
        # and return.
1465
 
        # we do two nested children so that we can verify the state of the
 
1273
        # we do two nested children so that we can verify the state of the 
1466
1274
        # logs after the outer child finishes is correct, which a bad clean
1467
1275
        # up routine in tearDown might trigger a fault in our test with only
1468
1276
        # one child, we should instead see the bad result inside our test with
1470
1278
        # the outer child test
1471
1279
        original_trace = bzrlib.trace._trace_file
1472
1280
        outer_test = TestTestCase("outer_child")
1473
 
        result = self.make_test_result()
 
1281
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1282
                                        descriptions=0,
 
1283
                                        verbosity=1)
1474
1284
        outer_test.run(result)
1475
1285
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1476
1286
 
1491
1301
        sample_test.run(result)
1492
1302
        self.assertContainsRe(
1493
1303
            output_stream.getvalue(),
1494
 
            r"\d+ms\*\n$")
 
1304
            r"\d+ms/ +\d+ms\n$")
1495
1305
 
1496
1306
    def test_hooks_sanitised(self):
1497
1307
        """The bzrlib hooks should be sanitised by setUp."""
1498
 
        # Note this test won't fail with hooks that the core library doesn't
1499
 
        # use - but it trigger with a plugin that adds hooks, so its still a
1500
 
        # useful warning in that case.
1501
1308
        self.assertEqual(bzrlib.branch.BranchHooks(),
1502
1309
            bzrlib.branch.Branch.hooks)
1503
1310
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1504
1311
            bzrlib.smart.server.SmartTCPServer.hooks)
1505
 
        self.assertEqual(bzrlib.commands.CommandHooks(),
1506
 
            bzrlib.commands.Command.hooks)
1507
1312
 
1508
1313
    def test__gather_lsprof_in_benchmarks(self):
1509
1314
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1510
 
 
 
1315
        
1511
1316
        Each self.time() call is individually and separately profiled.
1512
1317
        """
1513
1318
        self.requireFeature(test_lsprof.LSProfFeature)
1514
 
        # overrides the class member with an instance member so no cleanup
 
1319
        # overrides the class member with an instance member so no cleanup 
1515
1320
        # needed.
1516
1321
        self._gather_lsprof_in_benchmarks = True
1517
1322
        self.time(time.sleep, 0.000)
1524
1329
 
1525
1330
    def test_knownFailure(self):
1526
1331
        """Self.knownFailure() should raise a KnownFailure exception."""
1527
 
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1332
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1528
1333
 
1529
1334
    def test_requireFeature_available(self):
1530
1335
        """self.requireFeature(available) is a no-op."""
1531
 
        class Available(tests.Feature):
 
1336
        class Available(Feature):
1532
1337
            def _probe(self):return True
1533
1338
        feature = Available()
1534
1339
        self.requireFeature(feature)
1535
1340
 
1536
1341
    def test_requireFeature_unavailable(self):
1537
1342
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1538
 
        class Unavailable(tests.Feature):
 
1343
        class Unavailable(Feature):
1539
1344
            def _probe(self):return False
1540
1345
        feature = Unavailable()
1541
 
        self.assertRaises(tests.UnavailableFeature,
1542
 
                          self.requireFeature, feature)
 
1346
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1543
1347
 
1544
1348
    def test_run_no_parameters(self):
1545
1349
        test = SampleTestCase('_test_pass')
1546
1350
        test.run()
1547
 
 
 
1351
    
1548
1352
    def test_run_enabled_unittest_result(self):
1549
1353
        """Test we revert to regular behaviour when the test is enabled."""
1550
1354
        test = SampleTestCase('_test_pass')
1598
1402
            ],
1599
1403
            result.calls)
1600
1404
 
1601
 
    def test_assert_list_raises_on_generator(self):
1602
 
        def generator_which_will_raise():
1603
 
            # This will not raise until after the first yield
1604
 
            yield 1
1605
 
            raise _TestException()
1606
 
 
1607
 
        e = self.assertListRaises(_TestException, generator_which_will_raise)
1608
 
        self.assertIsInstance(e, _TestException)
1609
 
 
1610
 
        e = self.assertListRaises(Exception, generator_which_will_raise)
1611
 
        self.assertIsInstance(e, _TestException)
1612
 
 
1613
 
    def test_assert_list_raises_on_plain(self):
1614
 
        def plain_exception():
1615
 
            raise _TestException()
1616
 
            return []
1617
 
 
1618
 
        e = self.assertListRaises(_TestException, plain_exception)
1619
 
        self.assertIsInstance(e, _TestException)
1620
 
 
1621
 
        e = self.assertListRaises(Exception, plain_exception)
1622
 
        self.assertIsInstance(e, _TestException)
1623
 
 
1624
 
    def test_assert_list_raises_assert_wrong_exception(self):
1625
 
        class _NotTestException(Exception):
1626
 
            pass
1627
 
 
1628
 
        def wrong_exception():
1629
 
            raise _NotTestException()
1630
 
 
1631
 
        def wrong_exception_generator():
1632
 
            yield 1
1633
 
            yield 2
1634
 
            raise _NotTestException()
1635
 
 
1636
 
        # Wrong exceptions are not intercepted
1637
 
        self.assertRaises(_NotTestException,
1638
 
            self.assertListRaises, _TestException, wrong_exception)
1639
 
        self.assertRaises(_NotTestException,
1640
 
            self.assertListRaises, _TestException, wrong_exception_generator)
1641
 
 
1642
 
    def test_assert_list_raises_no_exception(self):
1643
 
        def success():
1644
 
            return []
1645
 
 
1646
 
        def success_generator():
1647
 
            yield 1
1648
 
            yield 2
1649
 
 
1650
 
        self.assertRaises(AssertionError,
1651
 
            self.assertListRaises, _TestException, success)
1652
 
 
1653
 
        self.assertRaises(AssertionError,
1654
 
            self.assertListRaises, _TestException, success_generator)
1655
 
 
1656
 
 
1657
 
# NB: Don't delete this; it's not actually from 0.11!
1658
 
@deprecated_function(deprecated_in((0, 11, 0)))
 
1405
 
 
1406
@symbol_versioning.deprecated_function(zero_eleven)
1659
1407
def sample_deprecated_function():
1660
1408
    """A deprecated function to test applyDeprecated with."""
1661
1409
    return 2
1668
1416
class ApplyDeprecatedHelper(object):
1669
1417
    """A helper class for ApplyDeprecated tests."""
1670
1418
 
1671
 
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1419
    @symbol_versioning.deprecated_method(zero_eleven)
1672
1420
    def sample_deprecated_method(self, param_one):
1673
1421
        """A deprecated method for testing with."""
1674
1422
        return param_one
1676
1424
    def sample_normal_method(self):
1677
1425
        """A undeprecated method."""
1678
1426
 
1679
 
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1427
    @symbol_versioning.deprecated_method(zero_ten)
1680
1428
    def sample_nested_deprecation(self):
1681
1429
        return sample_deprecated_function()
1682
1430
 
1683
1431
 
1684
 
class TestExtraAssertions(tests.TestCase):
 
1432
class TestExtraAssertions(TestCase):
1685
1433
    """Tests for new test assertions in bzrlib test suite"""
1686
1434
 
1687
1435
    def test_assert_isinstance(self):
1688
1436
        self.assertIsInstance(2, int)
1689
1437
        self.assertIsInstance(u'', basestring)
1690
 
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1691
 
        self.assertEquals(str(e),
1692
 
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
 
1438
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1693
1439
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1694
 
        e = self.assertRaises(AssertionError,
1695
 
            self.assertIsInstance, None, int, "it's just not")
1696
 
        self.assertEquals(str(e),
1697
 
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
1698
 
            ": it's just not")
1699
1440
 
1700
1441
    def test_assertEndsWith(self):
1701
1442
        self.assertEndsWith('foo', 'oo')
1704
1445
    def test_applyDeprecated_not_deprecated(self):
1705
1446
        sample_object = ApplyDeprecatedHelper()
1706
1447
        # calling an undeprecated callable raises an assertion
1707
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1708
 
            deprecated_in((0, 11, 0)),
 
1448
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1709
1449
            sample_object.sample_normal_method)
1710
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1711
 
            deprecated_in((0, 11, 0)),
 
1450
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1712
1451
            sample_undeprecated_function, "a param value")
1713
1452
        # calling a deprecated callable (function or method) with the wrong
1714
1453
        # expected deprecation fails.
1715
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1716
 
            deprecated_in((0, 10, 0)),
 
1454
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1717
1455
            sample_object.sample_deprecated_method, "a param value")
1718
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1719
 
            deprecated_in((0, 10, 0)),
 
1456
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1720
1457
            sample_deprecated_function)
1721
1458
        # calling a deprecated callable (function or method) with the right
1722
1459
        # expected deprecation returns the functions result.
1723
 
        self.assertEqual("a param value",
1724
 
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1460
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1725
1461
            sample_object.sample_deprecated_method, "a param value"))
1726
 
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1462
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
1727
1463
            sample_deprecated_function))
1728
1464
        # calling a nested deprecation with the wrong deprecation version
1729
 
        # fails even if a deeper nested function was deprecated with the
 
1465
        # fails even if a deeper nested function was deprecated with the 
1730
1466
        # supplied version.
1731
1467
        self.assertRaises(AssertionError, self.applyDeprecated,
1732
 
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1468
            zero_eleven, sample_object.sample_nested_deprecation)
1733
1469
        # calling a nested deprecation with the right deprecation value
1734
1470
        # returns the calls result.
1735
 
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1471
        self.assertEqual(2, self.applyDeprecated(zero_ten,
1736
1472
            sample_object.sample_nested_deprecation))
1737
1473
 
1738
1474
    def test_callDeprecated(self):
1739
1475
        def testfunc(be_deprecated, result=None):
1740
1476
            if be_deprecated is True:
1741
 
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1477
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
1742
1478
                                       stacklevel=1)
1743
1479
            return result
1744
1480
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1749
1485
        self.callDeprecated([], testfunc, be_deprecated=False)
1750
1486
 
1751
1487
 
1752
 
class TestWarningTests(tests.TestCase):
1753
 
    """Tests for calling methods that raise warnings."""
1754
 
 
1755
 
    def test_callCatchWarnings(self):
1756
 
        def meth(a, b):
1757
 
            warnings.warn("this is your last warning")
1758
 
            return a + b
1759
 
        wlist, result = self.callCatchWarnings(meth, 1, 2)
1760
 
        self.assertEquals(3, result)
1761
 
        # would like just to compare them, but UserWarning doesn't implement
1762
 
        # eq well
1763
 
        w0, = wlist
1764
 
        self.assertIsInstance(w0, UserWarning)
1765
 
        self.assertEquals("this is your last warning", str(w0))
1766
 
 
1767
 
 
1768
 
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1488
class TestConvenienceMakers(TestCaseWithTransport):
1769
1489
    """Test for the make_* convenience functions."""
1770
1490
 
1771
1491
    def test_make_branch_and_tree_with_format(self):
1784
1504
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1785
1505
 
1786
1506
 
1787
 
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
 
1507
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1788
1508
 
1789
1509
    def test_make_tree_for_sftp_branch(self):
1790
1510
        """Transports backed by local directories create local trees."""
1799
1519
                tree.branch.repository.bzrdir.root_transport)
1800
1520
 
1801
1521
 
1802
 
class TestSelftest(tests.TestCase):
 
1522
class TestSelftest(TestCase):
1803
1523
    """Tests of bzrlib.tests.selftest."""
1804
1524
 
1805
1525
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1806
1526
        factory_called = []
1807
1527
        def factory():
1808
1528
            factory_called.append(True)
1809
 
            return TestUtil.TestSuite()
 
1529
            return TestSuite()
1810
1530
        out = StringIO()
1811
1531
        err = StringIO()
1812
 
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1532
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
1813
1533
            test_suite_factory=factory)
1814
1534
        self.assertEqual([True], factory_called)
1815
1535
 
1816
1536
 
1817
 
class TestKnownFailure(tests.TestCase):
 
1537
class TestKnownFailure(TestCase):
1818
1538
 
1819
1539
    def test_known_failure(self):
1820
1540
        """Check that KnownFailure is defined appropriately."""
1821
1541
        # a KnownFailure is an assertion error for compatability with unaware
1822
1542
        # runners.
1823
 
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
1543
        self.assertIsInstance(KnownFailure(""), AssertionError)
1824
1544
 
1825
1545
    def test_expect_failure(self):
1826
1546
        try:
1827
1547
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1828
 
        except tests.KnownFailure, e:
 
1548
        except KnownFailure, e:
1829
1549
            self.assertEqual('Doomed to failure', e.args[0])
1830
1550
        try:
1831
1551
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1836
1556
            self.fail('Assertion not raised')
1837
1557
 
1838
1558
 
1839
 
class TestFeature(tests.TestCase):
 
1559
class TestFeature(TestCase):
1840
1560
 
1841
1561
    def test_caching(self):
1842
1562
        """Feature._probe is called by the feature at most once."""
1843
 
        class InstrumentedFeature(tests.Feature):
 
1563
        class InstrumentedFeature(Feature):
1844
1564
            def __init__(self):
1845
 
                super(InstrumentedFeature, self).__init__()
 
1565
                Feature.__init__(self)
1846
1566
                self.calls = []
1847
1567
            def _probe(self):
1848
1568
                self.calls.append('_probe')
1855
1575
 
1856
1576
    def test_named_str(self):
1857
1577
        """Feature.__str__ should thunk to feature_name()."""
1858
 
        class NamedFeature(tests.Feature):
 
1578
        class NamedFeature(Feature):
1859
1579
            def feature_name(self):
1860
1580
                return 'symlinks'
1861
1581
        feature = NamedFeature()
1863
1583
 
1864
1584
    def test_default_str(self):
1865
1585
        """Feature.__str__ should default to __class__.__name__."""
1866
 
        class NamedFeature(tests.Feature):
 
1586
        class NamedFeature(Feature):
1867
1587
            pass
1868
1588
        feature = NamedFeature()
1869
1589
        self.assertEqual('NamedFeature', str(feature))
1870
1590
 
1871
1591
 
1872
 
class TestUnavailableFeature(tests.TestCase):
 
1592
class TestUnavailableFeature(TestCase):
1873
1593
 
1874
1594
    def test_access_feature(self):
1875
 
        feature = tests.Feature()
1876
 
        exception = tests.UnavailableFeature(feature)
 
1595
        feature = Feature()
 
1596
        exception = UnavailableFeature(feature)
1877
1597
        self.assertIs(feature, exception.args[0])
1878
1598
 
1879
1599
 
1880
 
class TestSelftestFiltering(tests.TestCase):
 
1600
class TestSelftestFiltering(TestCase):
1881
1601
 
1882
1602
    def setUp(self):
1883
 
        tests.TestCase.setUp(self)
1884
1603
        self.suite = TestUtil.TestSuite()
1885
1604
        self.loader = TestUtil.TestLoader()
1886
1605
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1887
1606
            'bzrlib.tests.test_selftest']))
1888
 
        self.all_names = _test_ids(self.suite)
1889
 
 
1890
 
    def test_condition_id_re(self):
1891
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1892
 
            'test_condition_id_re')
1893
 
        filtered_suite = tests.filter_suite_by_condition(
1894
 
            self.suite, tests.condition_id_re('test_condition_id_re'))
1895
 
        self.assertEqual([test_name], _test_ids(filtered_suite))
1896
 
 
1897
 
    def test_condition_id_in_list(self):
1898
 
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1899
 
                      'test_condition_id_in_list']
1900
 
        id_list = tests.TestIdList(test_names)
1901
 
        filtered_suite = tests.filter_suite_by_condition(
1902
 
            self.suite, tests.condition_id_in_list(id_list))
1903
 
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1904
 
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
1905
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1906
 
 
1907
 
    def test_condition_id_startswith(self):
1908
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1909
 
        start1 = klass + 'test_condition_id_starts'
1910
 
        start2 = klass + 'test_condition_id_in'
1911
 
        test_names = [ klass + 'test_condition_id_in_list',
1912
 
                      klass + 'test_condition_id_startswith',
1913
 
                     ]
1914
 
        filtered_suite = tests.filter_suite_by_condition(
1915
 
            self.suite, tests.condition_id_startswith([start1, start2]))
1916
 
        self.assertEqual(test_names, _test_ids(filtered_suite))
1917
 
 
1918
 
    def test_condition_isinstance(self):
1919
 
        filtered_suite = tests.filter_suite_by_condition(
1920
 
            self.suite, tests.condition_isinstance(self.__class__))
1921
 
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1922
 
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
1923
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1924
 
 
1925
 
    def test_exclude_tests_by_condition(self):
1926
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1927
 
            'test_exclude_tests_by_condition')
1928
 
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
1929
 
            lambda x:x.id() == excluded_name)
1930
 
        self.assertEqual(len(self.all_names) - 1,
1931
 
            filtered_suite.countTestCases())
1932
 
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
1933
 
        remaining_names = list(self.all_names)
1934
 
        remaining_names.remove(excluded_name)
1935
 
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
1936
 
 
1937
 
    def test_exclude_tests_by_re(self):
1938
 
        self.all_names = _test_ids(self.suite)
1939
 
        filtered_suite = tests.exclude_tests_by_re(self.suite,
1940
 
                                                   'exclude_tests_by_re')
1941
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1942
 
            'test_exclude_tests_by_re')
1943
 
        self.assertEqual(len(self.all_names) - 1,
1944
 
            filtered_suite.countTestCases())
1945
 
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
1946
 
        remaining_names = list(self.all_names)
1947
 
        remaining_names.remove(excluded_name)
1948
 
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
1949
 
 
1950
 
    def test_filter_suite_by_condition(self):
1951
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1952
 
            'test_filter_suite_by_condition')
1953
 
        filtered_suite = tests.filter_suite_by_condition(self.suite,
1954
 
            lambda x:x.id() == test_name)
1955
 
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1607
        self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
1956
1608
 
1957
1609
    def test_filter_suite_by_re(self):
1958
 
        filtered_suite = tests.filter_suite_by_re(self.suite,
1959
 
                                                  'test_filter_suite_by_r')
1960
 
        filtered_names = _test_ids(filtered_suite)
 
1610
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
 
1611
        filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
1961
1612
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1962
1613
            'TestSelftestFiltering.test_filter_suite_by_re'])
1963
 
 
1964
 
    def test_filter_suite_by_id_list(self):
1965
 
        test_list = ['bzrlib.tests.test_selftest.'
1966
 
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
1967
 
        filtered_suite = tests.filter_suite_by_id_list(
1968
 
            self.suite, tests.TestIdList(test_list))
1969
 
        filtered_names = _test_ids(filtered_suite)
1970
 
        self.assertEqual(
1971
 
            filtered_names,
1972
 
            ['bzrlib.tests.test_selftest.'
1973
 
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
1974
 
 
1975
 
    def test_filter_suite_by_id_startswith(self):
1976
 
        # By design this test may fail if another test is added whose name also
1977
 
        # begins with one of the start value used.
1978
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1979
 
        start1 = klass + 'test_filter_suite_by_id_starts'
1980
 
        start2 = klass + 'test_filter_suite_by_id_li'
1981
 
        test_list = [klass + 'test_filter_suite_by_id_list',
1982
 
                     klass + 'test_filter_suite_by_id_startswith',
1983
 
                     ]
1984
 
        filtered_suite = tests.filter_suite_by_id_startswith(
1985
 
            self.suite, [start1, start2])
1986
 
        self.assertEqual(
1987
 
            test_list,
1988
 
            _test_ids(filtered_suite),
1989
 
            )
1990
 
 
1991
 
    def test_preserve_input(self):
1992
 
        # NB: Surely this is something in the stdlib to do this?
1993
 
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
1994
 
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
1995
 
 
1996
 
    def test_randomize_suite(self):
1997
 
        randomized_suite = tests.randomize_suite(self.suite)
1998
 
        # randomizing should not add or remove test names.
1999
 
        self.assertEqual(set(_test_ids(self.suite)),
2000
 
                         set(_test_ids(randomized_suite)))
2001
 
        # Technically, this *can* fail, because random.shuffle(list) can be
2002
 
        # equal to list. Trying multiple times just pushes the frequency back.
2003
 
        # As its len(self.all_names)!:1, the failure frequency should be low
2004
 
        # enough to ignore. RBC 20071021.
2005
 
        # It should change the order.
2006
 
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2007
 
        # But not the length. (Possibly redundant with the set test, but not
2008
 
        # necessarily.)
2009
 
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2010
 
 
2011
 
    def test_split_suit_by_condition(self):
2012
 
        self.all_names = _test_ids(self.suite)
2013
 
        condition = tests.condition_id_re('test_filter_suite_by_r')
2014
 
        split_suite = tests.split_suite_by_condition(self.suite, condition)
2015
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2016
 
            'test_filter_suite_by_re')
2017
 
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2018
 
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2019
 
        remaining_names = list(self.all_names)
2020
 
        remaining_names.remove(filtered_name)
2021
 
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2022
 
 
2023
 
    def test_split_suit_by_re(self):
2024
 
        self.all_names = _test_ids(self.suite)
2025
 
        split_suite = tests.split_suite_by_re(self.suite,
2026
 
                                              'test_filter_suite_by_r')
2027
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2028
 
            'test_filter_suite_by_re')
2029
 
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2030
 
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2031
 
        remaining_names = list(self.all_names)
2032
 
        remaining_names.remove(filtered_name)
2033
 
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2034
 
 
2035
 
 
2036
 
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
1614
            
 
1615
    def test_sort_suite_by_re(self):
 
1616
        sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
 
1617
        sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
 
1618
        self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
 
1619
            'TestSelftestFiltering.test_filter_suite_by_re')
 
1620
        self.assertEquals(sorted(self.all_names), sorted(sorted_names))
 
1621
 
 
1622
 
 
1623
class TestCheckInventoryShape(TestCaseWithTransport):
2037
1624
 
2038
1625
    def test_check_inventory_shape(self):
2039
1626
        files = ['a', 'b/', 'b/c']
2045
1632
            self.check_inventory_shape(tree.inventory, files)
2046
1633
        finally:
2047
1634
            tree.unlock()
2048
 
 
2049
 
 
2050
 
class TestBlackboxSupport(tests.TestCase):
2051
 
    """Tests for testsuite blackbox features."""
2052
 
 
2053
 
    def test_run_bzr_failure_not_caught(self):
2054
 
        # When we run bzr in blackbox mode, we want any unexpected errors to
2055
 
        # propagate up to the test suite so that it can show the error in the
2056
 
        # usual way, and we won't get a double traceback.
2057
 
        e = self.assertRaises(
2058
 
            AssertionError,
2059
 
            self.run_bzr, ['assert-fail'])
2060
 
        # make sure we got the real thing, not an error from somewhere else in
2061
 
        # the test framework
2062
 
        self.assertEquals('always fails', str(e))
2063
 
        # check that there's no traceback in the test log
2064
 
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
2065
 
            r'Traceback')
2066
 
 
2067
 
    def test_run_bzr_user_error_caught(self):
2068
 
        # Running bzr in blackbox mode, normal/expected/user errors should be
2069
 
        # caught in the regular way and turned into an error message plus exit
2070
 
        # code.
2071
 
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
2072
 
        self.assertEqual(out, '')
2073
 
        self.assertContainsRe(err,
2074
 
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2075
 
 
2076
 
 
2077
 
class TestTestLoader(tests.TestCase):
2078
 
    """Tests for the test loader."""
2079
 
 
2080
 
    def _get_loader_and_module(self):
2081
 
        """Gets a TestLoader and a module with one test in it."""
2082
 
        loader = TestUtil.TestLoader()
2083
 
        module = {}
2084
 
        class Stub(tests.TestCase):
2085
 
            def test_foo(self):
2086
 
                pass
2087
 
        class MyModule(object):
2088
 
            pass
2089
 
        MyModule.a_class = Stub
2090
 
        module = MyModule()
2091
 
        return loader, module
2092
 
 
2093
 
    def test_module_no_load_tests_attribute_loads_classes(self):
2094
 
        loader, module = self._get_loader_and_module()
2095
 
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2096
 
 
2097
 
    def test_module_load_tests_attribute_gets_called(self):
2098
 
        loader, module = self._get_loader_and_module()
2099
 
        # 'self' is here because we're faking the module with a class. Regular
2100
 
        # load_tests do not need that :)
2101
 
        def load_tests(self, standard_tests, module, loader):
2102
 
            result = loader.suiteClass()
2103
 
            for test in tests.iter_suite_tests(standard_tests):
2104
 
                result.addTests([test, test])
2105
 
            return result
2106
 
        # add a load_tests() method which multiplies the tests from the module.
2107
 
        module.__class__.load_tests = load_tests
2108
 
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2109
 
 
2110
 
    def test_load_tests_from_module_name_smoke_test(self):
2111
 
        loader = TestUtil.TestLoader()
2112
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2113
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2114
 
                          _test_ids(suite))
2115
 
 
2116
 
    def test_load_tests_from_module_name_with_bogus_module_name(self):
2117
 
        loader = TestUtil.TestLoader()
2118
 
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2119
 
 
2120
 
 
2121
 
class TestTestIdList(tests.TestCase):
2122
 
 
2123
 
    def _create_id_list(self, test_list):
2124
 
        return tests.TestIdList(test_list)
2125
 
 
2126
 
    def _create_suite(self, test_id_list):
2127
 
 
2128
 
        class Stub(tests.TestCase):
2129
 
            def test_foo(self):
2130
 
                pass
2131
 
 
2132
 
        def _create_test_id(id):
2133
 
            return lambda: id
2134
 
 
2135
 
        suite = TestUtil.TestSuite()
2136
 
        for id in test_id_list:
2137
 
            t  = Stub('test_foo')
2138
 
            t.id = _create_test_id(id)
2139
 
            suite.addTest(t)
2140
 
        return suite
2141
 
 
2142
 
    def _test_ids(self, test_suite):
2143
 
        """Get the ids for the tests in a test suite."""
2144
 
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
2145
 
 
2146
 
    def test_empty_list(self):
2147
 
        id_list = self._create_id_list([])
2148
 
        self.assertEquals({}, id_list.tests)
2149
 
        self.assertEquals({}, id_list.modules)
2150
 
 
2151
 
    def test_valid_list(self):
2152
 
        id_list = self._create_id_list(
2153
 
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
2154
 
             'mod1.func1', 'mod1.cl2.meth2',
2155
 
             'mod1.submod1',
2156
 
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2157
 
             ])
2158
 
        self.assertTrue(id_list.refers_to('mod1'))
2159
 
        self.assertTrue(id_list.refers_to('mod1.submod1'))
2160
 
        self.assertTrue(id_list.refers_to('mod1.submod2'))
2161
 
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2162
 
        self.assertTrue(id_list.includes('mod1.submod1'))
2163
 
        self.assertTrue(id_list.includes('mod1.func1'))
2164
 
 
2165
 
    def test_bad_chars_in_params(self):
2166
 
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2167
 
        self.assertTrue(id_list.refers_to('mod1'))
2168
 
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2169
 
 
2170
 
    def test_module_used(self):
2171
 
        id_list = self._create_id_list(['mod.class.meth'])
2172
 
        self.assertTrue(id_list.refers_to('mod'))
2173
 
        self.assertTrue(id_list.refers_to('mod.class'))
2174
 
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2175
 
 
2176
 
    def test_test_suite_matches_id_list_with_unknown(self):
2177
 
        loader = TestUtil.TestLoader()
2178
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2179
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2180
 
                     'bogus']
2181
 
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2182
 
        self.assertEquals(['bogus'], not_found)
2183
 
        self.assertEquals([], duplicates)
2184
 
 
2185
 
    def test_suite_matches_id_list_with_duplicates(self):
2186
 
        loader = TestUtil.TestLoader()
2187
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2188
 
        dupes = loader.suiteClass()
2189
 
        for test in tests.iter_suite_tests(suite):
2190
 
            dupes.addTest(test)
2191
 
            dupes.addTest(test) # Add it again
2192
 
 
2193
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2194
 
        not_found, duplicates = tests.suite_matches_id_list(
2195
 
            dupes, test_list)
2196
 
        self.assertEquals([], not_found)
2197
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2198
 
                          duplicates)
2199
 
 
2200
 
 
2201
 
class TestTestSuite(tests.TestCase):
2202
 
 
2203
 
    def test_test_suite(self):
2204
 
        # This test is slow, so we do a single test with one test in each
2205
 
        # category
2206
 
        test_list = [
2207
 
            # testmod_names
2208
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2209
 
            ('bzrlib.tests.per_transport.TransportTests'
2210
 
             '.test_abspath(LocalURLServer)'),
2211
 
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2212
 
            # modules_to_doctest
2213
 
            'bzrlib.timestamp.format_highres_date',
2214
 
            # plugins can't be tested that way since selftest may be run with
2215
 
            # --no-plugins
2216
 
            ]
2217
 
        suite = tests.test_suite(test_list)
2218
 
        self.assertEquals(test_list, _test_ids(suite))
2219
 
 
2220
 
    def test_test_suite_list_and_start(self):
2221
 
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2222
 
        suite = tests.test_suite(test_list,
2223
 
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
2224
 
        # test_test_suite_list_and_start is not included 
2225
 
        self.assertEquals(test_list, _test_ids(suite))
2226
 
 
2227
 
 
2228
 
class TestLoadTestIdList(tests.TestCaseInTempDir):
2229
 
 
2230
 
    def _create_test_list_file(self, file_name, content):
2231
 
        fl = open(file_name, 'wt')
2232
 
        fl.write(content)
2233
 
        fl.close()
2234
 
 
2235
 
    def test_load_unknown(self):
2236
 
        self.assertRaises(errors.NoSuchFile,
2237
 
                          tests.load_test_id_list, 'i_do_not_exist')
2238
 
 
2239
 
    def test_load_test_list(self):
2240
 
        test_list_fname = 'test.list'
2241
 
        self._create_test_list_file(test_list_fname,
2242
 
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2243
 
        tlist = tests.load_test_id_list(test_list_fname)
2244
 
        self.assertEquals(2, len(tlist))
2245
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2246
 
        self.assertEquals('mod2.cl2.meth2', tlist[1])
2247
 
 
2248
 
    def test_load_dirty_file(self):
2249
 
        test_list_fname = 'test.list'
2250
 
        self._create_test_list_file(test_list_fname,
2251
 
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
2252
 
                                    'bar baz\n')
2253
 
        tlist = tests.load_test_id_list(test_list_fname)
2254
 
        self.assertEquals(4, len(tlist))
2255
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2256
 
        self.assertEquals('', tlist[1])
2257
 
        self.assertEquals('mod2.cl2.meth2', tlist[2])
2258
 
        self.assertEquals('bar baz', tlist[3])
2259
 
 
2260
 
 
2261
 
class TestFilteredByModuleTestLoader(tests.TestCase):
2262
 
 
2263
 
    def _create_loader(self, test_list):
2264
 
        id_filter = tests.TestIdList(test_list)
2265
 
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2266
 
        return loader
2267
 
 
2268
 
    def test_load_tests(self):
2269
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2270
 
        loader = self._create_loader(test_list)
2271
 
 
2272
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2273
 
        self.assertEquals(test_list, _test_ids(suite))
2274
 
 
2275
 
    def test_exclude_tests(self):
2276
 
        test_list = ['bogus']
2277
 
        loader = self._create_loader(test_list)
2278
 
 
2279
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2280
 
        self.assertEquals([], _test_ids(suite))
2281
 
 
2282
 
 
2283
 
class TestFilteredByNameStartTestLoader(tests.TestCase):
2284
 
 
2285
 
    def _create_loader(self, name_start):
2286
 
        def needs_module(name):
2287
 
            return name.startswith(name_start) or name_start.startswith(name)
2288
 
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2289
 
        return loader
2290
 
 
2291
 
    def test_load_tests(self):
2292
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2293
 
        loader = self._create_loader('bzrlib.tests.test_samp')
2294
 
 
2295
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2296
 
        self.assertEquals(test_list, _test_ids(suite))
2297
 
 
2298
 
    def test_load_tests_inside_module(self):
2299
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2300
 
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2301
 
 
2302
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2303
 
        self.assertEquals(test_list, _test_ids(suite))
2304
 
 
2305
 
    def test_exclude_tests(self):
2306
 
        test_list = ['bogus']
2307
 
        loader = self._create_loader('bogus')
2308
 
 
2309
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2310
 
        self.assertEquals([], _test_ids(suite))
2311
 
 
2312
 
 
2313
 
class TestTestPrefixRegistry(tests.TestCase):
2314
 
 
2315
 
    def _get_registry(self):
2316
 
        tp_registry = tests.TestPrefixAliasRegistry()
2317
 
        return tp_registry
2318
 
 
2319
 
    def test_register_new_prefix(self):
2320
 
        tpr = self._get_registry()
2321
 
        tpr.register('foo', 'fff.ooo.ooo')
2322
 
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2323
 
 
2324
 
    def test_register_existing_prefix(self):
2325
 
        tpr = self._get_registry()
2326
 
        tpr.register('bar', 'bbb.aaa.rrr')
2327
 
        tpr.register('bar', 'bBB.aAA.rRR')
2328
 
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2329
 
        self.assertContainsRe(self._get_log(keep_log_file=True),
2330
 
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2331
 
 
2332
 
    def test_get_unknown_prefix(self):
2333
 
        tpr = self._get_registry()
2334
 
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2335
 
 
2336
 
    def test_resolve_prefix(self):
2337
 
        tpr = self._get_registry()
2338
 
        tpr.register('bar', 'bb.aa.rr')
2339
 
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2340
 
 
2341
 
    def test_resolve_unknown_alias(self):
2342
 
        tpr = self._get_registry()
2343
 
        self.assertRaises(errors.BzrCommandError,
2344
 
                          tpr.resolve_alias, 'I am not a prefix')
2345
 
 
2346
 
    def test_predefined_prefixes(self):
2347
 
        tpr = tests.test_prefix_alias_registry
2348
 
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2349
 
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2350
 
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2351
 
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2352
 
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2353
 
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2354
 
 
2355
 
 
2356
 
class TestRunSuite(tests.TestCase):
2357
 
 
2358
 
    def test_runner_class(self):
2359
 
        """run_suite accepts and uses a runner_class keyword argument."""
2360
 
        class Stub(tests.TestCase):
2361
 
            def test_foo(self):
2362
 
                pass
2363
 
        suite = Stub("test_foo")
2364
 
        calls = []
2365
 
        class MyRunner(tests.TextTestRunner):
2366
 
            def run(self, test):
2367
 
                calls.append(test)
2368
 
                return tests.ExtendedTestResult(self.stream, self.descriptions,
2369
 
                                                self.verbosity)
2370
 
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2371
 
        self.assertEqual(calls, [suite])
2372
 
 
2373
 
    def test_done(self):
2374
 
        """run_suite should call result.done()"""
2375
 
        self.calls = 0
2376
 
        def one_more_call(): self.calls += 1
2377
 
        def test_function():
2378
 
            pass
2379
 
        test = unittest.FunctionTestCase(test_function)
2380
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
2381
 
            def done(self): one_more_call()
2382
 
        class MyRunner(tests.TextTestRunner):
2383
 
            def run(self, test):
2384
 
                return InstrumentedTestResult(self.stream, self.descriptions,
2385
 
                                              self.verbosity)
2386
 
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
2387
 
        self.assertEquals(1, self.calls)