~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

Initial commit for russian version of documents.

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, 2008 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
27
28
from bzrlib import (
28
29
    branchbuilder,
29
30
    bzrdir,
30
 
    debug,
31
31
    errors,
32
 
    lockdir,
33
32
    memorytree,
34
33
    osutils,
35
 
    progress,
36
34
    remote,
37
35
    repository,
38
36
    symbol_versioning,
39
37
    tests,
40
38
    workingtree,
41
39
    )
 
40
from bzrlib.progress import _BaseProgressBar
42
41
from bzrlib.repofmt import (
43
42
    pack_repo,
44
43
    weaverepo,
45
44
    )
46
45
from bzrlib.symbol_versioning import (
47
 
    deprecated_function,
48
 
    deprecated_in,
49
 
    deprecated_method,
 
46
    one_zero,
 
47
    zero_eleven,
 
48
    zero_ten,
50
49
    )
51
50
from bzrlib.tests import (
52
 
    test_lsprof,
53
 
    test_sftp_transport,
54
 
    TestUtil,
55
 
    )
 
51
                          ChrootedTestCase,
 
52
                          ExtendedTestResult,
 
53
                          Feature,
 
54
                          KnownFailure,
 
55
                          TestCase,
 
56
                          TestCaseInTempDir,
 
57
                          TestCaseWithMemoryTransport,
 
58
                          TestCaseWithTransport,
 
59
                          TestNotApplicable,
 
60
                          TestSkipped,
 
61
                          TestSuite,
 
62
                          TestUtil,
 
63
                          TextTestRunner,
 
64
                          UnavailableFeature,
 
65
                          condition_id_re,
 
66
                          condition_isinstance,
 
67
                          exclude_tests_by_condition,
 
68
                          exclude_tests_by_re,
 
69
                          filter_suite_by_condition,
 
70
                          filter_suite_by_re,
 
71
                          iter_suite_tests,
 
72
                          preserve_input,
 
73
                          randomize_suite,
 
74
                          split_suite_by_condition,
 
75
                          split_suite_by_re,
 
76
                          test_lsprof,
 
77
                          test_suite,
 
78
                          )
 
79
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
 
80
from bzrlib.tests.TestUtil import _load_module_by_name
56
81
from bzrlib.trace import note
57
82
from bzrlib.transport.memory import MemoryServer, MemoryTransport
58
83
from bzrlib.version import _get_bzr_source_tree
60
85
 
61
86
def _test_ids(test_suite):
62
87
    """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):
 
88
    return [t.id() for t in iter_suite_tests(test_suite)]
 
89
 
 
90
 
 
91
class SelftestTests(TestCase):
67
92
 
68
93
    def test_import_tests(self):
69
 
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
94
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
70
95
        self.assertEqual(mod.SelftestTests, SelftestTests)
71
96
 
72
97
    def test_import_test_failure(self):
73
98
        self.assertRaises(ImportError,
74
 
                          TestUtil._load_module_by_name,
 
99
                          _load_module_by_name,
75
100
                          'bzrlib.no-name-yet')
76
101
 
77
 
class MetaTestLog(tests.TestCase):
 
102
class MetaTestLog(TestCase):
78
103
 
79
104
    def test_logging(self):
80
105
        """Test logs are captured when a test fails."""
84
109
                              'a test message\n')
85
110
 
86
111
 
87
 
class TestUnicodeFilename(tests.TestCase):
 
112
class TestUnicodeFilename(TestCase):
88
113
 
89
114
    def test_probe_passes(self):
90
115
        """UnicodeFilename._probe passes."""
93
118
        tests.UnicodeFilename._probe()
94
119
 
95
120
 
96
 
class TestTreeShape(tests.TestCaseInTempDir):
 
121
class TestTreeShape(TestCaseInTempDir):
97
122
 
98
123
    def test_unicode_paths(self):
99
124
        self.requireFeature(tests.UnicodeFilename)
103
128
        self.failUnlessExists(filename)
104
129
 
105
130
 
106
 
class TestTransportScenarios(tests.TestCase):
 
131
class TestTransportProviderAdapter(TestCase):
107
132
    """A group of tests that test the transport implementation adaption core.
108
133
 
109
 
    This is a meta test that the tests are applied to all available
 
134
    This is a meta test that the tests are applied to all available 
110
135
    transports.
111
136
 
112
 
    This will be generalised in the future which is why it is in this
 
137
    This will be generalised in the future which is why it is in this 
113
138
    test file even though it is specific to transport tests at the moment.
