~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Andrew Bennetts
  • Date: 2009-07-27 05:35:00 UTC
  • mfrom: (4570 +trunk)
  • mto: (4634.6.29 2.0)
  • mto: This revision was merged to the branch mainline in revision 4680.
  • Revision ID: andrew.bennetts@canonical.com-20090727053500-q76zsn2dx33jhmj5
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tests for the test framework."""
18
18
 
19
 
import cStringIO
 
19
from cStringIO import StringIO
20
20
import os
21
 
from StringIO import StringIO
22
21
import sys
23
22
import time
24
23
import unittest
28
27
from bzrlib import (
29
28
    branchbuilder,
30
29
    bzrdir,
 
30
    debug,
31
31
    errors,
 
32
    lockdir,
32
33
    memorytree,
33
34
    osutils,
 
35
    progress,
34
36
    remote,
35
37
    repository,
36
38
    symbol_versioning,
37
39
    tests,
38
40
    workingtree,
39
41
    )
40
 
from bzrlib.progress import _BaseProgressBar
41
42
from bzrlib.repofmt import (
42
43
    pack_repo,
43
44
    weaverepo,
44
45
    )
45
46
from bzrlib.symbol_versioning import (
46
 
    one_zero,
47
 
    zero_eleven,
48
 
    zero_ten,
 
47
    deprecated_function,
 
48
    deprecated_in,
 
49
    deprecated_method,
49
50
    )
50
51
from bzrlib.tests import (
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
 
                          run_suite,
75
 
                          split_suite_by_condition,
76
 
                          split_suite_by_re,
77
 
                          test_lsprof,
78
 
                          test_suite,
79
 
                          )
80
 
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
81
 
from bzrlib.tests.TestUtil import _load_module_by_name
 
52
    test_lsprof,
 
53
    test_sftp_transport,
 
54
    TestUtil,
 
55
    )
82
56
from bzrlib.trace import note
83
57
from bzrlib.transport.memory import MemoryServer, MemoryTransport
84
58
from bzrlib.version import _get_bzr_source_tree
86
60
 
87
61
def _test_ids(test_suite):
88
62
    """Get the ids for the tests in a test suite."""
89
 
    return [t.id() for t in iter_suite_tests(test_suite)]
90
 
 
91
 
 
92
 
class SelftestTests(TestCase):
 
63
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
64
 
 
65
 
 
66
class SelftestTests(tests.TestCase):
93
67
 
94
68
    def test_import_tests(self):
95
 
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
69
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
96
70
        self.assertEqual(mod.SelftestTests, SelftestTests)
97
71
 
98
72
    def test_import_test_failure(self):
99
73
        self.assertRaises(ImportError,
100
 
                          _load_module_by_name,
 
74
                          TestUtil._load_module_by_name,
101
75
                          'bzrlib.no-name-yet')
102
76
 
103
 
class MetaTestLog(TestCase):
 
77
class MetaTestLog(tests.TestCase):
104
78
 
105
79
    def test_logging(self):
106
80
        """Test logs are captured when a test fails."""
110
84
                              'a test message\n')
111
85
 
112
86
 
113
 
class TestUnicodeFilename(TestCase):
 
87
class TestUnicodeFilename(tests.TestCase):
114
88
 
115
89
    def test_probe_passes(self):
116
90
        """UnicodeFilename._probe passes."""
119
93
        tests.UnicodeFilename._probe()
120
94
 
121
95
 
122
 
class TestTreeShape(TestCaseInTempDir):
 
96
class TestTreeShape(tests.TestCaseInTempDir):
123
97
 
124
98
    def test_unicode_paths(self):
125
99
        self.requireFeature(tests.UnicodeFilename)
129
103
        self.failUnlessExists(filename)
130
104
 
131
105
 
132
 
class TestTransportProviderAdapter(TestCase):
 
106
class TestTransportScenarios(tests.TestCase):
133
107
    """A group of tests that test the transport implementation adaption core.
134
108
 
135
109
    This is a meta test that the tests are applied to all available
141
115
 
142
116
    def test_get_transport_permutations(self):
143
117
        # this checks that get_test_permutations defined by the module is
144
 
        # called by the adapter get_transport_test_permutations method.
 
118
        # called by the get_transport_test_permutations function.
145
119
        class MockModule(object):
146
120
            def get_test_permutations(self):
147
121
                return sample_permutation
148
122
        sample_permutation = [(1,2), (3,4)]
149
 
        from bzrlib.tests.test_transport_implementations \
150
 
            import TransportTestProviderAdapter
151
 
        adapter = TransportTestProviderAdapter()
 
123
        from bzrlib.tests.per_transport import get_transport_test_permutations
152
124
        self.assertEqual(sample_permutation,
153
 
                         adapter.get_transport_test_permutations(MockModule()))
 
125
                         get_transport_test_permutations(MockModule()))
154
126
 
155
 
    def test_adapter_checks_all_modules(self):
156
 
        # this checks that the adapter returns as many permutations as there
157
 
        # are in all the registered transport modules - we assume if this
158
 
        # matches its probably doing the right thing especially in combination
159
 
        # with the tests for setting the right classes below.
160
 
        from bzrlib.tests.test_transport_implementations \
161
 
            import TransportTestProviderAdapter
 
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
162
133
        from bzrlib.transport import _get_transport_modules
163
134
        modules = _get_transport_modules()
164
135
        permutation_count = 0
169
140
                     __import__(module))())
170
141
            except errors.DependencyNotPresent:
171
142
                pass
172
 
        input_test = TestTransportProviderAdapter(
173
 
            "test_adapter_sets_transport_class")
174
 
        adapter = TransportTestProviderAdapter()
175
 
        self.assertEqual(permutation_count,
176
 
                         len(list(iter(adapter.adapt(input_test)))))
 
143
        scenarios = transport_test_permutations()
 
144
        self.assertEqual(permutation_count, len(scenarios))
177
145
 
178
 
    def test_adapter_sets_transport_class(self):
179
 
        # Check that the test adapter inserts a transport and server into the
180
 
        # generated test.
181
 
        #
 
146
    def test_scenarios_include_transport_class(self):
182
147
        # This test used to know about all the possible transports and the
183
148
        # order they were returned but that seems overly brittle (mbp
184
149
        # 20060307)
185
 
        from bzrlib.tests.test_transport_implementations \
186
 
            import TransportTestProviderAdapter
187
 
        scenarios = TransportTestProviderAdapter().scenarios
 
150
        from bzrlib.tests.per_transport import transport_test_permutations
 
151
        scenarios = transport_test_permutations()
188
152
        # there are at least that many builtin transports
189
153
        self.assertTrue(len(scenarios) > 6)
190
154
        one_scenario = scenarios[0]
195
159
                                   bzrlib.transport.Server))
196
160
 
197
161
 
198
 
class TestBranchProviderAdapter(TestCase):
199
 
    """A group of tests that test the branch implementation test adapter."""
 
162
class TestBranchScenarios(tests.TestCase):
200
163
 
201
 
    def test_constructor(self):
 
164
    def test_scenarios(self):
202
165
        # check that constructor parameters are passed through to the adapted
203
166
        # test.
204
 
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
 
167
        from bzrlib.tests.per_branch import make_scenarios
205
168
        server1 = "a"
206
169
        server2 = "b"
207
170
        formats = [("c", "C"), ("d", "D")]
208
 
        adapter = BranchTestProviderAdapter(server1, server2, formats)
209
 
        self.assertEqual(2, len(adapter.scenarios))
 
171
        scenarios = make_scenarios(server1, server2, formats)
 
172
        self.assertEqual(2, len(scenarios))
210
173
        self.assertEqual([
211
174
            ('str',
212
175
             {'branch_format': 'c',
218
181
              'bzrdir_format': 'D',
219
182
              'transport_readonly_server': 'b',
220
183
              'transport_server': 'a'})],
221
 
            adapter.scenarios)
222
 
 
223
 
 
224
 
class TestBzrDirProviderAdapter(TestCase):
225
 
    """A group of tests that test the bzr dir implementation test adapter."""