114
139
    """
115
140
 
116
141
    def test_get_transport_permutations(self):
117
142
        # this checks that get_test_permutations defined by the module is
118
 
        # called by the get_transport_test_permutations function.
 
143
        # called by the adapter get_transport_test_permutations method.
119
144
        class MockModule(object):
120
145
            def get_test_permutations(self):
121
146
                return sample_permutation
122
147
        sample_permutation = [(1,2), (3,4)]
123
 
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
148
        from bzrlib.tests.test_transport_implementations \
 
149
            import TransportTestProviderAdapter
 
150
        adapter = TransportTestProviderAdapter()
124
151
        self.assertEqual(sample_permutation,
125
 
                         get_transport_test_permutations(MockModule()))
 
152
                         adapter.get_transport_test_permutations(MockModule()))
126
153
 
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
 
154
    def test_adapter_checks_all_modules(self):
 
155
        # this checks that the adapter returns as many permutations as there
 
156
        # are in all the registered transport modules - we assume if this
 
157
        # matches its probably doing the right thing especially in combination
 
158
        # with the tests for setting the right classes below.
 
159
        from bzrlib.tests.test_transport_implementations \
 
160
            import TransportTestProviderAdapter
133
161
        from bzrlib.transport import _get_transport_modules
134
162
        modules = _get_transport_modules()
135
163
        permutation_count = 0
136
164
        for module in modules:
137
165
            try:
138
 
                permutation_count += len(reduce(getattr,
 
166
                permutation_count += len(reduce(getattr, 
139
167
                    (module + ".get_test_permutations").split('.')[1:],
140
168
                     __import__(module))())
141
169
            except errors.DependencyNotPresent:
142
170
                pass
143
 
        scenarios = transport_test_permutations()
144
 
        self.assertEqual(permutation_count, len(scenarios))
 
171
        input_test = TestTransportProviderAdapter(
 
172
            "test_adapter_sets_transport_class")
 
173
        adapter = TransportTestProviderAdapter()
 
174
        self.assertEqual(permutation_count,
 
175
                         len(list(iter(adapter.adapt(input_test)))))
145
176
 
146
 
    def test_scenarios_include_transport_class(self):
 
177
    def test_adapter_sets_transport_class(self):
 
178
        # Check that the test adapter inserts a transport and server into the
 
179
        # generated test.
 
180
        #
147
181
        # This test used to know about all the possible transports and the
148
182
        # order they were returned but that seems overly brittle (mbp
149
183
        # 20060307)
150
 
        from bzrlib.tests.per_transport import transport_test_permutations
151
 
        scenarios = transport_test_permutations()
 
184
        from bzrlib.tests.test_transport_implementations \
 
185
            import TransportTestProviderAdapter
 
186
        scenarios = TransportTestProviderAdapter().scenarios
152
187
        # there are at least that many builtin transports
153
188
        self.assertTrue(len(scenarios) > 6)
154
189
        one_scenario = scenarios[0]
159
194
                                   bzrlib.transport.Server))
160
195
 
161
196
 
162
 
class TestBranchScenarios(tests.TestCase):
 
197
class TestBranchProviderAdapter(TestCase):
 
198
    """A group of tests that test the branch implementation test adapter."""
163
199
 
164
 
    def test_scenarios(self):
 
200
    def test_constructor(self):
165
201
        # check that constructor parameters are passed through to the adapted
166
202
        # test.
167
 
        from bzrlib.tests.per_branch import make_scenarios
 
203
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
168
204
        server1 = "a"
169
205
        server2 = "b"
170
206
        formats = [("c", "C"), ("d", "D")]
171
 
        scenarios = make_scenarios(server1, server2, formats)
172
 
        self.assertEqual(2, len(scenarios))
 
207
        adapter = BranchTestProviderAdapter(server1, server2, formats)
 
208
        self.assertEqual(2, len(adapter.scenarios))
173
209
        self.assertEqual([
174
210
            ('str',
175
211
             {'branch_format': 'c',
181
217
              'bzrdir_format': 'D',
182
218
              'transport_readonly_server': 'b',
183
219
              'transport_server': 'a'})],
184
 
            scenarios)
185
 
 
186
 
 
187
 
class TestBzrDirScenarios(tests.TestCase):
188
 
 
189
 
    def test_scenarios(self):
 
220
            adapter.scenarios)
 
221
 
 
222
 
 
223
class TestBzrDirProviderAdapter(TestCase):
 
224
    """A group of tests that test the bzr dir implementation test adapter."""
 
225
 
 
226
    def test_adapted_tests(self):
190
227
        # check that constructor parameters are passed through to the adapted
191
228
        # test.
192
 
        from bzrlib.tests.per_bzrdir import make_scenarios
 
229
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
193
230
        vfs_factory = "v"
194
231
        server1 = "a"
195
232
        server2 = "b"
196
233
        formats = ["c", "d"]
197
 
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
 
234
        adapter = BzrDirTestProviderAdapter(vfs_factory,
 
235
            server1, server2, formats)
198
236
        self.assertEqual([
199
237
            ('str',
200
238
             {'bzrdir_format': 'c',
206
244
              'transport_readonly_server': 'b',
207
245
              'transport_server': 'a',
208
246
              'vfs_transport_factory': 'v'})],
209
 
            scenarios)
210
 
 
211
 
 
212
 
class TestRepositoryScenarios(tests.TestCase):
 
247
            adapter.scenarios)
 
248
 
 
249
 
 
250
class TestRepositoryParameterisation(TestCase):
 
251
    """A group of tests that test the repository implementation test adapter."""
213
252
 
214
253
    def test_formats_to_scenarios(self):
215
 
        from bzrlib.tests.per_repository import formats_to_scenarios
 
254
        """The adapter can generate all the scenarios needed."""
 
255
        from bzrlib.tests.repository_implementations import formats_to_scenarios
216
256
        formats = [("(c)", remote.RemoteRepositoryFormat()),
217
257
                   ("(d)", repository.format_registry.get(
218
258
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
249
289
            vfs_scenarios)
250
290
 
251
291
 
252
 
class TestTestScenarioApplication(tests.TestCase):
 
292
class TestTestScenarioApplier(TestCase):
253
293
    """Tests for the test adaption facilities."""
254
294
 
255
 
    def test_apply_scenario(self):
256
 
        from bzrlib.tests import apply_scenario
257
 
        input_test = TestTestScenarioApplication("test_apply_scenario")
 
295
    def test_adapt_applies_scenarios(self):
 
296
        from bzrlib.tests.repository_implementations import TestScenarioApplier
 
297
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
298
        adapter = TestScenarioApplier()
 
299
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
 
300
        calls = []
 
301
        def capture_call(test, scenario):
 
302
            calls.append((test, scenario))
 
303
            return test
 
304
        adapter.adapt_test_to_scenario = capture_call
 
305
        adapter.adapt(input_test)
 
306
        self.assertEqual([(input_test, ("1", "dict")),
 
307
            (input_test, ("2", "settings"))], calls)
 
308
 
 
309
    def test_adapt_test_to_scenario(self):
 
310
        from bzrlib.tests.repository_implementations import TestScenarioApplier
 
311
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
312
        adapter = TestScenarioApplier()
258
313
        # setup two adapted tests
259
 
        adapted_test1 = apply_scenario(input_test,
 
314
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
260
315
            ("new id",
261
316
            {"bzrdir_format":"bzr_format",
262
317
             "repository_format":"repo_fmt",
263
318
             "transport_server":"transport_server",
264
319
             "transport_readonly_server":"readonly-server"}))
265
 
        adapted_test2 = apply_scenario(input_test,
 
320
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
266
321
            ("new id 2", {"bzrdir_format":None}))
267
322
        # input_test should have been altered.
268
323
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
269
 
        # the new tests are mutually incompatible, ensuring it has
 
324
        # the new tests are mutually incompatible, ensuring it has 
270
325
        # made new ones, and unspecified elements in the scenario
271
326
        # should not have been altered.
272
327
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
275
330
        self.assertEqual("readonly-server",
276
331
            adapted_test1.transport_readonly_server)
277
332
        self.assertEqual(
278
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
279
 
            "test_apply_scenario(new id)",
 
333
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
334
            "test_adapt_test_to_scenario(new id)",
280
335
            adapted_test1.id())
281
336
        self.assertEqual(None, adapted_test2.bzrdir_format)
282
337
        self.assertEqual(
283
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
284
 
            "test_apply_scenario(new id 2)",
 
338
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
339
            "test_adapt_test_to_scenario(new id 2)",
285
340
            adapted_test2.id())
286
341
 
287
342
 
288
 
class TestInterRepositoryScenarios(tests.TestCase):
 
343
class TestInterRepositoryProviderAdapter(TestCase):
 
344
    """A group of tests that test the InterRepository test adapter."""
289
345
 
290
 
    def test_scenarios(self):
 
346
    def test_adapted_tests(self):
291
347
        # check that constructor parameters are passed through to the adapted
292
348
        # test.
293
 
        from bzrlib.tests.per_interrepository import make_scenarios
 
349
        from bzrlib.tests.interrepository_implementations import \
 
350
            InterRepositoryTestProviderAdapter
294
351
        server1 = "a"
295
352
        server2 = "b"
296
353
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
297
 
        scenarios = make_scenarios(server1, server2, formats)
 
354
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
298
355
        self.assertEqual([
299
356
            ('str,str,str',
300
357
             {'interrepo_class': str,
308
365
              'repository_format_to': 'D2',
309
366
              'transport_readonly_server': 'b',
310
367
              'transport_server': 'a'})],
311
 
            scenarios)
312
 
 
313
 
 
314
 
class TestWorkingTreeScenarios(tests.TestCase):
 
368
            adapter.formats_to_scenarios(formats))
 
369
 
 
370
 
 
371
class TestWorkingTreeProviderAdapter(TestCase):
 
372
    """A group of tests that test the workingtree implementation test adapter."""
315
373
 
316
374
    def test_scenarios(self):
317
375
        # check that constructor parameters are passed through to the adapted
318
376
        # test.
319
 
        from bzrlib.tests.per_workingtree import make_scenarios
 
377
        from bzrlib.tests.workingtree_implementations \
 
378
            import WorkingTreeTestProviderAdapter
320
379
        server1 = "a"
321
380
        server2 = "b"
322
381
        formats = [workingtree.WorkingTreeFormat2(),
323
382
                   workingtree.WorkingTreeFormat3(),]
324
 
        scenarios = make_scenarios(server1, server2, formats)
 
383
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
325
384
        self.assertEqual([
326
385
            ('WorkingTreeFormat2',
327
386
             {'bzrdir_format': formats[0]._matchingbzrdir,
333
392
              'transport_readonly_server': 'b',
334
393
              'transport_server': 'a',
335
394
              '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,
 
395
            adapter.scenarios)
 
396
 
 
397
 
 
398
class TestTreeProviderAdapter(TestCase):
 
399
    """Test the setup of tree_implementation tests."""
 
400
 
 
401
    def test_adapted_tests(self):
 
402
        # the tree implementation adapter is meant to setup one instance for
 
403
        # each working tree format, and one additional instance that will
 
404
        # use the default wt format, but create a revision tree for the tests.
 
405
        # this means that the wt ones should have the workingtree_to_test_tree
 
406
        # attribute set to 'return_parameter' and the revision one set to
 
407
        # revision_tree_from_workingtree.
 
408
 
 
409
        from bzrlib.tests.tree_implementations import (
 
410
            TreeTestProviderAdapter,
354
411
            return_parameter,
355
412
            revision_tree_from_workingtree
356
413
            )
 
414
        input_test = TestTreeProviderAdapter(
 
415
            "test_adapted_tests")
357
416
        server1 = "a"
358
417
        server2 = "b"
359
418
        formats = [workingtree.WorkingTreeFormat2(),
360
419
                   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):
 
420
        adapter = TreeTestProviderAdapter(server1, server2, formats)
 
421
        suite = adapter.adapt(input_test)
 
422
        tests = list(iter(suite))
 
423
        # XXX We should not have tests fail as we add more scenarios
 
424
        # abentley 20080412
 
425
        self.assertEqual(5, len(tests))
 
426
        # this must match the default format setp up in
 
427
        # TreeTestProviderAdapter.adapt
 
428
        default_format = workingtree.WorkingTreeFormat3
 
429
        self.assertEqual(tests[0].workingtree_format, formats[0])
 
430
        self.assertEqual(tests[0].bzrdir_format, formats[0]._matchingbzrdir)
 
431
        self.assertEqual(tests[0].transport_server, server1)
 
432
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
433
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
 
434
        self.assertEqual(tests[1].workingtree_format, formats[1])
 
435
        self.assertEqual(tests[1].bzrdir_format, formats[1]._matchingbzrdir)
 
436
        self.assertEqual(tests[1].transport_server, server1)
 
437
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
438
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
 
439
        self.assertIsInstance(tests[2].workingtree_format, default_format)
 
440
        #self.assertEqual(tests[2].bzrdir_format,
 
441
        #                 default_format._matchingbzrdir)
 
442
        self.assertEqual(tests[2].transport_server, server1)
 
443
        self.assertEqual(tests[2].transport_readonly_server, server2)
 
444
        self.assertEqual(tests[2]._workingtree_to_test_tree,
 
445
            revision_tree_from_workingtree)
 
446
 
 
447
 
 
448
class TestInterTreeProviderAdapter(TestCase):
419
449
    """A group of tests that test the InterTreeTestAdapter."""
420
450
 
421
 
    def test_scenarios(self):
 
451
    def test_adapted_tests(self):
422
452
        # check that constructor parameters are passed through to the adapted
423
453
        # test.
424
454
        # for InterTree tests we want the machinery to bring up two trees in
428
458
        # unlike the TestProviderAdapter we dont want to automatically add a
429
459
        # parameterized one for WorkingTree - the optimisers will tell us what
430
460
        # ones to add.
431
 
        from bzrlib.tests.per_tree import (
 
461
        from bzrlib.tests.tree_implementations import (
432
462
            return_parameter,
433
463
            revision_tree_from_workingtree
434
464
            )
435
 
        from bzrlib.tests.per_intertree import (
436
 
            make_scenarios,
 
465
        from bzrlib.tests.intertree_implementations import (
 
466
            InterTreeTestProviderAdapter,
437
467
            )
438
468
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
439
 
        input_test = TestInterTreeScenarios(
440
 
            "test_scenarios")
 
469
        input_test = TestInterTreeProviderAdapter(
 
470
            "test_adapted_tests")
441
471
        server1 = "a"
442
472
        server2 = "b"
443
473
        format1 = WorkingTreeFormat2()
444
474
        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):
 
475
        formats = [(str, format1, format2, "converter1"),
 
476
            (int, format2, format1, "converter2")]
 
477
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
 
478
        suite = adapter.adapt(input_test)
 
479
        tests = list(iter(suite))
 
480
        self.assertEqual(2, len(tests))
 
481
        self.assertEqual(tests[0].intertree_class, formats[0][0])
 
482
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
 
483
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
 
484
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
 
485
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
 
486
        self.assertEqual(tests[0].transport_server, server1)
 
487
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
488
        self.assertEqual(tests[1].intertree_class, formats[1][0])
 
489
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
 
490
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
 
491
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
 
492
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
 
493
        self.assertEqual(tests[1].transport_server, server1)
 
494
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
495
 
 
496
 
 
497
class TestTestCaseInTempDir(TestCaseInTempDir):
475
498
 
476
499
    def test_home_is_not_working(self):
477
500
        self.assertNotEqual(self.test_dir, self.test_home_dir)
479
502
        self.assertIsSameRealPath(self.test_dir, cwd)
480
503
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
481
504
 
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):
 
505
 
 
506
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
497
507
 
498
508
    def test_home_is_non_existant_dir_under_root(self):
499
509
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
500
510
 
501
511
        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
 
512
        need any disk resources: they should be hooked into bzrlib in such a 
 
513
        way that no global settings are being changed by the test (only a 
504
514
        few tests should need to do that), and having a missing dir as home is
505
515
        an effective way to ensure that this is the case.
506
516
        """
508
518
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
509
519
            self.test_home_dir)
510
520
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
511
 
 
 
521
        
512
522
    def test_cwd_is_TEST_ROOT(self):
513
523
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
514
524
        cwd = osutils.getcwd()
588
598
        # But we have a safety net in place.
589
599
        self.assertRaises(AssertionError, self._check_safety_net)
590
600
 
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):
 
601
 
 
602
class TestTestCaseWithTransport(TestCaseWithTransport):
604
603
    """Tests for the convenience functions TestCaseWithTransport introduces."""
605
604
 
606
605
    def test_get_readonly_url_none(self):
657
656
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
658
657
 
659
658
 
660
 
class TestTestCaseTransports(tests.TestCaseWithTransport):
 
659
class TestTestCaseTransports(TestCaseWithTransport):
661
660
 
662
661
    def setUp(self):
663
662
        super(TestTestCaseTransports, self).setUp()
666
665
    def test_make_bzrdir_preserves_transport(self):
667
666
        t = self.get_transport()
668
667
        result_bzrdir = self.make_bzrdir('subdir')
669
 
        self.assertIsInstance(result_bzrdir.transport,
 
668
        self.assertIsInstance(result_bzrdir.transport, 
670
669
                              MemoryTransport)
671
670
        # should not be on disk, should only be in memory
672
671
        self.failIfExists('subdir')
673
672
 
674
673
 
675
 
class TestChrootedTest(tests.ChrootedTestCase):
 
674
class TestChrootedTest(ChrootedTestCase):
676
675
 
677
676
    def test_root_is_root(self):
678
677
        from bzrlib.transport import get_transport
681
680
        self.assertEqual(url, t.clone('..').base)
682
681
 
683
682
 
684
 
class MockProgress(progress._BaseProgressBar):
 
683
class MockProgress(_BaseProgressBar):
685
684
    """Progress-bar standin that records calls.
686
685
 
687
686
    Useful for testing pb using code.
688
687
    """
689
688
 
690
689
    def __init__(self):
691
 
        progress._BaseProgressBar.__init__(self)
 
690
        _BaseProgressBar.__init__(self)
692
691
        self.calls = []
693
692
 
694
693
    def tick(self):
704
703
        self.calls.append(('note', msg, args))
705
704
 
706
705
 
707
 
class TestTestResult(tests.TestCase):
 
706
class TestTestResult(TestCase):
708
707
 
709
708
    def check_timing(self, test_case, expected_re):
710
709
        result = bzrlib.tests.TextTestResult(self._log_file,
716
715
        self.assertContainsRe(timed_string, expected_re)
717
716
 
718
717
    def test_test_reporting(self):
719
 
        class ShortDelayTestCase(tests.TestCase):
 
718
        class ShortDelayTestCase(TestCase):
720
719
            def test_short_delay(self):
721
720
                time.sleep(0.003)
722
721
            def test_short_benchmark(self):
723
722
                self.time(time.sleep, 0.003)
724
723
        self.check_timing(ShortDelayTestCase('test_short_delay'),
725
724
                          r"^ +[0-9]+ms$")
726
 
        # if a benchmark time is given, we now show just that time followed by
727
 
        # a star
 
725
        # if a benchmark time is given, we want a x of y style result.
728
726
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
729
 
                          r"^ +[0-9]+ms\*$")
 
727
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
730
728
 
731
729
    def test_unittest_reporting_unittest_class(self):
732
730
        # getting the time from a non-bzrlib test works ok
735
733
                time.sleep(0.003)
736
734
        self.check_timing(ShortDelayTestCase('test_short_delay'),
737
735
                          r"^ +[0-9]+ms$")
738
 
 
 
736
        
739
737
    def test_assigned_benchmark_file_stores_date(self):
740
738
        output = StringIO()
741
739
        result = bzrlib.tests.TextTestResult(self._log_file,
768
766
        self.assertContainsRe(lines[1],
769
767
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
770
768
            "._time_hello_world_encoding")
771
 
 
 
769
 
772
770
    def _time_hello_world_encoding(self):
773
771
        """Profile two sleep calls
774
 
 
 
772
        
775
773
        This is used to exercise the test framework.
776
774
        """
777
775
        self.time(unicode, 'hello', errors='replace')
795
793
        # execute the test, which should succeed and record profiles
796
794
        example_test_case.run(result)
797
795
        # lsprofile_something()
798
 
        # if this worked we want
 
796
        # if this worked we want 
799
797
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
800
798
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
801
799
        # (the lsprof header)
802
800
        # ... an arbitrary number of lines
803
801
        # and the function call which is time.sleep.
804
 
        #           1        0            ???         ???       ???(sleep)
 
802
        #           1        0            ???         ???       ???(sleep) 
805
803
        # and then repeated but with 'world', rather than 'hello'.
806
804
        # this should appear in the output stream of our test result.
807
805
        output = result_stream.getvalue()
816
814
 
817
815
    def test_known_failure(self):
818
816
        """A KnownFailure being raised should trigger several result actions."""
819
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
820
 
            def done(self): pass
821
 
            def startTests(self): pass
 
817
        class InstrumentedTestResult(ExtendedTestResult):
 
818
 
822
819
            def report_test_start(self, test): pass
823
820
            def report_known_failure(self, test, err):
824
821
                self._call = test, err
825
822
        result = InstrumentedTestResult(None, None, None, None)
826
823
        def test_function():
827
 
            raise tests.KnownFailure('failed!')
 
824
            raise KnownFailure('failed!')
828
825
        test = unittest.FunctionTestCase(test_function)
829
826
        test.run(result)
830
827
        # it should invoke 'report_known_failure'.
831
828
        self.assertEqual(2, len(result._call))
832
829
        self.assertEqual(test, result._call[0])
833
 
        self.assertEqual(tests.KnownFailure, result._call[1][0])
834
 
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
830
        self.assertEqual(KnownFailure, result._call[1][0])
 
831
        self.assertIsInstance(result._call[1][1], KnownFailure)
835
832
        # we dont introspec the traceback, if the rest is ok, it would be
836
833
        # exceptional for it not to be.
837
834
        # it should update the known_failure_count on the object.
854
851
        # (class, exception object, traceback)
855
852
        # KnownFailures dont get their tracebacks shown though, so we
856
853
        # can skip that.
857
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
854
        err = (KnownFailure, KnownFailure('foo'), None)
858
855
        result.report_known_failure(test, err)
859
856
        output = result_stream.getvalue()[prefix:]
860
857
        lines = output.splitlines()
866
863
        # text test output formatting
867
864
        pb = MockProgress()
868
865
        result = bzrlib.tests.TextTestResult(
869
 
            StringIO(),
 
866
            None,
870
867
            descriptions=0,
871
868
            verbosity=1,
872
869
            pb=pb,
878
875
        # (class, exception object, traceback)
879
876
        # KnownFailures dont get their tracebacks shown though, so we
880
877
        # can skip that.
881
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
878
        err = (KnownFailure, KnownFailure('foo'), None)
882
879
        result.report_known_failure(test, err)
883
880
        self.assertEqual(
884
881
            [
905
902
 
906
903
    def test_add_not_supported(self):
907
904
        """Test the behaviour of invoking addNotSupported."""
908
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
909
 
            def done(self): pass
910
 
            def startTests(self): pass
 
905
        class InstrumentedTestResult(ExtendedTestResult):
911
906
            def report_test_start(self, test): pass
912
907
            def report_unsupported(self, test, feature):
913
908
                self._call = test, feature
914
909
        result = InstrumentedTestResult(None, None, None, None)
915
910
        test = SampleTestCase('_test_pass')
916
 
        feature = tests.Feature()
 
911
        feature = Feature()
917
912
        result.startTest(test)
918
913
        result.addNotSupported(test, feature)
919
914
        # it should invoke 'report_unsupported'.
938
933
            verbosity=2,
939
934
            )
940
935
        test = self.get_passing_test()
941
 
        feature = tests.Feature()
 
936
        feature = Feature()
942
937
        result.startTest(test)
943
938
        prefix = len(result_stream.getvalue())
944
939
        result.report_unsupported(test, feature)
945
940
        output = result_stream.getvalue()[prefix:]
946
941
        lines = output.splitlines()
947
 
        self.assertEqual(lines, ['NODEP        0ms',
948
 
                                 "    The feature 'Feature' is not available."])
949
 
 
 
942
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
 
943
    
950
944
    def test_text_report_unsupported(self):
951
945
        # text test output formatting
952
946
        pb = MockProgress()
953
947
        result = bzrlib.tests.TextTestResult(
954
 
            StringIO(),
 
948
            None,
955
949
            descriptions=0,
956
950
            verbosity=1,
957
951
            pb=pb,
958
952
            )
959
953
        test = self.get_passing_test()
960
 
        feature = tests.Feature()
 
954
        feature = Feature()
961
955
        # this seeds the state to handle reporting the test.
962
956
        result.startTest(test)
963
957
        result.report_unsupported(test, feature)
975
969
            ('update', '[2 in 0s, 2 missing] 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'.
1005
998
        result.addNotSupported(test, feature)
1006
999
        self.assertFalse(result.wasStrictlySuccessful())
1007
1000
        self.assertEqual(None, result._extractBenchmarkTime(test))
1008
 
 
 
1001
 
1009
1002
    def test_strict_with_known_failure(self):
1010
1003
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1011
1004
                                             verbosity=1)
1012
1005
        test = self.get_passing_test()
1013
 
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
1006
        err = (KnownFailure, KnownFailure('foo'), None)
1014
1007
        result._addKnownFailure(test, err)
1015
1008
        self.assertFalse(result.wasStrictlySuccessful())
1016
1009
        self.assertEqual(None, result._extractBenchmarkTime(test))
1023
1016
        self.assertTrue(result.wasStrictlySuccessful())
1024
1017
        self.assertEqual(None, result._extractBenchmarkTime(test))
1025
1018
 
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):
 
1019
 
 
1020
class TestUnicodeFilenameFeature(TestCase):
1041
1021
 
1042
1022
    def test_probe_passes(self):
1043
1023
        """UnicodeFilenameFeature._probe passes."""
1046
1026
        tests.UnicodeFilenameFeature._probe()
1047
1027
 
1048
1028
 
1049
 
class TestRunner(tests.TestCase):
 
1029
class TestRunner(TestCase):
1050
1030
 
1051
1031
    def dummy_test(self):
1052
1032
        pass
1056
1036
 
1057
1037
        This current saves and restores:
1058
1038
        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.
 
1039
        
 
1040
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
 
1041
        without using this convenience method, because of our use of global state.
1063
1042
        """
1064
 
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1043
        old_root = TestCaseInTempDir.TEST_ROOT
1065
1044
        try:
1066
 
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1045
            TestCaseInTempDir.TEST_ROOT = None
1067
1046
            return testrunner.run(test)
1068
1047
        finally:
1069
 
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1048
            TestCaseInTempDir.TEST_ROOT = old_root
1070
1049
 
1071
1050
    def test_known_failure_failed_run(self):
1072
1051
        # run a test that generates a known failure which should be printed in
1073
1052
        # the final output when real failures occur.
1074
1053
        def known_failure_test():
1075
 
            raise tests.KnownFailure('failed')
 
1054
            raise KnownFailure('failed')
1076
1055
        test = unittest.TestSuite()
1077
1056
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1078
1057
        def failing_test():
1079
1058
            raise AssertionError('foo')
1080
1059
        test.addTest(unittest.FunctionTestCase(failing_test))
1081
1060
        stream = StringIO()
1082
 
        runner = tests.TextTestRunner(stream=stream)
 
1061
        runner = TextTestRunner(stream=stream)
1083
1062
        result = self.run_test_runner(runner, test)
1084
1063
        lines = stream.getvalue().splitlines()
1085
1064
        self.assertEqual([
1094
1073
            '----------------------------------------------------------------------',
1095
1074
            '',
1096
1075
            'FAILED (failures=1, known_failure_count=1)'],
1097
 
            lines[3:8] + lines[9:13] + lines[14:])
 
1076
            lines[0:5] + lines[6:10] + lines[11:])
1098
1077
 
1099
1078
    def test_known_failure_ok_run(self):
1100
1079
        # run a test that generates a known failure which should be printed in the final output.
1101
1080
        def known_failure_test():
1102
 
            raise tests.KnownFailure('failed')
 
1081
            raise KnownFailure('failed')
1103
1082
        test = unittest.FunctionTestCase(known_failure_test)
1104
1083
        stream = StringIO()
1105
 
        runner = tests.TextTestRunner(stream=stream)
 
1084
        runner = TextTestRunner(stream=stream)
1106
1085
        result = self.run_test_runner(runner, test)
1107
1086
        self.assertContainsRe(stream.getvalue(),
1108
1087
            '\n'
1115
1094
        # run a test that is skipped, and check the suite as a whole still
1116
1095
        # succeeds.
1117
1096
        # 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")
 
1097
        def skipping_test():
 
1098
            raise TestSkipped('test intentionally skipped')
 
1099
 
 
1100
        runner = TextTestRunner(stream=self._log_file)
 
1101
        test = unittest.FunctionTestCase(skipping_test)
1123
1102
        result = self.run_test_runner(runner, test)
1124
1103
        self.assertTrue(result.wasSuccessful())
1125
1104
 
1126
1105
    def test_skipped_from_setup(self):
1127
1106
        calls = []
1128
 
        class SkippedSetupTest(tests.TestCase):
 
1107
        class SkippedSetupTest(TestCase):
1129
1108
 
1130
1109
            def setUp(self):
1131
1110
                calls.append('setUp')
1132
1111
                self.addCleanup(self.cleanup)
1133
 
                raise tests.TestSkipped('skipped setup')
 
1112
                raise TestSkipped('skipped setup')
1134
1113
 
1135
1114
            def test_skip(self):
1136
1115
                self.fail('test reached')
1138
1117
            def cleanup(self):
1139
1118
                calls.append('cleanup')
1140
1119
 
1141
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1120
        runner = TextTestRunner(stream=self._log_file)
1142
1121
        test = SkippedSetupTest('test_skip')
1143
1122
        result = self.run_test_runner(runner, test)
1144
1123
        self.assertTrue(result.wasSuccessful())
1147
1126
 
1148
1127
    def test_skipped_from_test(self):
1149
1128
        calls = []
1150
 
        class SkippedTest(tests.TestCase):
 
1129
        class SkippedTest(TestCase):
1151
1130
 
1152
1131
            def setUp(self):
1153
 
                tests.TestCase.setUp(self)
1154
1132
                calls.append('setUp')
1155
1133
                self.addCleanup(self.cleanup)
1156
1134
 
1157
1135
            def test_skip(self):
1158
 
                raise tests.TestSkipped('skipped test')
 
1136
                raise TestSkipped('skipped test')
1159
1137
 
1160
1138
            def cleanup(self):
1161
1139
                calls.append('cleanup')
1162
1140
 
1163
 
        runner = tests.TextTestRunner(stream=self._log_file)
 
1141
        runner = TextTestRunner(stream=self._log_file)
1164
1142
        test = SkippedTest('test_skip')
1165
1143
        result = self.run_test_runner(runner, test)
1166
1144
        self.assertTrue(result.wasSuccessful())
1170
1148
    def test_not_applicable(self):
1171
1149
        # run a test that is skipped because it's not applicable
1172
1150
        def not_applicable_test():
1173
 
            raise tests.TestNotApplicable('this test never runs')
 
1151
            from bzrlib.tests import TestNotApplicable
 
1152
            raise TestNotApplicable('this test never runs')
1174
1153
        out = StringIO()
1175
 
        runner = tests.TextTestRunner(stream=out, verbosity=2)
 
1154
        runner = TextTestRunner(stream=out, verbosity=2)
1176
1155
        test = unittest.FunctionTestCase(not_applicable_test)
1177
1156
        result = self.run_test_runner(runner, test)
1178
1157
        self._log_file.write(out.getvalue())
1185
1164
 
1186
1165
    def test_not_applicable_demo(self):
1187
1166
        # just so you can see it in the test output
1188
 
        raise tests.TestNotApplicable('this test is just a demonstation')
 
1167
        raise TestNotApplicable('this test is just a demonstation')
1189
1168
 
1190
1169
    def test_unsupported_features_listed(self):
1191
1170
        """When unsupported features are encountered they are detailed."""
1192
 
        class Feature1(tests.Feature):
 
1171
        class Feature1(Feature):
1193
1172
            def _probe(self): return False
1194
 
        class Feature2(tests.Feature):
 
1173
        class Feature2(Feature):
1195
1174
            def _probe(self): return False
1196
1175
        # create sample tests
1197
1176
        test1 = SampleTestCase('_test_pass')
1202
1181
        test.addTest(test1)
1203
1182
        test.addTest(test2)
1204
1183
        stream = StringIO()
1205
 
        runner = tests.TextTestRunner(stream=stream)
 
1184
        runner = TextTestRunner(stream=stream)
1206
1185
        result = self.run_test_runner(runner, test)
1207
1186
        lines = stream.getvalue().splitlines()
1208
1187
        self.assertEqual([
1219
1198
        workingtree = _get_bzr_source_tree()
1220
1199
        test = TestRunner('dummy_test')
1221
1200
        output = StringIO()
1222
 
        runner = tests.TextTestRunner(stream=self._log_file,
1223
 
                                      bench_history=output)
 
1201
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
1224
1202
        result = self.run_test_runner(runner, test)
1225
1203
        output_string = output.getvalue()
1226
1204
        self.assertContainsRe(output_string, "--date [0-9.]+")
1237
1215
    def test_success_log_deleted(self):
1238
1216
        """Successful tests have their log deleted"""
1239
1217
 
1240
 
        class LogTester(tests.TestCase):
 
1218
        class LogTester(TestCase):
1241
1219
 
1242
1220
            def test_success(self):
1243
1221
                self.log('this will be removed\n')
1244
1222
 
1245
 
        sio = StringIO()
1246
 
        runner = tests.TextTestRunner(stream=sio)
 
1223
        sio = cStringIO.StringIO()
 
1224
        runner = TextTestRunner(stream=sio)
1247
1225
        test = LogTester('test_success')
1248
1226
        result = self.run_test_runner(runner, test)
1249
1227
 
1252
1230
    def test_skipped_log_deleted(self):
1253
1231
        """Skipped tests have their log deleted"""
1254
1232
 
1255
 
        class LogTester(tests.TestCase):
 
1233
        class LogTester(TestCase):
1256
1234
 
1257
1235
            def test_skipped(self):
1258
1236
                self.log('this will be removed\n')
1259
1237
                raise tests.TestSkipped()
1260
1238
 
1261
 
        sio = StringIO()
1262
 
        runner = tests.TextTestRunner(stream=sio)
 
1239
        sio = cStringIO.StringIO()
 
1240
        runner = TextTestRunner(stream=sio)
1263
1241
        test = LogTester('test_skipped')
1264
1242
        result = self.run_test_runner(runner, test)
1265
1243
 
1268
1246
    def test_not_aplicable_log_deleted(self):
1269
1247
        """Not applicable tests have their log deleted"""
1270
1248
 
1271
 
        class LogTester(tests.TestCase):
 
1249
        class LogTester(TestCase):
1272
1250
 
1273
1251
            def test_not_applicable(self):
1274
1252
                self.log('this will be removed\n')
1275
1253
                raise tests.TestNotApplicable()
1276
1254
 
1277
 
        sio = StringIO()
1278
 
        runner = tests.TextTestRunner(stream=sio)
 
1255
        sio = cStringIO.StringIO()
 
1256
        runner = TextTestRunner(stream=sio)
1279
1257
        test = LogTester('test_not_applicable')
1280
1258
        result = self.run_test_runner(runner, test)
1281
1259
 
1284
1262
    def test_known_failure_log_deleted(self):
1285
1263
        """Know failure tests have their log deleted"""
1286
1264
 
1287
 
        class LogTester(tests.TestCase):
 
1265
        class LogTester(TestCase):
1288
1266
 
1289
1267
            def test_known_failure(self):
1290
1268
                self.log('this will be removed\n')
1291
1269
                raise tests.KnownFailure()
1292
1270
 
1293
 
        sio = StringIO()
1294
 
        runner = tests.TextTestRunner(stream=sio)
 
1271
        sio = cStringIO.StringIO()
 
1272
        runner = TextTestRunner(stream=sio)
1295
1273
        test = LogTester('test_known_failure')
1296
1274
        result = self.run_test_runner(runner, test)
1297
1275
 
1300
1278
    def test_fail_log_kept(self):
1301
1279
        """Failed tests have their log kept"""
1302
1280
 
1303
 
        class LogTester(tests.TestCase):
 
1281
        class LogTester(TestCase):
1304
1282
 
1305
1283
            def test_fail(self):
1306
1284
                self.log('this will be kept\n')
1307
1285
                self.fail('this test fails')
1308
1286
 
1309
 
        sio = StringIO()
1310
 
        runner = tests.TextTestRunner(stream=sio)
 
1287
        sio = cStringIO.StringIO()
 
1288
        runner = TextTestRunner(stream=sio)
1311
1289
        test = LogTester('test_fail')
1312
1290
        result = self.run_test_runner(runner, test)
1313
1291
 
1322
1300
    def test_error_log_kept(self):
1323
1301
        """Tests with errors have their log kept"""
1324
1302
 
1325
 
        class LogTester(tests.TestCase):
 
1303
        class LogTester(TestCase):
1326
1304
 
1327
1305
            def test_error(self):
1328
1306
                self.log('this will be kept\n')
1329
1307
                raise ValueError('random exception raised')
1330
1308
 
1331
 
        sio = StringIO()
1332
 
        runner = tests.TextTestRunner(stream=sio)
 
1309
        sio = cStringIO.StringIO()
 
1310
        runner = TextTestRunner(stream=sio)
1333
1311
        test = LogTester('test_error')
1334
1312
        result = self.run_test_runner(runner, test)
1335
1313
 
1342
1320
        self.assertEqual(log, test._log_contents)
1343
1321
 
1344
1322
 
1345
 
class SampleTestCase(tests.TestCase):
 
1323
class SampleTestCase(TestCase):
1346
1324
 
1347
1325
    def _test_pass(self):
1348
1326
        pass
1350
1328
class _TestException(Exception):
1351
1329
    pass
1352
1330
 
1353
 
class TestTestCase(tests.TestCase):
 
1331
class TestTestCase(TestCase):
1354
1332
    """Tests that test the core bzrlib TestCase."""
1355
1333
 
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
1334
    def test_debug_flags_sanitised(self):
1400
1335
        """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
1336
        # we could set something and run a test that will check
1405
1337
        # it gets santised, but this is probably sufficient for now:
1406
1338
        # if someone runs the test with -Dsomething it will error.
1407
1339
        self.assertEqual(set(), bzrlib.debug.debug_flags)
1408
1340
 
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
1341
    def inner_test(self):
1448
1342
        # the inner child test
1449
1343
        note("inner_test")
1452
1346
        # the outer child test
1453
1347
        note("outer_start")
1454
1348
        self.inner_test = TestTestCase("inner_child")
1455
 
        result = self.make_test_result()
 
1349
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1350
                                        descriptions=0,
 
1351
                                        verbosity=1)
1456
1352
        self.inner_test.run(result)
1457
1353
        note("outer finish")
1458
1354
 
1462
1358
        # should setup a new log, log content to it, setup a child case (B),
1463
1359
        # which should log independently, then case (A) should log a trailer
1464
1360
        # and return.
1465
 
        # we do two nested children so that we can verify the state of the
 
1361
        # we do two nested children so that we can verify the state of the 
1466
1362
        # logs after the outer child finishes is correct, which a bad clean
1467
1363
        # up routine in tearDown might trigger a fault in our test with only
1468
1364
        # one child, we should instead see the bad result inside our test with
1470
1366
        # the outer child test
1471
1367
        original_trace = bzrlib.trace._trace_file
1472
1368
        outer_test = TestTestCase("outer_child")
1473
 
        result = self.make_test_result()
 
1369
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1370
                                        descriptions=0,
 
1371
                                        verbosity=1)
1474
1372
        outer_test.run(result)
1475
1373
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1476
1374
 
1491
1389
        sample_test.run(result)
1492
1390
        self.assertContainsRe(
1493
1391
            output_stream.getvalue(),
1494
 
            r"\d+ms\*\n$")
 
1392
            r"\d+ms/ +\d+ms\n$")