226
 
 
227
 
    def test_adapted_tests(self):
 
184
            scenarios)
 
185
 
 
186
 
 
187
class TestBzrDirScenarios(tests.TestCase):
 
188
 
 
189
    def test_scenarios(self):
228
190
        # check that constructor parameters are passed through to the adapted
229
191
        # test.
230
 
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
 
192
        from bzrlib.tests.per_bzrdir import make_scenarios
231
193
        vfs_factory = "v"
232
194
        server1 = "a"
233
195
        server2 = "b"
234
196
        formats = ["c", "d"]
235
 
        adapter = BzrDirTestProviderAdapter(vfs_factory,
236
 
            server1, server2, formats)
 
197
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
237
198
        self.assertEqual([
238
199
            ('str',
239
200
             {'bzrdir_format': 'c',
245
206
              'transport_readonly_server': 'b',
246
207
              'transport_server': 'a',
247
208
              'vfs_transport_factory': 'v'})],
248
 
            adapter.scenarios)
249
 
 
250
 
 
251
 
class TestRepositoryParameterisation(TestCase):
252
 
    """A group of tests that test the repository implementation test adapter."""
 
209
            scenarios)
 
210
 
 
211
 
 
212
class TestRepositoryScenarios(tests.TestCase):
253
213
 
254
214
    def test_formats_to_scenarios(self):
255
 
        """The adapter can generate all the scenarios needed."""
256
215
        from bzrlib.tests.per_repository import formats_to_scenarios
257
216
        formats = [("(c)", remote.RemoteRepositoryFormat()),
258
217
                   ("(d)", repository.format_registry.get(
290
249
            vfs_scenarios)
291
250
 
292
251
 
293
 
class TestTestScenarioApplier(TestCase):
 
252
class TestTestScenarioApplication(tests.TestCase):
294
253
    """Tests for the test adaption facilities."""
295
254
 
296
 
    def test_adapt_applies_scenarios(self):
297
 
        from bzrlib.tests.per_repository import TestScenarioApplier
298
 
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
299
 
        adapter = TestScenarioApplier()
300
 
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
301
 
        calls = []
302
 
        def capture_call(test, scenario):
303
 
            calls.append((test, scenario))
304
 
            return test
305
 
        adapter.adapt_test_to_scenario = capture_call
306
 
        adapter.adapt(input_test)
307
 
        self.assertEqual([(input_test, ("1", "dict")),
308
 
            (input_test, ("2", "settings"))], calls)
309
 
 
310
 
    def test_adapt_test_to_scenario(self):
311
 
        from bzrlib.tests.per_repository import TestScenarioApplier
312
 
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
313
 
        adapter = TestScenarioApplier()
 
255
    def test_apply_scenario(self):
 
256
        from bzrlib.tests import apply_scenario
 
257
        input_test = TestTestScenarioApplication("test_apply_scenario")
314
258
        # setup two adapted tests
315
 
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
 
259
        adapted_test1 = apply_scenario(input_test,
316
260
            ("new id",
317
261
            {"bzrdir_format":"bzr_format",
318
262
             "repository_format":"repo_fmt",
319
263
             "transport_server":"transport_server",
320
264
             "transport_readonly_server":"readonly-server"}))
321
 
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
 
265
        adapted_test2 = apply_scenario(input_test,
322
266
            ("new id 2", {"bzrdir_format":None}))
323
267
        # input_test should have been altered.
324
268
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
331
275
        self.assertEqual("readonly-server",
332
276
            adapted_test1.transport_readonly_server)
333
277
        self.assertEqual(
334
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
335
 
            "test_adapt_test_to_scenario(new id)",
 
278
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
279
            "test_apply_scenario(new id)",
336
280
            adapted_test1.id())
337
281
        self.assertEqual(None, adapted_test2.bzrdir_format)
338
282
        self.assertEqual(
339
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
340
 
            "test_adapt_test_to_scenario(new id 2)",
 
283
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
284
            "test_apply_scenario(new id 2)",
341
285
            adapted_test2.id())
342
286
 
343
287
 
344
 
class TestInterRepositoryProviderAdapter(TestCase):
345
 
    """A group of tests that test the InterRepository test adapter."""
 
288
class TestInterRepositoryScenarios(tests.TestCase):
346
289
 
347
 
    def test_adapted_tests(self):
 
290
    def test_scenarios(self):
348
291
        # check that constructor parameters are passed through to the adapted
349
292
        # test.
350
 
        from bzrlib.tests.interrepository_implementations import \
351
 
            InterRepositoryTestProviderAdapter
 
293
        from bzrlib.tests.per_interrepository import make_scenarios
352
294
        server1 = "a"
353
295
        server2 = "b"
354
296
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
355
 
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
 
297
        scenarios = make_scenarios(server1, server2, formats)
356
298
        self.assertEqual([
357
299
            ('str,str,str',
358
300
             {'interrepo_class': str,
366
308
              'repository_format_to': 'D2',
367
309
              'transport_readonly_server': 'b',
368
310
              'transport_server': 'a'})],
369
 
            adapter.formats_to_scenarios(formats))
370
 
 
371
 
 
372
 
class TestWorkingTreeProviderAdapter(TestCase):
373
 
    """A group of tests that test the workingtree implementation test adapter."""
 
311
            scenarios)
 
312
 
 
313
 
 
314
class TestWorkingTreeScenarios(tests.TestCase):
374
315
 
375
316
    def test_scenarios(self):
376
317
        # check that constructor parameters are passed through to the adapted
377
318
        # test.
378
 
        from bzrlib.tests.workingtree_implementations \
379
 
            import WorkingTreeTestProviderAdapter
 
319
        from bzrlib.tests.per_workingtree import make_scenarios
380
320
        server1 = "a"
381
321
        server2 = "b"
382
322
        formats = [workingtree.WorkingTreeFormat2(),
383
323
                   workingtree.WorkingTreeFormat3(),]
384
 
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
324
        scenarios = make_scenarios(server1, server2, formats)
385
325
        self.assertEqual([
386
326
            ('WorkingTreeFormat2',
387
327
             {'bzrdir_format': formats[0]._matchingbzrdir,
393
333
              'transport_readonly_server': 'b',
394
334
              'transport_server': 'a',
395
335
              'workingtree_format': formats[1]})],
396
 
            adapter.scenarios)
397
 
 
398
 
 
399
 
class TestTreeProviderAdapter(TestCase):
400
 
    """Test the setup of tree_implementation tests."""
401
 
 
402
 
    def test_adapted_tests(self):
403
 
        # the tree implementation adapter is meant to setup one instance for
404
 
        # each working tree format, and one additional instance that will
405
 
        # use the default wt format, but create a revision tree for the tests.
406
 
        # this means that the wt ones should have the workingtree_to_test_tree
407
 
        # attribute set to 'return_parameter' and the revision one set to
408
 
        # revision_tree_from_workingtree.
409
 
 
410
 
        from bzrlib.tests.tree_implementations import (
411
 
            TreeTestProviderAdapter,
 
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,
412
354
            return_parameter,
413
355
            revision_tree_from_workingtree
414
356
            )
415
 
        input_test = TestTreeProviderAdapter(
416
 
            "test_adapted_tests")
417
357
        server1 = "a"
418
358
        server2 = "b"
419
359
        formats = [workingtree.WorkingTreeFormat2(),
420
360
                   workingtree.WorkingTreeFormat3(),]
421
 
        adapter = TreeTestProviderAdapter(server1, server2, formats)
422
 
        suite = adapter.adapt(input_test)
423
 
        tests = list(iter(suite))
424
 
        # XXX We should not have tests fail as we add more scenarios
425
 
        # abentley 20080412
426
 
        self.assertEqual(7, len(tests))
427
 
        # this must match the default format setp up in
428
 
        # TreeTestProviderAdapter.adapt
429
 
        default_format = workingtree.WorkingTreeFormat3
430
 
        self.assertEqual(tests[0].workingtree_format, formats[0])
431
 
        self.assertEqual(tests[0].bzrdir_format, formats[0]._matchingbzrdir)
432
 
        self.assertEqual(tests[0].transport_server, server1)
433
 
        self.assertEqual(tests[0].transport_readonly_server, server2)
434
 
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
435
 
        self.assertEqual(tests[1].workingtree_format, formats[1])
436
 
        self.assertEqual(tests[1].bzrdir_format, formats[1]._matchingbzrdir)
437
 
        self.assertEqual(tests[1].transport_server, server1)
438
 
        self.assertEqual(tests[1].transport_readonly_server, server2)
439
 
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
440
 
        self.assertIsInstance(tests[2].workingtree_format, default_format)
441
 
        #self.assertEqual(tests[2].bzrdir_format,
442
 
        #                 default_format._matchingbzrdir)
443
 
        self.assertEqual(tests[2].transport_server, server1)
444
 
        self.assertEqual(tests[2].transport_readonly_server, server2)
445
 
        self.assertEqual(tests[2]._workingtree_to_test_tree,
446
 
            revision_tree_from_workingtree)
447
 
 
448
 
 
449
 
class TestInterTreeProviderAdapter(TestCase):
 
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):
450
419
    """A group of tests that test the InterTreeTestAdapter."""