1495
1393
 
1496
1394
    def test_hooks_sanitised(self):
1497
1395
        """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
1396
        self.assertEqual(bzrlib.branch.BranchHooks(),
1502
1397
            bzrlib.branch.Branch.hooks)
1503
1398
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1504
1399
            bzrlib.smart.server.SmartTCPServer.hooks)
1505
 
        self.assertEqual(bzrlib.commands.CommandHooks(),
1506
 
            bzrlib.commands.Command.hooks)
1507
1400
 
1508
1401
    def test__gather_lsprof_in_benchmarks(self):
1509
1402
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1510
 
 
 
1403
        
1511
1404
        Each self.time() call is individually and separately profiled.
1512
1405
        """
1513
1406
        self.requireFeature(test_lsprof.LSProfFeature)
1514
 
        # overrides the class member with an instance member so no cleanup
 
1407
        # overrides the class member with an instance member so no cleanup 
1515
1408
        # needed.
1516
1409
        self._gather_lsprof_in_benchmarks = True
1517
1410
        self.time(time.sleep, 0.000)
1524
1417
 
1525
1418
    def test_knownFailure(self):
1526
1419
        """Self.knownFailure() should raise a KnownFailure exception."""
1527
 
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1420
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1528
1421
 
1529
1422
    def test_requireFeature_available(self):