451
420
 
452
 
    def test_adapted_tests(self):
 
421
    def test_scenarios(self):
453
422
        # check that constructor parameters are passed through to the adapted
454
423
        # test.
455
424
        # for InterTree tests we want the machinery to bring up two trees in
459
428
        # unlike the TestProviderAdapter we dont want to automatically add a
460
429
        # parameterized one for WorkingTree - the optimisers will tell us what
461
430
        # ones to add.
462
 
        from bzrlib.tests.tree_implementations import (
 
431
        from bzrlib.tests.per_tree import (
463
432
            return_parameter,
464
433
            revision_tree_from_workingtree
465
434
            )
466
 
        from bzrlib.tests.intertree_implementations import (
467
 
            InterTreeTestProviderAdapter,
 
435
        from bzrlib.tests.per_intertree import (
 
436
            make_scenarios,
468
437
            )
469
438
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
470
 
        input_test = TestInterTreeProviderAdapter(
471
 
            "test_adapted_tests")
 
439
        input_test = TestInterTreeScenarios(
 
440
            "test_scenarios")
472
441
        server1 = "a"
473
442
        server2 = "b"
474
443
        format1 = WorkingTreeFormat2()
475
444
        format2 = WorkingTreeFormat3()
476
445
        formats = [("1", str, format1, format2, "converter1"),
477
446
            ("2", int, format2, format1, "converter2")]
478
 
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
479
 
        suite = adapter.adapt(input_test)
480
 
        tests = list(iter(suite))
481
 
        self.assertEqual(2, len(tests))
482
 
        self.assertEqual(tests[0].intertree_class, formats[0][1])
483
 
        self.assertEqual(tests[0].workingtree_format, formats[0][2])
484
 
        self.assertEqual(tests[0].workingtree_format_to, formats[0][3])
485
 
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][4])
486
 
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
487
 
        self.assertEqual(tests[0].transport_server, server1)
488
 
        self.assertEqual(tests[0].transport_readonly_server, server2)
489
 
        self.assertEqual(tests[1].intertree_class, formats[1][1])
490
 
        self.assertEqual(tests[1].workingtree_format, formats[1][2])
491
 
        self.assertEqual(tests[1].workingtree_format_to, formats[1][3])
492
 
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][4])
493
 
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
494
 
        self.assertEqual(tests[1].transport_server, server1)
495
 
        self.assertEqual(tests[1].transport_readonly_server, server2)
496
 
 
497
 
 
498
 
class TestTestCaseInTempDir(TestCaseInTempDir):
 
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):
499
475
 
500
476
    def test_home_is_not_working(self):
501
477
        self.assertNotEqual(self.test_dir, self.test_home_dir)
517
493
            os.lstat("foo"), os.lstat("bar"))
518
494
 
519
495
 
520
 
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
496
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
521
497
 
522
498
    def test_home_is_non_existant_dir_under_root(self):
523
499
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
612
588
        # But we have a safety net in place.
613
589
        self.assertRaises(AssertionError, self._check_safety_net)
614
590
 
615
 
 
616
 
class TestTestCaseWithTransport(TestCaseWithTransport):
 
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):
617
604
    """Tests for the convenience functions TestCaseWithTransport introduces."""
618
605
 
619
606
    def test_get_readonly_url_none(self):
670
657
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
671
658
 
672
659
 
673
 
class TestTestCaseTransports(TestCaseWithTransport):
 
660
class TestTestCaseTransports(tests.TestCaseWithTransport):
674
661
 
675
662
    def setUp(self):
676
663
        super(TestTestCaseTransports, self).setUp()
685
672
        self.failIfExists('subdir')
686
673
 
687
674
 
688
 
class TestChrootedTest(ChrootedTestCase):
 
675
class TestChrootedTest(tests.ChrootedTestCase):
689
676
 
690
677
    def test_root_is_root(self):
691
678
        from bzrlib.transport import get_transport
694
681
        self.assertEqual(url, t.clone('..').base)
695
682
 
696
683
 
697
 
class MockProgress(_BaseProgressBar):
 
684
class MockProgress(progress._BaseProgressBar):
698
685
    """Progress-bar standin that records calls.
699
686
 
700
687
    Useful for testing pb using code.
701
688
    """
702
689
 
703
690
    def __init__(self):
704
 
        _BaseProgressBar.__init__(self)
 
691
        progress._BaseProgressBar.__init__(self)
705
692
        self.calls = []
706
693
 
707
694
    def tick(self):
717
704
        self.calls.append(('note', msg, args))
718
705
 
719
706
 
720
 
class TestTestResult(TestCase):
 
707
class TestTestResult(tests.TestCase):
721
708
 
722
709
    def check_timing(self, test_case, expected_re):
723
710
        result = bzrlib.tests.TextTestResult(self._log_file,
729
716
        self.assertContainsRe(timed_string, expected_re)
730
717
 
731
718
    def test_test_reporting(self):
732
 
        class ShortDelayTestCase(TestCase):
 
719
        class ShortDelayTestCase(tests.TestCase):
733
720
            def test_short_delay(self):
734
721
                time.sleep(0.003)
735
722
            def test_short_benchmark(self):
736
723
                self.time(time.sleep, 0.003)
737
724
        self.check_timing(ShortDelayTestCase('test_short_delay'),
738
725
                          r"^ +[0-9]+ms$")
739
 
        # if a benchmark time is given, we want a x of y style result.
 
726
        # if a benchmark time is given, we now show just that time followed by
 
727
        # a star
740
728
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
741
 
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
 
729
                          r"^ +[0-9]+ms\*$")
742
730
 
743
731
    def test_unittest_reporting_unittest_class(self):
744
732
        # getting the time from a non-bzrlib test works ok
828
816
 
829
817
    def test_known_failure(self):
830
818
        """A KnownFailure being raised should trigger several result actions."""
831
 
        class InstrumentedTestResult(ExtendedTestResult):
832
 
 
 
819
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
820
            def done(self): pass
 
821
            def startTests(self): pass
833
822
            def report_test_start(self, test): pass
834
823
            def report_known_failure(self, test, err):
835
824
                self._call = test, err
836
825
        result = InstrumentedTestResult(None, None, None, None)
837
826
        def test_function():
838
 
            raise KnownFailure('failed!')
 
827
            raise tests.KnownFailure('failed!')
839
828
        test = unittest.FunctionTestCase(test_function)
840
829
        test.run(result)
841
830
        # it should invoke 'report_known_failure'.
842
831
        self.assertEqual(2, len(result._call))
843
832
        self.assertEqual(test, result._call[0])
844
 
        self.assertEqual(KnownFailure, result._call[1][0])
845
 
        self.assertIsInstance(result._call[1][1], KnownFailure)
 
833
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
834
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
846
835
        # we dont introspec the traceback, if the rest is ok, it would be
847
836
        # exceptional for it not to be.
848
837
        # it should update the known_failure_count on the object.
865
854
        # (class, exception object, traceback)