1530
1423
        """self.requireFeature(available) is a no-op."""
1531
 
        class Available(tests.Feature):
 
1424
        class Available(Feature):
1532
1425
            def _probe(self):return True
1533
1426
        feature = Available()
1534
1427
        self.requireFeature(feature)
1535
1428
 
1536
1429
    def test_requireFeature_unavailable(self):
1537
1430
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1538
 
        class Unavailable(tests.Feature):
 
1431
        class Unavailable(Feature):
1539
1432
            def _probe(self):return False
1540
1433
        feature = Unavailable()
1541
 
        self.assertRaises(tests.UnavailableFeature,
1542
 
                          self.requireFeature, feature)
 
1434
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1543
1435
 
1544
1436
    def test_run_no_parameters(self):
1545
1437
        test = SampleTestCase('_test_pass')
1546
1438
        test.run()
1547
 
 
 
1439
    
1548
1440
    def test_run_enabled_unittest_result(self):
1549
1441
        """Test we revert to regular behaviour when the test is enabled."""
1550
1442
        test = SampleTestCase('_test_pass')
1654
1546
            self.assertListRaises, _TestException, success_generator)
1655
1547
 
1656
1548
 
1657
 
# NB: Don't delete this; it's not actually from 0.11!
1658
 
@deprecated_function(deprecated_in((0, 11, 0)))
 
1549
@symbol_versioning.deprecated_function(zero_eleven)
1659
1550
def sample_deprecated_function():
1660
1551
    """A deprecated function to test applyDeprecated with."""
1661
1552
    return 2
1668
1559
class ApplyDeprecatedHelper(object):
1669
1560
    """A helper class for ApplyDeprecated tests."""
1670
1561
 
1671
 
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1562
    @symbol_versioning.deprecated_method(zero_eleven)
1672
1563
    def sample_deprecated_method(self, param_one):
1673
1564
        """A deprecated method for testing with."""
1674
1565
        return param_one
1676
1567
    def sample_normal_method(self):
1677
1568
        """A undeprecated method."""
1678
1569
 
1679
 
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1570
    @symbol_versioning.deprecated_method(zero_ten)
1680
1571
    def sample_nested_deprecation(self):
1681
1572
        return sample_deprecated_function()
1682
1573
 
1683
1574
 
1684
 
class TestExtraAssertions(tests.TestCase):
 
1575
class TestExtraAssertions(TestCase):
1685
1576
    """Tests for new test assertions in bzrlib test suite"""
1686
1577
 
1687
1578
    def test_assert_isinstance(self):
1688
1579
        self.assertIsInstance(2, int)
1689
1580
        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'>")
 
1581
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1693
1582
        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
1583
 
1700
1584
    def test_assertEndsWith(self):
1701
1585
        self.assertEndsWith('foo', 'oo')
1704
1588
    def test_applyDeprecated_not_deprecated(self):
1705
1589
        sample_object = ApplyDeprecatedHelper()