866
855
        # KnownFailures dont get their tracebacks shown though, so we
867
856
        # can skip that.
868
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
857
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
869
858
        result.report_known_failure(test, err)
870
859
        output = result_stream.getvalue()[prefix:]
871
860
        lines = output.splitlines()
877
866
        # text test output formatting
878
867
        pb = MockProgress()
879
868
        result = bzrlib.tests.TextTestResult(
880
 
            None,
 
869
            StringIO(),
881
870
            descriptions=0,
882
871
            verbosity=1,
883
872
            pb=pb,
889
878
        # (class, exception object, traceback)
890
879
        # KnownFailures dont get their tracebacks shown though, so we
891
880
        # can skip that.
892
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
881
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
893
882
        result.report_known_failure(test, err)
894
883
        self.assertEqual(
895
884
            [
916
905
 
917
906
    def test_add_not_supported(self):
918
907
        """Test the behaviour of invoking addNotSupported."""
919
 
        class InstrumentedTestResult(ExtendedTestResult):
 
908
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
909
            def done(self): pass
 
910
            def startTests(self): pass
920
911
            def report_test_start(self, test): pass
921
912
            def report_unsupported(self, test, feature):
922
913
                self._call = test, feature
923
914
        result = InstrumentedTestResult(None, None, None, None)
924
915
        test = SampleTestCase('_test_pass')
925
 
        feature = Feature()
 
916
        feature = tests.Feature()
926
917
        result.startTest(test)
927
918
        result.addNotSupported(test, feature)
928
919
        # it should invoke 'report_unsupported'.
947
938
            verbosity=2,
948
939
            )
949
940
        test = self.get_passing_test()
950
 
        feature = Feature()
 
941
        feature = tests.Feature()
951
942
        result.startTest(test)
952
943
        prefix = len(result_stream.getvalue())
953
944
        result.report_unsupported(test, feature)
954
945
        output = result_stream.getvalue()[prefix:]
955
946
        lines = output.splitlines()
956
 
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
 
947
        self.assertEqual(lines, ['NODEP        0ms',
 
948
                                 "    The feature 'Feature' is not available."])
957
949
 
958
950
    def test_text_report_unsupported(self):
959
951
        # text test output formatting
960
952
        pb = MockProgress()
961
953
        result = bzrlib.tests.TextTestResult(
962
 
            None,
 
954
            StringIO(),
963
955
            descriptions=0,
964
956
            verbosity=1,
965
957
            pb=pb,
966
958
            )
967
959
        test = self.get_passing_test()
968
 
        feature = Feature()
 
960
        feature = tests.Feature()
969
961
        # this seeds the state to handle reporting the test.
970
962
        result.startTest(test)
971
963
        result.report_unsupported(test, feature)
986
978
 
987
979
    def test_unavailable_exception(self):
988
980
        """An UnavailableFeature being raised should invoke addNotSupported."""
989
 
        class InstrumentedTestResult(ExtendedTestResult):
990
 
 
 
981
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
982
            def done(self): pass
 
983
            def startTests(self): pass
991
984
            def report_test_start(self, test): pass
992
985
            def addNotSupported(self, test, feature):
993
986
                self._call = test, feature
994
987
        result = InstrumentedTestResult(None, None, None, None)
995
 
        feature = Feature()
 
988
        feature = tests.Feature()
996
989
        def test_function():
997
 
            raise UnavailableFeature(feature)
 
990
            raise tests.UnavailableFeature(feature)
998
991
        test = unittest.FunctionTestCase(test_function)
999
992
        test.run(result)
1000
993
        # it should invoke 'addNotSupported'.
1017
1010
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1018
1011
                                             verbosity=1)
1019
1012
        test = self.get_passing_test()
1020
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
1013
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
1021
1014
        result._addKnownFailure(test, err)
1022
1015
        self.assertFalse(result.wasStrictlySuccessful())
1023
1016
        self.assertEqual(None, result._extractBenchmarkTime(test))
1030
1023
        self.assertTrue(result.wasStrictlySuccessful())
1031
1024
        self.assertEqual(None, result._extractBenchmarkTime(test))
1032
1025
 
1033
 
 
1034
 
class TestUnicodeFilenameFeature(TestCase):
 
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):
1035
1041
 
1036
1042
    def test_probe_passes(self):
1037
1043
        """UnicodeFilenameFeature._probe passes."""
1040
1046
        tests.UnicodeFilenameFeature._probe()
1041
1047
 
1042
1048
 
1043
 
class TestRunner(TestCase):
 
1049
class TestRunner(tests.TestCase):
1044
1050
 
1045
1051
    def dummy_test(self):
1046
1052
        pass
1051
1057
        This current saves and restores:
1052
1058
        TestCaseInTempDir.TEST_ROOT
1053
1059
 
1054
 
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
1055
 
        without using this convenience method, because of our use of global state.
 
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.
1056
1063
        """
1057
 
        old_root = TestCaseInTempDir.TEST_ROOT
 
1064
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1058
1065
        try:
1059
 
            TestCaseInTempDir.TEST_ROOT = None
 
1066
            tests.TestCaseInTempDir.TEST_ROOT = None
1060
1067
            return testrunner.run(test)
1061
1068
        finally:
1062
 
            TestCaseInTempDir.TEST_ROOT = old_root
 
1069
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1063
1070
 
1064
1071
    def test_known_failure_failed_run(self):
1065
1072
        # run a test that generates a known failure which should be printed in
1066
1073
        # the final output when real failures occur.
1067
1074
        def known_failure_test():
1068
 
            raise KnownFailure('failed')
 
1075
            raise tests.KnownFailure('failed')
1069
1076
        test = unittest.TestSuite()
1070
1077
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1071
1078
        def failing_test():
1072
1079
            raise AssertionError('foo')
1073
1080
        test.addTest(unittest.FunctionTestCase(failing_test))
1074
1081
        stream = StringIO()
1075
 
        runner = TextTestRunner(stream=stream)
 
1082
        runner = tests.TextTestRunner(stream=stream)
1076
1083
        result = self.run_test_runner(runner, test)
1077
1084
        lines = stream.getvalue().splitlines()
1078
1085
        self.assertEqual([
1087
1094
            '----------------------------------------------------------------------',
1088
1095
            '',
1089
1096
            'FAILED (failures=1, known_failure_count=1)'],
1090
 
            lines[0:5] + lines[6:10] + lines[11:])
 
1097
            lines[3:8] + lines[9:13] + lines[14:])
1091
1098
 
1092
1099
    def test_known_failure_ok_run(self):
1093
1100
        # run a test that generates a known failure which should be printed in the final output.
1094
1101
        def known_failure_test():
1095
 
            raise KnownFailure('failed')
 
1102
            raise tests.KnownFailure('failed')
1096
1103
        test = unittest.FunctionTestCase(known_failure_test)
1097
1104
        stream = StringIO()
1098
 
        runner = TextTestRunner(stream=stream)
 
1105
        runner = tests.TextTestRunner(stream=stream)
1099
1106
        result = self.run_test_runner(runner, test)
1100
1107
        self.assertContainsRe(stream.getvalue(),
1101
1108
            '\n'
1108
1115
        # run a test that is skipped, and check the suite as a whole still
1109
1116
        # succeeds.
1110
1117
        # skipping_test must be hidden in here so it's not run as a real test
1111
 
        class SkippingTest(TestCase):
 
1118
        class SkippingTest(tests.TestCase):
1112
1119
            def skipping_test(self):
1113
 
                raise TestSkipped('test intentionally skipped')
1114
 
        runner = TextTestRunner(stream=self._log_file)
 
1120
                raise tests.TestSkipped('test intentionally skipped')
 
1121
        runner = tests.TextTestRunner(stream=self._log_file)
1115
1122
        test = SkippingTest("skipping_test")
1116
1123
        result = self.run_test_runner(runner, test)
1117
1124
        self.assertTrue(result.wasSuccessful())
1118
1125
 
1119
1126
    def test_skipped_from_setup(self):
1120
1127
        calls = []
1121
 
        class SkippedSetupTest(TestCase):
 
1128
        class SkippedSetupTest(tests.TestCase):
1122
1129
 
1123
1130
            def setUp(self):
1124
1131
                calls.append('setUp')
1125
1132
                self.addCleanup(self.cleanup)
1126
 
                raise TestSkipped('skipped setup')
 
1133
                raise tests.TestSkipped('skipped setup')
1127
1134
 
1128
1135
            def test_skip(self):
1129
1136
                self.fail('test reached')
1131
1138
            def cleanup(self):
1132
1139
                calls.append('cleanup')
1133
1140
 
1134
 
        runner = TextTestRunner(stream=self._log_file)
 
1141
        runner = tests.TextTestRunner(stream=self._log_file)
1135
1142
        test = SkippedSetupTest('test_skip')
1136
1143
        result = self.run_test_runner(runner, test)
1137
1144
        self.assertTrue(result.wasSuccessful())
1140
1147
 
1141
1148
    def test_skipped_from_test(self):
1142
1149
        calls = []
1143
 
        class SkippedTest(TestCase):
 
1150
        class SkippedTest(tests.TestCase):
1144
1151
 
1145
1152
            def setUp(self):
 
1153
                tests.TestCase.setUp(self)
1146
1154
                calls.append('setUp')
1147
1155
                self.addCleanup(self.cleanup)
1148
1156
 
1149
1157
            def test_skip(self):
1150
 
                raise TestSkipped('skipped test')
 
1158
                raise tests.TestSkipped('skipped test')
1151
1159
 
1152
1160
            def cleanup(self):
1153
1161
                calls.append('cleanup')
1154
1162
 
1155
 
        runner = TextTestRunner(stream=self._log_file)
 
1163
        runner = tests.TextTestRunner(stream=self._log_file)
1156
1164
        test = SkippedTest('test_skip')
1157
1165
        result = self.run_test_runner(runner, test)
1158
1166
        self.assertTrue(result.wasSuccessful())
1162
1170
    def test_not_applicable(self):
1163
1171
        # run a test that is skipped because it's not applicable
1164
1172
        def not_applicable_test():
1165
 
            from bzrlib.tests import TestNotApplicable
1166
 
            raise TestNotApplicable('this test never runs')
 
1173
            raise tests.TestNotApplicable('this test never runs')
1167
1174
        out = StringIO()
1168
 
        runner = TextTestRunner(stream=out, verbosity=2)
 
1175
        runner = tests.TextTestRunner(stream=out, verbosity=2)
1169
1176
        test = unittest.FunctionTestCase(not_applicable_test)
1170
1177
        result = self.run_test_runner(runner, test)
1171
1178
        self._log_file.write(out.getvalue())
1178
1185
 
1179
1186
    def test_not_applicable_demo(self):
1180
1187
        # just so you can see it in the test output
1181
 
        raise TestNotApplicable('this test is just a demonstation')
 
1188
        raise tests.TestNotApplicable('this test is just a demonstation')
1182
1189
 
1183
1190
    def test_unsupported_features_listed(self):
1184
1191
        """When unsupported features are encountered they are detailed."""
1185
 
        class Feature1(Feature):
 
1192
        class Feature1(tests.Feature):
1186
1193
            def _probe(self): return False
1187
 
        class Feature2(Feature):
 
1194
        class Feature2(tests.Feature):
1188
1195
            def _probe(self): return False
1189
1196
        # create sample tests
1190
1197
        test1 = SampleTestCase('_test_pass')
1195
1202
        test.addTest(test1)
1196
1203
        test.addTest(test2)
1197
1204
        stream = StringIO()
1198
 
        runner = TextTestRunner(stream=stream)
 
1205
        runner = tests.TextTestRunner(stream=stream)
1199
1206
        result = self.run_test_runner(runner, test)
1200
1207
        lines = stream.getvalue().splitlines()
1201
1208
        self.assertEqual([
1212
1219
        workingtree = _get_bzr_source_tree()
1213
1220
        test = TestRunner('dummy_test')
1214
1221
        output = StringIO()
1215
 
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
1222
        runner = tests.TextTestRunner(stream=self._log_file,
 
1223
                                      bench_history=output)
1216
1224
        result = self.run_test_runner(runner, test)
1217
1225
        output_string = output.getvalue()
1218
1226
        self.assertContainsRe(output_string, "--date [0-9.]+")
1229
1237
    def test_success_log_deleted(self):
1230
1238
        """Successful tests have their log deleted"""
1231
1239
 
1232
 
        class LogTester(TestCase):
 
1240
        class LogTester(tests.TestCase):
1233
1241
 
1234
1242
            def test_success(self):
1235
1243
                self.log('this will be removed\n')
1236
1244
 
1237
 
        sio = cStringIO.StringIO()
1238
 
        runner = TextTestRunner(stream=sio)
 
1245
        sio = StringIO()
 
1246
        runner = tests.TextTestRunner(stream=sio)
1239
1247
        test = LogTester('test_success')
1240
1248
        result = self.run_test_runner(runner, test)
1241
1249
 
1244
1252
    def test_skipped_log_deleted(self):
1245
1253
        """Skipped tests have their log deleted"""
1246
1254
 
1247
 
        class LogTester(TestCase):
 
1255
        class LogTester(tests.TestCase):
1248
1256
 
1249
1257
            def test_skipped(self):
1250
1258
                self.log('this will be removed\n')
1251
1259
                raise tests.TestSkipped()
1252
1260
 
1253
 
        sio = cStringIO.StringIO()
1254
 
        runner = TextTestRunner(stream=sio)
 
1261
        sio = StringIO()
 
1262
        runner = tests.TextTestRunner(stream=sio)
1255
1263
        test = LogTester('test_skipped')
1256
1264
        result = self.run_test_runner(runner, test)
1257
1265
 
1260
1268
    def test_not_aplicable_log_deleted(self):
1261
1269
        """Not applicable tests have their log deleted"""
1262
1270
 
1263
 
        class LogTester(TestCase):
 
1271
        class LogTester(tests.TestCase):
1264
1272
 
1265
1273
            def test_not_applicable(self):
1266
1274
                self.log('this will be removed\n')
1267
1275
                raise tests.TestNotApplicable()
1268
1276
 
1269
 
        sio = cStringIO.StringIO()
1270
 
        runner = TextTestRunner(stream=sio)
 
1277
        sio = StringIO()
 
1278
        runner = tests.TextTestRunner(stream=sio)
1271
1279
        test = LogTester('test_not_applicable')
1272
1280
        result = self.run_test_runner(runner, test)
1273
1281
 
1276
1284
    def test_known_failure_log_deleted(self):
1277
1285
        """Know failure tests have their log deleted"""
1278
1286
 
1279
 
        class LogTester(TestCase):
 
1287
        class LogTester(tests.TestCase):
1280
1288
 
1281
1289
            def test_known_failure(self):
1282
1290
                self.log('this will be removed\n')
1283
1291
                raise tests.KnownFailure()
1284
1292
 
1285
 
        sio = cStringIO.StringIO()
1286
 
        runner = TextTestRunner(stream=sio)
 
1293
        sio = StringIO()
 
1294
        runner = tests.TextTestRunner(stream=sio)
1287
1295
        test = LogTester('test_known_failure')
1288
1296
        result = self.run_test_runner(runner, test)
1289
1297
 
1292
1300
    def test_fail_log_kept(self):
1293
1301
        """Failed tests have their log kept"""
1294
1302
 
1295
 
        class LogTester(TestCase):
 
1303
        class LogTester(tests.TestCase):
1296
1304
 
1297
1305
            def test_fail(self):
1298
1306
                self.log('this will be kept\n')
1299
1307
                self.fail('this test fails')
1300
1308
 
1301
 
        sio = cStringIO.StringIO()
1302
 
        runner = TextTestRunner(stream=sio)
 
1309
        sio = StringIO()
 
1310
        runner = tests.TextTestRunner(stream=sio)
1303
1311
        test = LogTester('test_fail')
1304
1312
        result = self.run_test_runner(runner, test)
1305
1313
 
1314
1322
    def test_error_log_kept(self):
1315
1323
        """Tests with errors have their log kept"""
1316
1324
 
1317
 
        class LogTester(TestCase):
 
1325
        class LogTester(tests.TestCase):
1318
1326
 
1319
1327
            def test_error(self):
1320
1328
                self.log('this will be kept\n')
1321
1329
                raise ValueError('random exception raised')
1322
1330
 
1323
 
        sio = cStringIO.StringIO()
1324
 
        runner = TextTestRunner(stream=sio)
 
1331
        sio = StringIO()
 
1332
        runner = tests.TextTestRunner(stream=sio)
1325
1333
        test = LogTester('test_error')
1326
1334
        result = self.run_test_runner(runner, test)
1327
1335
 
1334
1342
        self.assertEqual(log, test._log_contents)
1335
1343
 
1336
1344
 
1337
 
class SampleTestCase(TestCase):
 
1345
class SampleTestCase(tests.TestCase):
1338
1346
 
1339
1347
    def _test_pass(self):
1340
1348
        pass
1342
1350
class _TestException(Exception):
1343
1351
    pass
1344
1352
 
1345
 
class TestTestCase(TestCase):
 
1353
class TestTestCase(tests.TestCase):
1346
1354
    """Tests that test the core bzrlib TestCase."""
1347
1355
 
 
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
 
1348
1399
    def test_debug_flags_sanitised(self):
1349
1400
        """The bzrlib debug flags should be sanitised by setUp."""
1350
1401
        if 'allow_debug' in tests.selftest_debug_flags:
1351
 
            raise TestNotApplicable(
 
1402
            raise tests.TestNotApplicable(
1352
1403
                '-Eallow_debug option prevents debug flag sanitisation')
1353
1404
        # we could set something and run a test that will check
1354
1405
        # it gets santised, but this is probably sufficient for now:
1369
1420
        """