1706
1590
        # calling an undeprecated callable raises an assertion
1707
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1708
 
            deprecated_in((0, 11, 0)),
 
1591
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1709
1592
            sample_object.sample_normal_method)
1710
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1711
 
            deprecated_in((0, 11, 0)),
 
1593
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1712
1594
            sample_undeprecated_function, "a param value")
1713
1595
        # calling a deprecated callable (function or method) with the wrong
1714
1596
        # expected deprecation fails.
1715
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1716
 
            deprecated_in((0, 10, 0)),
 
1597
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1717
1598
            sample_object.sample_deprecated_method, "a param value")
1718
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1719
 
            deprecated_in((0, 10, 0)),
 
1599
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1720
1600
            sample_deprecated_function)
1721
1601
        # calling a deprecated callable (function or method) with the right
1722
1602
        # expected deprecation returns the functions result.
1723
 
        self.assertEqual("a param value",
1724
 
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1603
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1725
1604
            sample_object.sample_deprecated_method, "a param value"))
1726
 
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1605
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
1727
1606
            sample_deprecated_function))
1728
1607
        # calling a nested deprecation with the wrong deprecation version
1729
 
        # fails even if a deeper nested function was deprecated with the
 
1608
        # fails even if a deeper nested function was deprecated with the 
1730
1609
        # supplied version.
1731
1610
        self.assertRaises(AssertionError, self.applyDeprecated,
1732
 
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1611
            zero_eleven, sample_object.sample_nested_deprecation)
1733
1612
        # calling a nested deprecation with the right deprecation value
1734
1613
        # returns the calls result.
1735
 
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1614
        self.assertEqual(2, self.applyDeprecated(zero_ten,
1736
1615
            sample_object.sample_nested_deprecation))
1737
1616
 
1738
1617
    def test_callDeprecated(self):
1739
1618
        def testfunc(be_deprecated, result=None):
1740
1619
            if be_deprecated is True:
1741
 
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1620
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
1742
1621
                                       stacklevel=1)
1743
1622
            return result
1744
1623
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1749
1628
        self.callDeprecated([], testfunc, be_deprecated=False)
1750
1629
 
1751
1630
 
1752
 
class TestWarningTests(tests.TestCase):
 
1631
class TestWarningTests(TestCase):
1753
1632
    """Tests for calling methods that raise warnings."""
1754
1633
 
1755
1634
    def test_callCatchWarnings(self):
1765
1644
        self.assertEquals("this is your last warning", str(w0))
1766
1645
 
1767
1646
 
1768
 
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1647
class TestConvenienceMakers(TestCaseWithTransport):
1769
1648
    """Test for the make_* convenience functions."""
1770
1649
 
1771
1650
    def test_make_branch_and_tree_with_format(self):
1784
1663
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1785
1664
 
1786
1665
 
1787
 
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
 
1666
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1788
1667
 
1789
1668
    def test_make_tree_for_sftp_branch(self):
1790
1669
        """Transports backed by local directories create local trees."""
1799
1678
                tree.branch.repository.bzrdir.root_transport)
1800
1679
 
1801
1680
 
1802
 
class TestSelftest(tests.TestCase):
 
1681
class TestSelftest(TestCase):
1803
1682
    """Tests of bzrlib.tests.selftest."""
1804
1683
 
1805
1684
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1806
1685
        factory_called = []
1807
1686
        def factory():
1808
1687
            factory_called.append(True)
1809
 
            return TestUtil.TestSuite()
 
1688
            return TestSuite()
1810
1689
        out = StringIO()
1811
1690
        err = StringIO()
1812
 
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1691
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
1813
1692
            test_suite_factory=factory)
1814
1693
        self.assertEqual([True], factory_called)
1815
1694
 
1816
1695
 
1817
 
class TestKnownFailure(tests.TestCase):
 
1696
class TestKnownFailure(TestCase):
1818
1697
 
1819
1698
    def test_known_failure(self):
1820
1699
        """Check that KnownFailure is defined appropriately."""
1821
1700
        # a KnownFailure is an assertion error for compatability with unaware
1822
1701
        # runners.
1823
 
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
1702
        self.assertIsInstance(KnownFailure(""), AssertionError)
1824
1703
 
1825
1704
    def test_expect_failure(self):
1826
1705
        try:
1827
1706
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1828
 
        except tests.KnownFailure, e:
 
1707
        except KnownFailure, e:
1829
1708
            self.assertEqual('Doomed to failure', e.args[0])
1830
1709
        try:
1831
1710
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1836
1715
            self.fail('Assertion not raised')
1837
1716
 
1838
1717
 
1839
 
class TestFeature(tests.TestCase):
 
1718
class TestFeature(TestCase):
1840
1719
 
1841
1720
    def test_caching(self):
1842
1721
        """Feature._probe is called by the feature at most once."""
1843
 
        class InstrumentedFeature(tests.Feature):
 
1722
        class InstrumentedFeature(Feature):
1844
1723
            def __init__(self):
1845
 
                super(InstrumentedFeature, self).__init__()
 
1724
                Feature.__init__(self)
1846
1725
                self.calls = []
1847
1726
            def _probe(self):
1848
1727
                self.calls.append('_probe')
1855
1734
 
1856
1735
    def test_named_str(self):
1857
1736
        """Feature.__str__ should thunk to feature_name()."""
1858
 
        class NamedFeature(tests.Feature):
 
1737
        class NamedFeature(Feature):
1859
1738
            def feature_name(self):
1860
1739
                return 'symlinks'
1861
1740
        feature = NamedFeature()
1863
1742
 
1864
1743
    def test_default_str(self):
1865
1744
        """Feature.__str__ should default to __class__.__name__."""
1866
 
        class NamedFeature(tests.Feature):
 
1745
        class NamedFeature(Feature):
1867
1746
            pass
1868
1747
        feature = NamedFeature()
1869
1748
        self.assertEqual('NamedFeature', str(feature))
1870
1749
 
1871
1750
 
1872
 
class TestUnavailableFeature(tests.TestCase):
 
1751
class TestUnavailableFeature(TestCase):
1873
1752
 
1874
1753
    def test_access_feature(self):
1875
 
        feature = tests.Feature()
1876
 
        exception = tests.UnavailableFeature(feature)
 
1754
        feature = Feature()
 
1755
        exception = UnavailableFeature(feature)
1877
1756
        self.assertIs(feature, exception.args[0])
1878
1757
 
1879
1758
 
1880
 
class TestSelftestFiltering(tests.TestCase):
 
1759
class TestSelftestFiltering(TestCase):
1881
1760
 
1882
1761
    def setUp(self):
1883
 
        tests.TestCase.setUp(self)
1884
1762
        self.suite = TestUtil.TestSuite()
1885
1763
        self.loader = TestUtil.TestLoader()
1886
1764
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1890
1768
    def test_condition_id_re(self):
1891
1769
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1892
1770
            'test_condition_id_re')
1893
 
        filtered_suite = tests.filter_suite_by_condition(
1894
 
            self.suite, tests.condition_id_re('test_condition_id_re'))
 
1771
        filtered_suite = filter_suite_by_condition(self.suite,
 
1772
            condition_id_re('test_condition_id_re'))
1895
1773
        self.assertEqual([test_name], _test_ids(filtered_suite))
1896
1774
 
1897
1775
    def test_condition_id_in_list(self):
1898
1776
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1899
1777
                      'test_condition_id_in_list']
1900
1778
        id_list = tests.TestIdList(test_names)
1901
 
        filtered_suite = tests.filter_suite_by_condition(
 
1779
        filtered_suite = filter_suite_by_condition(
1902
1780
            self.suite, tests.condition_id_in_list(id_list))
1903
1781
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1904
 
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
 
1782
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
1905
1783
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1906
1784
 
1907
1785
    def test_condition_id_startswith(self):
1908
1786
        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))
 
1787
        start = klass + 'test_condition_id_starts'
 
1788
        test_names = [klass + 'test_condition_id_startswith']
 
1789
        filtered_suite = filter_suite_by_condition(
 
1790
            self.suite, tests.condition_id_startswith(start))
 
1791
        my_pattern = 'TestSelftestFiltering.*test_condition_id_startswith'
 
1792
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
 
1793
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1917
1794
 
1918
1795
    def test_condition_isinstance(self):