1370
1421
        self.change_selftest_debug_flags(set(['allow_debug']))
1371
1422
        bzrlib.debug.debug_flags = set(['a-flag'])
1372
 
        class TestThatRecordsFlags(TestCase):
 
1423
        class TestThatRecordsFlags(tests.TestCase):
1373
1424
            def test_foo(nested_self):
1374
1425
                self.flags = set(bzrlib.debug.debug_flags)
1375
1426
        test = TestThatRecordsFlags('test_foo')
1383
1434
        self.change_selftest_debug_flags(set(['allow_debug']))
1384
1435
        # Now run a test that modifies debug.debug_flags.
1385
1436
        bzrlib.debug.debug_flags = set(['original-state'])
1386
 
        class TestThatModifiesFlags(TestCase):
 
1437
        class TestThatModifiesFlags(tests.TestCase):
1387
1438
            def test_foo(self):
1388
1439
                bzrlib.debug.debug_flags = set(['modified'])
1389
1440
        test = TestThatModifiesFlags('test_foo')
1391
1442
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1392
1443
 
1393
1444
    def make_test_result(self):
1394
 
        return bzrlib.tests.TextTestResult(
1395
 
            self._log_file, descriptions=0, verbosity=1)
 
1445
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1396
1446
 
1397
1447
    def inner_test(self):
1398
1448
        # the inner child test
1441
1491
        sample_test.run(result)
1442
1492
        self.assertContainsRe(
1443
1493
            output_stream.getvalue(),
1444
 
            r"\d+ms/ +\d+ms\n$")
 
1494
            r"\d+ms\*\n$")
1445
1495
 
1446
1496
    def test_hooks_sanitised(self):
1447
1497
        """The bzrlib hooks should be sanitised by setUp."""
1474
1524
 
1475
1525
    def test_knownFailure(self):
1476
1526
        """Self.knownFailure() should raise a KnownFailure exception."""
1477
 
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
 
1527
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1478
1528
 
1479
1529
    def test_requireFeature_available(self):
1480
1530
        """self.requireFeature(available) is a no-op."""
1481
 
        class Available(Feature):
 
1531
        class Available(tests.Feature):
1482
1532
            def _probe(self):return True
1483
1533
        feature = Available()
1484
1534
        self.requireFeature(feature)
1485
1535
 
1486
1536
    def test_requireFeature_unavailable(self):
1487
1537
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1488
 
        class Unavailable(Feature):
 
1538
        class Unavailable(tests.Feature):
1489
1539
            def _probe(self):return False
1490
1540
        feature = Unavailable()
1491
 
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
 
1541
        self.assertRaises(tests.UnavailableFeature,
 
1542
                          self.requireFeature, feature)
1492
1543
 
1493
1544
    def test_run_no_parameters(self):
1494
1545
        test = SampleTestCase('_test_pass')
1603
1654
            self.assertListRaises, _TestException, success_generator)
1604
1655
 
1605
1656
 
1606
 
@symbol_versioning.deprecated_function(zero_eleven)
 
1657
# NB: Don't delete this; it's not actually from 0.11!
 
1658
@deprecated_function(deprecated_in((0, 11, 0)))
1607
1659
def sample_deprecated_function():
1608
1660
    """A deprecated function to test applyDeprecated with."""
1609
1661
    return 2
1616
1668
class ApplyDeprecatedHelper(object):
1617
1669
    """A helper class for ApplyDeprecated tests."""
1618
1670
 
1619
 
    @symbol_versioning.deprecated_method(zero_eleven)
 
1671
    @deprecated_method(deprecated_in((0, 11, 0)))
1620
1672
    def sample_deprecated_method(self, param_one):
1621
1673
        """A deprecated method for testing with."""
1622
1674
        return param_one
1624
1676
    def sample_normal_method(self):
1625
1677
        """A undeprecated method."""
1626
1678
 
1627
 
    @symbol_versioning.deprecated_method(zero_ten)
 
1679
    @deprecated_method(deprecated_in((0, 10, 0)))
1628
1680
    def sample_nested_deprecation(self):
1629
1681
        return sample_deprecated_function()
1630
1682
 
1631
1683
 
1632
 
class TestExtraAssertions(TestCase):
 
1684
class TestExtraAssertions(tests.TestCase):
1633
1685
    """Tests for new test assertions in bzrlib test suite"""
1634
1686
 
1635
1687
    def test_assert_isinstance(self):
1636
1688
        self.assertIsInstance(2, int)
1637
1689
        self.assertIsInstance(u'', basestring)
1638
 
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
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'>")
1639
1693
        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")
1640
1699
 
1641
1700
    def test_assertEndsWith(self):
1642
1701
        self.assertEndsWith('foo', 'oo')
1645
1704
    def test_applyDeprecated_not_deprecated(self):
1646
1705
        sample_object = ApplyDeprecatedHelper()
1647
1706
        # calling an undeprecated callable raises an assertion
1648
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1707
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1708
            deprecated_in((0, 11, 0)),
1649
1709
            sample_object.sample_normal_method)
1650
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1710
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1711
            deprecated_in((0, 11, 0)),
1651
1712
            sample_undeprecated_function, "a param value")
1652
1713
        # calling a deprecated callable (function or method) with the wrong
1653
1714
        # expected deprecation fails.
1654
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1715
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1716
            deprecated_in((0, 10, 0)),
1655
1717
            sample_object.sample_deprecated_method, "a param value")
1656
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1718
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1719
            deprecated_in((0, 10, 0)),
1657
1720
            sample_deprecated_function)
1658
1721
        # calling a deprecated callable (function or method) with the right
1659
1722
        # expected deprecation returns the functions result.
1660
 
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
1723
        self.assertEqual("a param value",
 
1724
            self.applyDeprecated(deprecated_in((0, 11, 0)),
1661
1725
            sample_object.sample_deprecated_method, "a param value"))
1662
 
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
1726
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1663
1727
            sample_deprecated_function))
1664
1728
        # calling a nested deprecation with the wrong deprecation version
1665
1729
        # fails even if a deeper nested function was deprecated with the
1666
1730
        # supplied version.
1667
1731
        self.assertRaises(AssertionError, self.applyDeprecated,
1668
 
            zero_eleven, sample_object.sample_nested_deprecation)
 
1732
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1669
1733
        # calling a nested deprecation with the right deprecation value
1670
1734
        # returns the calls result.
1671
 
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
1735
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1672
1736
            sample_object.sample_nested_deprecation))
1673
1737
 
1674
1738
    def test_callDeprecated(self):
1685
1749
        self.callDeprecated([], testfunc, be_deprecated=False)
1686
1750
 
1687
1751
 
1688
 
class TestWarningTests(TestCase):
 
1752
class TestWarningTests(tests.TestCase):
1689
1753
    """Tests for calling methods that raise warnings."""
1690
1754
 
1691
1755
    def test_callCatchWarnings(self):
1701
1765
        self.assertEquals("this is your last warning", str(w0))
1702
1766
 
1703
1767
 
1704
 
class TestConvenienceMakers(TestCaseWithTransport):
 
1768
class TestConvenienceMakers(tests.TestCaseWithTransport):
1705
1769
    """Test for the make_* convenience functions."""
1706
1770
 
1707
1771
    def test_make_branch_and_tree_with_format(self):
1720
1784
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1721
1785
 
1722
1786
 
1723
 
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1787
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
1724
1788
 
1725
1789
    def test_make_tree_for_sftp_branch(self):
1726
1790
        """Transports backed by local directories create local trees."""
1735
1799
                tree.branch.repository.bzrdir.root_transport)
1736
1800
 
1737
1801
 
1738
 
class TestSelftest(TestCase):
 
1802
class TestSelftest(tests.TestCase):
1739
1803
    """Tests of bzrlib.tests.selftest."""
1740
1804
 
1741
1805
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1742
1806
        factory_called = []
1743
1807
        def factory():
1744
1808
            factory_called.append(True)
1745
 
            return TestSuite()
 
1809
            return TestUtil.TestSuite()
1746
1810
        out = StringIO()
1747
1811
        err = StringIO()
1748
1812
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1750
1814
        self.assertEqual([True], factory_called)
1751
1815
 
1752
1816
 
1753
 
class TestKnownFailure(TestCase):
 
1817
class TestKnownFailure(tests.TestCase):
1754
1818
 
1755
1819
    def test_known_failure(self):
1756
1820
        """Check that KnownFailure is defined appropriately."""
1757
1821
        # a KnownFailure is an assertion error for compatability with unaware
1758
1822
        # runners.
1759
 
        self.assertIsInstance(KnownFailure(""), AssertionError)
 
1823
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
1760
1824
 
1761
1825
    def test_expect_failure(self):
1762
1826
        try:
1763
1827
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1764
 
        except KnownFailure, e:
 
1828
        except tests.KnownFailure, e:
1765
1829
            self.assertEqual('Doomed to failure', e.args[0])
1766
1830
        try:
1767
1831
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1772
1836
            self.fail('Assertion not raised')
1773
1837
 
1774
1838
 
1775
 
class TestFeature(TestCase):
 
1839
class TestFeature(tests.TestCase):
1776
1840
 
1777
1841
    def test_caching(self):
1778
1842
        """Feature._probe is called by the feature at most once."""
1779
 
        class InstrumentedFeature(Feature):
 
1843
        class InstrumentedFeature(tests.Feature):
1780
1844
            def __init__(self):
1781
 
                Feature.__init__(self)
 
1845
                super(InstrumentedFeature, self).__init__()
1782
1846
                self.calls = []
1783
1847
            def _probe(self):
1784
1848
                self.calls.append('_probe')
1791
1855
 
1792
1856
    def test_named_str(self):
1793
1857
        """Feature.__str__ should thunk to feature_name()."""
1794
 
        class NamedFeature(Feature):
 
1858
        class NamedFeature(tests.Feature):
1795
1859
            def feature_name(self):
1796
1860
                return 'symlinks'
1797
1861
        feature = NamedFeature()
1799
1863
 
1800
1864
    def test_default_str(self):
1801
1865
        """Feature.__str__ should default to __class__.__name__."""
1802
 
        class NamedFeature(Feature):
 
1866
        class NamedFeature(tests.Feature):
1803
1867
            pass
1804
1868
        feature = NamedFeature()
1805
1869
        self.assertEqual('NamedFeature', str(feature))
1806
1870
 
1807
1871
 
1808
 
class TestUnavailableFeature(TestCase):
 
1872
class TestUnavailableFeature(tests.TestCase):
1809
1873
 
1810
1874
    def test_access_feature(self):
1811
 
        feature = Feature()
1812
 
        exception = UnavailableFeature(feature)
 
1875
        feature = tests.Feature()
 
1876
        exception = tests.UnavailableFeature(feature)
1813
1877
        self.assertIs(feature, exception.args[0])
1814
1878
 
1815
1879
 
1816
 
class TestSelftestFiltering(TestCase):
 
1880
class TestSelftestFiltering(tests.TestCase):
1817
1881
 
1818
1882
    def setUp(self):
 
1883
        tests.TestCase.setUp(self)
1819
1884
        self.suite = TestUtil.TestSuite()
1820
1885
        self.loader = TestUtil.TestLoader()
1821
1886
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1825
1890
    def test_condition_id_re(self):
1826
1891
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1827
1892
            'test_condition_id_re')
1828
 
        filtered_suite = filter_suite_by_condition(self.suite,
1829
 
            condition_id_re('test_condition_id_re'))
 
1893
        filtered_suite = tests.filter_suite_by_condition(
 
1894
            self.suite, tests.condition_id_re('test_condition_id_re'))
1830
1895
        self.assertEqual([test_name], _test_ids(filtered_suite))
1831
1896
 
1832
1897
    def test_condition_id_in_list(self):
1833
1898
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1834
1899
                      'test_condition_id_in_list']
1835
1900
        id_list = tests.TestIdList(test_names)
1836
 
        filtered_suite = filter_suite_by_condition(
 
1901
        filtered_suite = tests.filter_suite_by_condition(
1837
1902
            self.suite, tests.condition_id_in_list(id_list))
1838
1903
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1839
 
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
 
1904
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
1840
1905
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1841
1906
 
1842
1907
    def test_condition_id_startswith(self):
1846
1911
        test_names = [ klass + 'test_condition_id_in_list',
1847
1912
                      klass + 'test_condition_id_startswith',
1848
1913
                     ]
1849
 
        filtered_suite = filter_suite_by_condition(
 
1914
        filtered_suite = tests.filter_suite_by_condition(
1850
1915
            self.suite, tests.condition_id_startswith([start1, start2]))
1851
1916
        self.assertEqual(test_names, _test_ids(filtered_suite))
1852
1917
 
1853
1918
    def test_condition_isinstance(self):
1854
 
        filtered_suite = filter_suite_by_condition(self.suite,
1855
 
            condition_isinstance(self.__class__))
 
1919
        filtered_suite = tests.filter_suite_by_condition(
 
1920
            self.suite, tests.condition_isinstance(self.__class__))
1856
1921
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1857
 
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
 
1922
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
1858
1923
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1859
1924
 
1860
1925
    def test_exclude_tests_by_condition(self):
1861
1926
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1862
1927
            'test_exclude_tests_by_condition')
1863
 
        filtered_suite = exclude_tests_by_condition(self.suite,
 
1928
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
1864
1929
            lambda x:x.id() == excluded_name)
1865
1930
        self.assertEqual(len(self.all_names) - 1,
1866
1931
            filtered_suite.countTestCases())
1871
1936
 
1872
1937
    def test_exclude_tests_by_re(self):
1873
1938
        self.all_names = _test_ids(self.suite)
1874
 
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
 
1939
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
1940
                                                   'exclude_tests_by_re')
1875
1941
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1876
1942
            'test_exclude_tests_by_re')
1877
1943
        self.assertEqual(len(self.all_names) - 1,
1884
1950
    def test_filter_suite_by_condition(self):
1885
1951
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1886
1952
            'test_filter_suite_by_condition')