1919
 
        filtered_suite = tests.filter_suite_by_condition(
1920
 
            self.suite, tests.condition_isinstance(self.__class__))
 
1796
        filtered_suite = filter_suite_by_condition(self.suite,
 
1797
            condition_isinstance(self.__class__))
1921
1798
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1922
 
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
 
1799
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
1923
1800
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1924
1801
 
1925
1802
    def test_exclude_tests_by_condition(self):
1926
1803
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1927
1804
            'test_exclude_tests_by_condition')
1928
 
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
 
1805
        filtered_suite = exclude_tests_by_condition(self.suite,
1929
1806
            lambda x:x.id() == excluded_name)
1930
1807
        self.assertEqual(len(self.all_names) - 1,
1931
1808
            filtered_suite.countTestCases())
1936
1813
 
1937
1814
    def test_exclude_tests_by_re(self):
1938
1815
        self.all_names = _test_ids(self.suite)
1939
 
        filtered_suite = tests.exclude_tests_by_re(self.suite,
1940
 
                                                   'exclude_tests_by_re')
 
1816
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1941
1817
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1942
1818
            'test_exclude_tests_by_re')
1943
1819
        self.assertEqual(len(self.all_names) - 1,
1950
1826
    def test_filter_suite_by_condition(self):
1951
1827
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1952
1828
            'test_filter_suite_by_condition')
1953
 
        filtered_suite = tests.filter_suite_by_condition(self.suite,
 
1829
        filtered_suite = filter_suite_by_condition(self.suite,
1954
1830
            lambda x:x.id() == test_name)
1955
1831
        self.assertEqual([test_name], _test_ids(filtered_suite))
1956
1832
 
1957
1833
    def test_filter_suite_by_re(self):
1958
 
        filtered_suite = tests.filter_suite_by_re(self.suite,
1959
 
                                                  'test_filter_suite_by_r')
 
1834
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1960
1835
        filtered_names = _test_ids(filtered_suite)
1961
1836
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1962
1837
            'TestSelftestFiltering.test_filter_suite_by_re'])
1974
1849
 
1975
1850
    def test_filter_suite_by_id_startswith(self):
1976
1851
        # By design this test may fail if another test is added whose name also
1977
 
        # begins with one of the start value used.
 
1852
        # begins with the start value used.
1978
1853
        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])
 
1854
        start = klass + 'test_filter_suite_by_id_starts'
 
1855
        test_list = [klass + 'test_filter_suite_by_id_startswith']
 
1856
        filtered_suite = tests.filter_suite_by_id_startswith(self.suite, start)
 
1857
        filtered_names = _test_ids(filtered_suite)
1986
1858
        self.assertEqual(
1987
 
            test_list,
1988
 
            _test_ids(filtered_suite),
1989
 
            )
 
1859
            filtered_names,
 
1860
            ['bzrlib.tests.test_selftest.'
 
1861
             'TestSelftestFiltering.test_filter_suite_by_id_startswith'])
1990
1862
 
1991
1863
    def test_preserve_input(self):
1992
1864
        # 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("@#$"))
 
1865
        self.assertTrue(self.suite is preserve_input(self.suite))
 
1866
        self.assertTrue("@#$" is preserve_input("@#$"))
1995
1867
 
1996
1868
    def test_randomize_suite(self):
1997
 
        randomized_suite = tests.randomize_suite(self.suite)
 
1869
        randomized_suite = randomize_suite(self.suite)
1998
1870
        # randomizing should not add or remove test names.
1999
1871
        self.assertEqual(set(_test_ids(self.suite)),
2000
1872
                         set(_test_ids(randomized_suite)))
2010
1882
 
2011
1883
    def test_split_suit_by_condition(self):
2012
1884
        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)
 
1885
        condition = condition_id_re('test_filter_suite_by_r')
 
1886
        split_suite = split_suite_by_condition(self.suite, condition)
2015
1887
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2016
1888
            'test_filter_suite_by_re')
2017
1889
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2022
1894
 
2023
1895
    def test_split_suit_by_re(self):
2024
1896
        self.all_names = _test_ids(self.suite)
2025
 
        split_suite = tests.split_suite_by_re(self.suite,
2026
 
                                              'test_filter_suite_by_r')
 
1897
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
2027
1898
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2028
1899
            'test_filter_suite_by_re')
2029
1900
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2033
1904
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2034
1905
 
2035
1906
 
2036
 
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
1907
class TestCheckInventoryShape(TestCaseWithTransport):
2037
1908
 
2038
1909
    def test_check_inventory_shape(self):
2039
1910
        files = ['a', 'b/', 'b/c']
2047
1918
            tree.unlock()
2048
1919
 
2049
1920
 
2050
 
class TestBlackboxSupport(tests.TestCase):
 
1921
class TestBlackboxSupport(TestCase):
2051
1922
    """Tests for testsuite blackbox features."""
2052
1923
 
2053
1924
    def test_run_bzr_failure_not_caught(self):
2074
1945
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2075
1946
 
2076
1947
 
2077
 
class TestTestLoader(tests.TestCase):
 
1948
class TestTestLoader(TestCase):
2078
1949
    """Tests for the test loader."""
2079
1950
 
2080
1951
    def _get_loader_and_module(self):
2081
1952
        """Gets a TestLoader and a module with one test in it."""
2082
1953
        loader = TestUtil.TestLoader()
2083
1954
        module = {}
2084
 
        class Stub(tests.TestCase):
 
1955
        class Stub(TestCase):
2085
1956
            def test_foo(self):
2086
1957
                pass
2087
1958
        class MyModule(object):
2100
1971
        # load_tests do not need that :)
2101
1972
        def load_tests(self, standard_tests, module, loader):
2102
1973
            result = loader.suiteClass()
2103
 
            for test in tests.iter_suite_tests(standard_tests):
 
1974
            for test in iter_suite_tests(standard_tests):
2104
1975
                result.addTests([test, test])
2105
1976
            return result
2106
1977
        # add a load_tests() method which multiplies the tests from the module.
2125
1996
 
2126
1997
    def _create_suite(self, test_id_list):
2127
1998
 
2128
 
        class Stub(tests.TestCase):
 
1999
        class Stub(TestCase):
2129
2000
            def test_foo(self):
2130
2001
                pass
2131
2002
 
2141
2012
 
2142
2013
    def _test_ids(self, test_suite):
2143
2014
        """Get the ids for the tests in a test suite."""
2144
 
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
2015
        return [t.id() for t in iter_suite_tests(test_suite)]
2145
2016
 
2146
2017
    def test_empty_list(self):
2147
2018
        id_list = self._create_id_list([])
2173
2044
        self.assertTrue(id_list.refers_to('mod.class'))
2174
2045
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2175
2046
 
 
2047
    def test_test_suite(self):
 
2048
        # This test is slow, so we do a single test with one test in each
 
2049
        # category
 
2050
        test_list = [
 
2051
            # testmod_names
 
2052
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2053
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
 
2054
            # transport implementations
 
2055
            'bzrlib.tests.test_transport_implementations.TransportTests'
 
2056
            '.test_abspath(LocalURLServer)',
 
2057
            # modules_to_doctest
 
2058
            'bzrlib.timestamp.format_highres_date',
 
2059
            # plugins can't be tested that way since selftest may be run with
 
2060
            # --no-plugins
 
2061
            ]
 
2062
        suite = tests.test_suite(test_list)
 
2063
        self.assertEquals(test_list, _test_ids(suite))
 
2064
 
2176
2065
    def test_test_suite_matches_id_list_with_unknown(self):
2177
2066
        loader = TestUtil.TestLoader()
2178
2067
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2186
2075
        loader = TestUtil.TestLoader()
2187
2076
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2188
2077
        dupes = loader.suiteClass()
2189
 
        for test in tests.iter_suite_tests(suite):
 
2078
        for test in iter_suite_tests(suite):
2190
2079
            dupes.addTest(test)
2191
2080
            dupes.addTest(test) # Add it again
2192
2081
 
2198
2087
                          duplicates)
2199
2088
 
2200
2089
 
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
2090
class TestLoadTestIdList(tests.TestCaseInTempDir):
2229
2091
 
2230
2092
    def _create_test_list_file(self, file_name, content):
2308
2170
 
2309
2171
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2310
2172
        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)