1887
 
        filtered_suite = filter_suite_by_condition(self.suite,
 
1953
        filtered_suite = tests.filter_suite_by_condition(self.suite,
1888
1954
            lambda x:x.id() == test_name)
1889
1955
        self.assertEqual([test_name], _test_ids(filtered_suite))
1890
1956
 
1891
1957
    def test_filter_suite_by_re(self):
1892
 
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
1958
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
1959
                                                  'test_filter_suite_by_r')
1893
1960
        filtered_names = _test_ids(filtered_suite)
1894
1961
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1895
1962
            'TestSelftestFiltering.test_filter_suite_by_re'])
1923
1990
 
1924
1991
    def test_preserve_input(self):
1925
1992
        # NB: Surely this is something in the stdlib to do this?
1926
 
        self.assertTrue(self.suite is preserve_input(self.suite))
1927
 
        self.assertTrue("@#$" is preserve_input("@#$"))
 
1993
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
1994
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
1928
1995
 
1929
1996
    def test_randomize_suite(self):
1930
 
        randomized_suite = randomize_suite(self.suite)
 
1997
        randomized_suite = tests.randomize_suite(self.suite)
1931
1998
        # randomizing should not add or remove test names.
1932
1999
        self.assertEqual(set(_test_ids(self.suite)),
1933
2000
                         set(_test_ids(randomized_suite)))
1943
2010
 
1944
2011
    def test_split_suit_by_condition(self):
1945
2012
        self.all_names = _test_ids(self.suite)
1946
 
        condition = condition_id_re('test_filter_suite_by_r')
1947
 
        split_suite = split_suite_by_condition(self.suite, condition)
 
2013
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2014
        split_suite = tests.split_suite_by_condition(self.suite, condition)
1948
2015
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1949
2016
            'test_filter_suite_by_re')
1950
2017
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1955
2022
 
1956
2023
    def test_split_suit_by_re(self):
1957
2024
        self.all_names = _test_ids(self.suite)
1958
 
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
2025
        split_suite = tests.split_suite_by_re(self.suite,
 
2026
                                              'test_filter_suite_by_r')
1959
2027
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1960
2028
            'test_filter_suite_by_re')
1961
2029
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1965
2033
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1966
2034
 
1967
2035
 
1968
 
class TestCheckInventoryShape(TestCaseWithTransport):
 
2036
class TestCheckInventoryShape(tests.TestCaseWithTransport):
1969
2037
 
1970
2038
    def test_check_inventory_shape(self):
1971
2039
        files = ['a', 'b/', 'b/c']
1979
2047
            tree.unlock()
1980
2048
 
1981
2049
 
1982
 
class TestBlackboxSupport(TestCase):
 
2050
class TestBlackboxSupport(tests.TestCase):
1983
2051
    """Tests for testsuite blackbox features."""
1984
2052
 
1985
2053
    def test_run_bzr_failure_not_caught(self):
2006
2074
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2007
2075
 
2008
2076
 
2009
 
class TestTestLoader(TestCase):
 
2077
class TestTestLoader(tests.TestCase):
2010
2078
    """Tests for the test loader."""
2011
2079
 
2012
2080
    def _get_loader_and_module(self):
2013
2081
        """Gets a TestLoader and a module with one test in it."""
2014
2082
        loader = TestUtil.TestLoader()
2015
2083
        module = {}
2016
 
        class Stub(TestCase):
 
2084
        class Stub(tests.TestCase):
2017
2085
            def test_foo(self):
2018
2086
                pass
2019
2087
        class MyModule(object):
2032
2100
        # load_tests do not need that :)
2033
2101
        def load_tests(self, standard_tests, module, loader):
2034
2102
            result = loader.suiteClass()
2035
 
            for test in iter_suite_tests(standard_tests):
 
2103
            for test in tests.iter_suite_tests(standard_tests):
2036
2104
                result.addTests([test, test])
2037
2105
            return result
2038
2106
        # add a load_tests() method which multiplies the tests from the module.
2057
2125
 
2058
2126
    def _create_suite(self, test_id_list):
2059
2127
 
2060
 
        class Stub(TestCase):
 
2128
        class Stub(tests.TestCase):
2061
2129
            def test_foo(self):
2062
2130
                pass
2063
2131
 
2073
2141
 
2074
2142
    def _test_ids(self, test_suite):
2075
2143
        """Get the ids for the tests in a test suite."""
2076
 
        return [t.id() for t in iter_suite_tests(test_suite)]
 
2144
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
2077
2145
 
2078
2146
    def test_empty_list(self):
2079
2147
        id_list = self._create_id_list([])
2105
2173
        self.assertTrue(id_list.refers_to('mod.class'))
2106
2174
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2107
2175
 
2108
 
    def test_test_suite(self):
2109
 
        # This test is slow, so we do a single test with one test in each
2110
 
        # category
2111
 
        test_list = [
2112
 
            # testmod_names
2113
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2114
 
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
2115
 
            # transport implementations
2116
 
            'bzrlib.tests.test_transport_implementations.TransportTests'
2117
 
            '.test_abspath(LocalURLServer)',
2118
 
            # modules_to_doctest
2119
 
            'bzrlib.timestamp.format_highres_date',
2120
 
            # plugins can't be tested that way since selftest may be run with
2121
 
            # --no-plugins
2122
 
            ]
2123
 
        suite = tests.test_suite(test_list)
2124
 
        self.assertEquals(test_list, _test_ids(suite))
2125
 
 
2126
2176
    def test_test_suite_matches_id_list_with_unknown(self):
2127
2177
        loader = TestUtil.TestLoader()
2128
2178
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2136
2186
        loader = TestUtil.TestLoader()
2137
2187
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2138
2188
        dupes = loader.suiteClass()
2139
 
        for test in iter_suite_tests(suite):
 
2189
        for test in tests.iter_suite_tests(suite):
2140
2190
            dupes.addTest(test)
2141
2191
            dupes.addTest(test) # Add it again
2142
2192
 
2148
2198
                          duplicates)
2149
2199
 
2150
2200
 
 
2201
class TestTestSuite(tests.TestCase):
 
2202
 
 
2203
    def test_test_suite(self):
 
2204
        # This test is slow, so we do a single test with one test in each
 
2205
        # category
 
2206
        test_list = [
 
2207
            # testmod_names
 
2208
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2209
            ('bzrlib.tests.per_transport.TransportTests'
 
2210
             '.test_abspath(LocalURLServer)'),
 
2211
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2212
            # modules_to_doctest
 
2213
            'bzrlib.timestamp.format_highres_date',
 
2214
            # plugins can't be tested that way since selftest may be run with
 
2215
            # --no-plugins
 
2216
            ]
 
2217
        suite = tests.test_suite(test_list)
 
2218
        self.assertEquals(test_list, _test_ids(suite))
 
2219
 
 
2220
    def test_test_suite_list_and_start(self):
 
2221
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
2222
        suite = tests.test_suite(test_list,
 
2223
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
2224
        # test_test_suite_list_and_start is not included 
 
2225
        self.assertEquals(test_list, _test_ids(suite))
 
2226
 
 
2227
 
2151
2228
class TestLoadTestIdList(tests.TestCaseInTempDir):
2152
2229
 
2153
2230
    def _create_test_list_file(self, file_name, content):
2276
2353
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2277
2354
 
2278
2355
 
2279
 
class TestRunSuite(TestCase):
 
2356
class TestRunSuite(tests.TestCase):
2280
2357
 
2281
2358
    def test_runner_class(self):
2282
2359
        """run_suite accepts and uses a runner_class keyword argument."""
2283
 
        class Stub(TestCase):
 
2360
        class Stub(tests.TestCase):
2284
2361
            def test_foo(self):
2285
2362
                pass
2286
2363
        suite = Stub("test_foo")
2287
2364
        calls = []
2288
 
        class MyRunner(TextTestRunner):
 
2365
        class MyRunner(tests.TextTestRunner):
2289
2366
            def run(self, test):
2290
2367
                calls.append(test)
2291
 
                return ExtendedTestResult(self.stream, self.descriptions,
2292
 
                    self.verbosity)
2293
 
        run_suite(suite, runner_class=MyRunner)
 
2368
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
2369
                                                self.verbosity)
 
2370
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2294
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)