~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

NEWS section template into a separate file

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 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
 
21
import signal
22
22
import sys
23
23
import time
24
24
import unittest
26
26
 
27
27
import bzrlib
28
28
from bzrlib import (
 
29
    branchbuilder,
29
30
    bzrdir,
 
31
    debug,
30
32
    errors,
 
33
    lockdir,
31
34
    memorytree,
32
35
    osutils,
 
36
    progress,
 
37
    remote,
33
38
    repository,
34
39
    symbol_versioning,
35
40
    tests,
36
 
    )
37
 
from bzrlib.progress import _BaseProgressBar
38
 
from bzrlib.repofmt import weaverepo
 
41
    workingtree,
 
42
    )
 
43
from bzrlib.repofmt import (
 
44
    groupcompress_repo,
 
45
    pack_repo,
 
46
    weaverepo,
 
47
    )
39
48
from bzrlib.symbol_versioning import (
40
 
    one_zero,
41
 
    zero_eleven,
42
 
    zero_ten,
 
49
    deprecated_function,
 
50
    deprecated_in,
 
51
    deprecated_method,
43
52
    )
44
53
from bzrlib.tests import (
45
 
                          ChrootedTestCase,
46
 
                          ExtendedTestResult,
47
 
                          Feature,
48
 
                          KnownFailure,
49
 
                          TestCase,
50
 
                          TestCaseInTempDir,
51
 
                          TestCaseWithMemoryTransport,
52
 
                          TestCaseWithTransport,
53
 
                          TestNotApplicable,
54
 
                          TestSkipped,
55
 
                          TestSuite,
56
 
                          TestUtil,
57
 
                          TextTestRunner,
58
 
                          UnavailableFeature,
59
 
                          condition_id_re,
60
 
                          condition_isinstance,
61
 
                          exclude_tests_by_condition,
62
 
                          exclude_tests_by_re,
63
 
                          filter_suite_by_condition,
64
 
                          filter_suite_by_re,
65
 
                          iter_suite_tests,
66
 
                          preserve_input,
67
 
                          randomize_suite,
68
 
                          split_suite_by_condition,
69
 
                          split_suite_by_re,
70
 
                          test_lsprof,
71
 
                          test_suite,
72
 
                          )
73
 
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
74
 
from bzrlib.tests.TestUtil import _load_module_by_name
 
54
    SubUnitFeature,
 
55
    test_lsprof,
 
56
    test_sftp_transport,
 
57
    TestUtil,
 
58
    )
75
59
from bzrlib.trace import note
76
60
from bzrlib.transport.memory import MemoryServer, MemoryTransport
77
61
from bzrlib.version import _get_bzr_source_tree
79
63
 
80
64
def _test_ids(test_suite):
81
65
    """Get the ids for the tests in a test suite."""
82
 
    return [t.id() for t in iter_suite_tests(test_suite)]
83
 
 
84
 
 
85
 
class SelftestTests(TestCase):
 
66
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
67
 
 
68
 
 
69
class SelftestTests(tests.TestCase):
86
70
 
87
71
    def test_import_tests(self):
88
 
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
72
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
89
73
        self.assertEqual(mod.SelftestTests, SelftestTests)
90
74
 
91
75
    def test_import_test_failure(self):
92
76
        self.assertRaises(ImportError,
93
 
                          _load_module_by_name,
 
77
                          TestUtil._load_module_by_name,
94
78
                          'bzrlib.no-name-yet')
95
79
 
96
 
class MetaTestLog(TestCase):
 
80
class MetaTestLog(tests.TestCase):
97
81
 
98
82
    def test_logging(self):
99
83
        """Test logs are captured when a test fails."""
103
87
                              'a test message\n')
104
88
 
105
89
 
106
 
class TestUnicodeFilename(TestCase):
 
90
class TestUnicodeFilename(tests.TestCase):
107
91
 
108
92
    def test_probe_passes(self):
109
93
        """UnicodeFilename._probe passes."""
112
96
        tests.UnicodeFilename._probe()
113
97
 
114
98
 
115
 
class TestTreeShape(TestCaseInTempDir):
 
99
class TestTreeShape(tests.TestCaseInTempDir):
116
100
 
117
101
    def test_unicode_paths(self):
118
102
        self.requireFeature(tests.UnicodeFilename)
122
106
        self.failUnlessExists(filename)
123
107
 
124
108
 
125
 
class TestTransportProviderAdapter(TestCase):
 
109
class TestTransportScenarios(tests.TestCase):
126
110
    """A group of tests that test the transport implementation adaption core.
127
111
 
128
 
    This is a meta test that the tests are applied to all available 
 
112
    This is a meta test that the tests are applied to all available
129
113
    transports.
130
114
 
131
 
    This will be generalised in the future which is why it is in this 
 
115
    This will be generalised in the future which is why it is in this
132
116
    test file even though it is specific to transport tests at the moment.
133
117
    """
134
118
 
135
119
    def test_get_transport_permutations(self):
136
120
        # this checks that get_test_permutations defined by the module is
137
 
        # called by the adapter get_transport_test_permutations method.
 
121
        # called by the get_transport_test_permutations function.
138
122
        class MockModule(object):
139
123
            def get_test_permutations(self):
140
124
                return sample_permutation
141
125
        sample_permutation = [(1,2), (3,4)]
142
 
        from bzrlib.tests.test_transport_implementations \
143
 
            import TransportTestProviderAdapter
144
 
        adapter = TransportTestProviderAdapter()
 
126
        from bzrlib.tests.per_transport import get_transport_test_permutations
145
127
        self.assertEqual(sample_permutation,
146
 
                         adapter.get_transport_test_permutations(MockModule()))
 
128
                         get_transport_test_permutations(MockModule()))
147
129
 
148
 
    def test_adapter_checks_all_modules(self):
149
 
        # this checks that the adapter returns as many permutations as there
150
 
        # are in all the registered transport modules - we assume if this
151
 
        # matches its probably doing the right thing especially in combination
152
 
        # with the tests for setting the right classes below.
153
 
        from bzrlib.tests.test_transport_implementations \
154
 
            import TransportTestProviderAdapter
 
130
    def test_scenarios_include_all_modules(self):
 
131
        # this checks that the scenario generator returns as many permutations
 
132
        # as there are in all the registered transport modules - we assume if
 
133
        # this matches its probably doing the right thing especially in
 
134
        # combination with the tests for setting the right classes below.
 
135
        from bzrlib.tests.per_transport import transport_test_permutations
155
136
        from bzrlib.transport import _get_transport_modules
156
137
        modules = _get_transport_modules()
157
138
        permutation_count = 0
158
139
        for module in modules:
159
140
            try:
160
 
                permutation_count += len(reduce(getattr, 
 
141
                permutation_count += len(reduce(getattr,
161
142
                    (module + ".get_test_permutations").split('.')[1:],
162
143
                     __import__(module))())
163
144
            except errors.DependencyNotPresent:
164
145
                pass
165
 
        input_test = TestTransportProviderAdapter(
166
 
            "test_adapter_sets_transport_class")
167
 
        adapter = TransportTestProviderAdapter()
168
 
        self.assertEqual(permutation_count,
169
 
                         len(list(iter(adapter.adapt(input_test)))))
 
146
        scenarios = transport_test_permutations()
 
147
        self.assertEqual(permutation_count, len(scenarios))
170
148
 
171
 
    def test_adapter_sets_transport_class(self):
172
 
        # Check that the test adapter inserts a transport and server into the
173
 
        # generated test.
174
 
        #
 
149
    def test_scenarios_include_transport_class(self):
175
150
        # This test used to know about all the possible transports and the
176
151
        # order they were returned but that seems overly brittle (mbp
177
152
        # 20060307)
178
 
        from bzrlib.tests.test_transport_implementations \
179
 
            import TransportTestProviderAdapter
180
 
        scenarios = TransportTestProviderAdapter().scenarios
 
153
        from bzrlib.tests.per_transport import transport_test_permutations
 
154
        scenarios = transport_test_permutations()
181
155
        # there are at least that many builtin transports
182
156
        self.assertTrue(len(scenarios) > 6)
183
157
        one_scenario = scenarios[0]
188
162
                                   bzrlib.transport.Server))
189
163
 
190
164
 
191
 
class TestBranchProviderAdapter(TestCase):
192
 
    """A group of tests that test the branch implementation test adapter."""
 
165
class TestBranchScenarios(tests.TestCase):
193
166
 
194
 
    def test_constructor(self):
 
167
    def test_scenarios(self):
195
168
        # check that constructor parameters are passed through to the adapted
196
169
        # test.
197
 
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
 
170
        from bzrlib.tests.per_branch import make_scenarios
198
171
        server1 = "a"
199
172
        server2 = "b"
200
173
        formats = [("c", "C"), ("d", "D")]
201
 
        adapter = BranchTestProviderAdapter(server1, server2, formats)
202
 
        self.assertEqual(2, len(adapter.scenarios))
 
174
        scenarios = make_scenarios(server1, server2, formats)
 
175
        self.assertEqual(2, len(scenarios))
203
176
        self.assertEqual([
204
177
            ('str',
205
178
             {'branch_format': 'c',
211
184
              'bzrdir_format': 'D',
212
185
              'transport_readonly_server': 'b',
213
186
              'transport_server': 'a'})],
214
 
            adapter.scenarios)
215
 
 
216
 
 
217
 
class TestBzrDirProviderAdapter(TestCase):
218
 
    """A group of tests that test the bzr dir implementation test adapter."""
219
 
 
220
 
    def test_adapted_tests(self):
 
187
            scenarios)
 
188
 
 
189
 
 
190
class TestBzrDirScenarios(tests.TestCase):
 
191
 
 
192
    def test_scenarios(self):
221
193
        # check that constructor parameters are passed through to the adapted
222
194
        # test.
223
 
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
 
195
        from bzrlib.tests.per_bzrdir import make_scenarios
224
196
        vfs_factory = "v"
225
197
        server1 = "a"
226
198
        server2 = "b"
227
199
        formats = ["c", "d"]
228
 
        adapter = BzrDirTestProviderAdapter(vfs_factory,
229
 
            server1, server2, formats)
 
200
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
230
201
        self.assertEqual([
231
202
            ('str',
232
203
             {'bzrdir_format': 'c',
238
209
              'transport_readonly_server': 'b',
239
210
              'transport_server': 'a',
240
211
              'vfs_transport_factory': 'v'})],
241
 
            adapter.scenarios)
242
 
 
243
 
 
244
 
class TestRepositoryParameterisation(TestCase):
245
 
    """A group of tests that test the repository implementation test adapter."""
246
 
 
247
 
    def test_setting_vfs_transport(self):
248
 
        """The vfs_transport_factory can be set optionally."""
249
 
        from bzrlib.tests.repository_implementations import formats_to_scenarios
250
 
        scenarios = formats_to_scenarios(
251
 
            [("(one)", "a", "b"), ("(two)", "c", "d")],
252
 
            None,
253
 
            None,
254
 
            vfs_transport_factory="vfs")
255
 
        self.assertEqual([
256
 
            ('str(one)',
257
 
             {'bzrdir_format': 'b',
258
 
              'repository_format': 'a',
259
 
              'transport_readonly_server': None,
260
 
              'transport_server': None,
261
 
              'vfs_transport_factory': 'vfs'}),
262
 
            ('str(two)',
263
 
             {'bzrdir_format': 'd',
264
 
              'repository_format': 'c',
265
 
              'transport_readonly_server': None,
266
 
              'transport_server': None,
267
 
              'vfs_transport_factory': 'vfs'})],
268
212
            scenarios)
269
213
 
 
214
 
 
215
class TestRepositoryScenarios(tests.TestCase):
 
216
 
270
217
    def test_formats_to_scenarios(self):
271
 
        """The adapter can generate all the scenarios needed."""
272
 
        from bzrlib.tests.repository_implementations import formats_to_scenarios
273
 
        formats = [("(c)", "c", "C"), ("(d)", 1, "D")]
 
218
        from bzrlib.tests.per_repository import formats_to_scenarios
 
219
        formats = [("(c)", remote.RemoteRepositoryFormat()),
 
220
                   ("(d)", repository.format_registry.get(
 
221
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
274
222
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
275
223
            None)
276
224
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
277
225
            vfs_transport_factory="vfs")
278
 
        # no_vfs generate scenarios without vfs_transport_factor
279
 
        self.assertEqual([
280
 
            ('str(c)',
281
 
             {'bzrdir_format': 'C',
282
 
              'repository_format': 'c',
 
226
        # no_vfs generate scenarios without vfs_transport_factory
 
227
        expected = [
 
228
            ('RemoteRepositoryFormat(c)',
 
229
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
230
              'repository_format': remote.RemoteRepositoryFormat(),
283
231
              'transport_readonly_server': 'readonly',
284
232
              'transport_server': 'server'}),
285
 
            ('int(d)',
286
 
             {'bzrdir_format': 'D',
287
 
              'repository_format': 1,
 
233
            ('RepositoryFormat2a(d)',
 
234
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
235
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
288
236
              'transport_readonly_server': 'readonly',
289
 
              'transport_server': 'server'})],
290
 
            no_vfs_scenarios)
 
237
              'transport_server': 'server'})]
 
238
        self.assertEqual(expected, no_vfs_scenarios)
291
239
        self.assertEqual([
292
 
            ('str(c)',
293
 
             {'bzrdir_format': 'C',
294
 
              'repository_format': 'c',
 
240
            ('RemoteRepositoryFormat(c)',
 
241
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
242
              'repository_format': remote.RemoteRepositoryFormat(),
295
243
              'transport_readonly_server': 'readonly',
296
244
              'transport_server': 'server',
297
245
              'vfs_transport_factory': 'vfs'}),
298
 
            ('int(d)',
299
 
             {'bzrdir_format': 'D',
300
 
              'repository_format': 1,
 
246
            ('RepositoryFormat2a(d)',
 
247
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
248
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
301
249
              'transport_readonly_server': 'readonly',
302
250
              'transport_server': 'server',
303
251
              'vfs_transport_factory': 'vfs'})],
304
252
            vfs_scenarios)
305
253
 
306
254
 
307
 
class TestTestScenarioApplier(TestCase):
 
255
class TestTestScenarioApplication(tests.TestCase):
308
256
    """Tests for the test adaption facilities."""
309
257
 
310
 
    def test_adapt_applies_scenarios(self):
311
 
        from bzrlib.tests.repository_implementations import TestScenarioApplier
312
 
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
313
 
        adapter = TestScenarioApplier()
314
 
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
315
 
        calls = []
316
 
        def capture_call(test, scenario):
317
 
            calls.append((test, scenario))
318
 
            return test
319
 
        adapter.adapt_test_to_scenario = capture_call
320
 
        adapter.adapt(input_test)
321
 
        self.assertEqual([(input_test, ("1", "dict")),
322
 
            (input_test, ("2", "settings"))], calls)
323
 
 
324
 
    def test_adapt_test_to_scenario(self):
325
 
        from bzrlib.tests.repository_implementations import TestScenarioApplier
326
 
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
327
 
        adapter = TestScenarioApplier()
 
258
    def test_apply_scenario(self):
 
259
        from bzrlib.tests import apply_scenario
 
260
        input_test = TestTestScenarioApplication("test_apply_scenario")
328
261
        # setup two adapted tests
329
 
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
 
262
        adapted_test1 = apply_scenario(input_test,
330
263
            ("new id",
331
264
            {"bzrdir_format":"bzr_format",
332
265
             "repository_format":"repo_fmt",
333
266
             "transport_server":"transport_server",
334
267
             "transport_readonly_server":"readonly-server"}))
335
 
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
 
268
        adapted_test2 = apply_scenario(input_test,
336
269
            ("new id 2", {"bzrdir_format":None}))
337
270
        # input_test should have been altered.
338
271
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
339
 
        # the new tests are mutually incompatible, ensuring it has 
 
272
        # the new tests are mutually incompatible, ensuring it has
340
273
        # made new ones, and unspecified elements in the scenario
341
274
        # should not have been altered.
342
275
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
345
278
        self.assertEqual("readonly-server",
346
279
            adapted_test1.transport_readonly_server)
347
280
        self.assertEqual(
348
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
349
 
            "test_adapt_test_to_scenario(new id)",
 
281
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
282
            "test_apply_scenario(new id)",
350
283
            adapted_test1.id())
351
284
        self.assertEqual(None, adapted_test2.bzrdir_format)
352
285
        self.assertEqual(
353
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
354
 
            "test_adapt_test_to_scenario(new id 2)",
 
286
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
287
            "test_apply_scenario(new id 2)",
355
288
            adapted_test2.id())
356
289
 
357
290
 
358
 
class TestInterRepositoryProviderAdapter(TestCase):
359
 
    """A group of tests that test the InterRepository test adapter."""
 
291
class TestInterRepositoryScenarios(tests.TestCase):
360
292
 
361
 
    def test_adapted_tests(self):
 
293
    def test_scenarios(self):
362
294
        # check that constructor parameters are passed through to the adapted
363
295
        # test.
364
 
        from bzrlib.tests.interrepository_implementations import \
365
 
            InterRepositoryTestProviderAdapter
 
296
        from bzrlib.tests.per_interrepository import make_scenarios
366
297
        server1 = "a"
367
298
        server2 = "b"
368
 
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
369
 
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
 
299
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
 
300
        scenarios = make_scenarios(server1, server2, formats)
370
301
        self.assertEqual([
371
 
            ('str,str,str',
372
 
             {'interrepo_class': str,
373
 
              'repository_format': 'C1',
 
302
            ('C0,str,str',
 
303
             {'repository_format': 'C1',
374
304
              'repository_format_to': 'C2',
375
305
              'transport_readonly_server': 'b',
376
306
              'transport_server': 'a'}),
377
 
            ('int,str,str',
378
 
             {'interrepo_class': int,
379
 
              'repository_format': 'D1',
 
307
            ('D0,str,str',
 
308
             {'repository_format': 'D1',
380
309
              'repository_format_to': 'D2',
381
310
              'transport_readonly_server': 'b',
382
311
              'transport_server': 'a'})],
383
 
            adapter.formats_to_scenarios(formats))
384
 
 
385
 
 
386
 
class TestWorkingTreeProviderAdapter(TestCase):
387
 
    """A group of tests that test the workingtree implementation test adapter."""
 
312
            scenarios)
 
313
 
 
314
 
 
315
class TestWorkingTreeScenarios(tests.TestCase):
388
316
 
389
317
    def test_scenarios(self):
390
318
        # check that constructor parameters are passed through to the adapted
391
319
        # test.
392
 
        from bzrlib.tests.workingtree_implementations \
393
 
            import WorkingTreeTestProviderAdapter
 
320
        from bzrlib.tests.per_workingtree import make_scenarios
394
321
        server1 = "a"
395
322
        server2 = "b"
396
 
        formats = [("c", "C"), ("d", "D")]
397
 
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
323
        formats = [workingtree.WorkingTreeFormat2(),
 
324
                   workingtree.WorkingTreeFormat3(),]
 
325
        scenarios = make_scenarios(server1, server2, formats)
398
326
        self.assertEqual([
399
 
            ('str',
400
 
             {'bzrdir_format': 'C',
401
 
              'transport_readonly_server': 'b',
402
 
              'transport_server': 'a',
403
 
              'workingtree_format': 'c'}),
404
 
            ('str',
405
 
             {'bzrdir_format': 'D',
406
 
              'transport_readonly_server': 'b',
407
 
              'transport_server': 'a',
408
 
              'workingtree_format': 'd'})],
409
 
            adapter.scenarios)
410
 
 
411
 
 
412
 
class TestTreeProviderAdapter(TestCase):
413
 
    """Test the setup of tree_implementation tests."""
414
 
 
415
 
    def test_adapted_tests(self):
416
 
        # the tree implementation adapter is meant to setup one instance for
417
 
        # each working tree format, and one additional instance that will
418
 
        # use the default wt format, but create a revision tree for the tests.
419
 
        # this means that the wt ones should have the workingtree_to_test_tree
420
 
        # attribute set to 'return_parameter' and the revision one set to
421
 
        # revision_tree_from_workingtree.
422
 
 
423
 
        from bzrlib.tests.tree_implementations import (
424
 
            TreeTestProviderAdapter,
 
327
            ('WorkingTreeFormat2',
 
328
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
329
              'transport_readonly_server': 'b',
 
330
              'transport_server': 'a',
 
331
              'workingtree_format': formats[0]}),
 
332
            ('WorkingTreeFormat3',
 
333
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
334
              'transport_readonly_server': 'b',
 
335
              'transport_server': 'a',
 
336
              'workingtree_format': formats[1]})],
 
337
            scenarios)
 
338
 
 
339
 
 
340
class TestTreeScenarios(tests.TestCase):
 
341
 
 
342
    def test_scenarios(self):
 
343
        # the tree implementation scenario generator is meant to setup one
 
344
        # instance for each working tree format, and one additional instance
 
345
        # that will use the default wt format, but create a revision tree for
 
346
        # the tests.  this means that the wt ones should have the
 
347
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
 
348
        # revision one set to revision_tree_from_workingtree.
 
349
 
 
350
        from bzrlib.tests.per_tree import (
 
351
            _dirstate_tree_from_workingtree,
 
352
            make_scenarios,
 
353
            preview_tree_pre,
 
354
            preview_tree_post,
425
355
            return_parameter,
426
356
            revision_tree_from_workingtree
427
357
            )
428
 
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
429
 
        input_test = TestTreeProviderAdapter(
430
 
            "test_adapted_tests")
431
358
        server1 = "a"
432
359
        server2 = "b"
433
 
        formats = [("c", "C"), ("d", "D")]
434
 
        adapter = TreeTestProviderAdapter(server1, server2, formats)
435
 
        suite = adapter.adapt(input_test)
436
 
        tests = list(iter(suite))
437
 
        # XXX We should not have tests fail as we add more scenarios
438
 
        # abentley 20080412
439
 
        self.assertEqual(5, len(tests))
440
 
        # this must match the default format setp up in
441
 
        # TreeTestProviderAdapter.adapt
442
 
        default_format = WorkingTreeFormat3
443
 
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
444
 
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
445
 
        self.assertEqual(tests[0].transport_server, server1)
446
 
        self.assertEqual(tests[0].transport_readonly_server, server2)
447
 
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
448
 
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
449
 
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
450
 
        self.assertEqual(tests[1].transport_server, server1)
451
 
        self.assertEqual(tests[1].transport_readonly_server, server2)
452
 
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
453
 
        self.assertIsInstance(tests[2].workingtree_format, default_format)
454
 
        #self.assertEqual(tests[2].bzrdir_format,
455
 
        #                 default_format._matchingbzrdir)
456
 
        self.assertEqual(tests[2].transport_server, server1)
457
 
        self.assertEqual(tests[2].transport_readonly_server, server2)
458
 
        self.assertEqual(tests[2]._workingtree_to_test_tree,
459
 
            revision_tree_from_workingtree)
460
 
 
461
 
 
462
 
class TestInterTreeProviderAdapter(TestCase):
 
360
        formats = [workingtree.WorkingTreeFormat2(),
 
361
                   workingtree.WorkingTreeFormat3(),]
 
362
        scenarios = make_scenarios(server1, server2, formats)
 
363
        self.assertEqual(7, len(scenarios))
 
364
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
365
        wt4_format = workingtree.WorkingTreeFormat4()
 
366
        wt5_format = workingtree.WorkingTreeFormat5()
 
367
        expected_scenarios = [
 
368
            ('WorkingTreeFormat2',
 
369
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
370
              'transport_readonly_server': 'b',
 
371
              'transport_server': 'a',
 
372
              'workingtree_format': formats[0],
 
373
              '_workingtree_to_test_tree': return_parameter,
 
374
              }),
 
375
            ('WorkingTreeFormat3',
 
376
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
377
              'transport_readonly_server': 'b',
 
378
              'transport_server': 'a',
 
379
              'workingtree_format': formats[1],
 
380
              '_workingtree_to_test_tree': return_parameter,
 
381
             }),
 
382
            ('RevisionTree',
 
383
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
 
384
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
385
              'transport_readonly_server': 'b',
 
386
              'transport_server': 'a',
 
387
              'workingtree_format': default_wt_format,
 
388
             }),
 
389
            ('DirStateRevisionTree,WT4',
 
390
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
391
              'bzrdir_format': wt4_format._matchingbzrdir,
 
392
              'transport_readonly_server': 'b',
 
393
              'transport_server': 'a',
 
394
              'workingtree_format': wt4_format,
 
395
             }),
 
396
            ('DirStateRevisionTree,WT5',
 
397
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
398
              'bzrdir_format': wt5_format._matchingbzrdir,
 
399
              'transport_readonly_server': 'b',
 
400
              'transport_server': 'a',
 
401
              'workingtree_format': wt5_format,
 
402
             }),
 
403
            ('PreviewTree',
 
404
             {'_workingtree_to_test_tree': preview_tree_pre,
 
405
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
406
              'transport_readonly_server': 'b',
 
407
              'transport_server': 'a',
 
408
              'workingtree_format': default_wt_format}),
 
409
            ('PreviewTreePost',
 
410
             {'_workingtree_to_test_tree': preview_tree_post,
 
411
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
412
              'transport_readonly_server': 'b',
 
413
              'transport_server': 'a',
 
414
              'workingtree_format': default_wt_format}),
 
415
             ]
 
416
        self.assertEqual(expected_scenarios, scenarios)
 
417
 
 
418
 
 
419
class TestInterTreeScenarios(tests.TestCase):
463
420
    """A group of tests that test the InterTreeTestAdapter."""
464
421
 
465
 
    def test_adapted_tests(self):
 
422
    def test_scenarios(self):
466
423
        # check that constructor parameters are passed through to the adapted
467
424
        # test.
468
425
        # for InterTree tests we want the machinery to bring up two trees in
472
429
        # unlike the TestProviderAdapter we dont want to automatically add a
473
430
        # parameterized one for WorkingTree - the optimisers will tell us what
474
431
        # ones to add.
475
 
        from bzrlib.tests.tree_implementations import (
 
432
        from bzrlib.tests.per_tree import (
476
433
            return_parameter,
477
434
            revision_tree_from_workingtree
478
435
            )
479
 
        from bzrlib.tests.intertree_implementations import (
480
 
            InterTreeTestProviderAdapter,
 
436
        from bzrlib.tests.per_intertree import (
 
437
            make_scenarios,
481
438
            )
482
439
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
483
 
        input_test = TestInterTreeProviderAdapter(
484
 
            "test_adapted_tests")
 
440
        input_test = TestInterTreeScenarios(
 
441
            "test_scenarios")
485
442
        server1 = "a"
486
443
        server2 = "b"
487
444
        format1 = WorkingTreeFormat2()
488
445
        format2 = WorkingTreeFormat3()
489
 
        formats = [(str, format1, format2, "converter1"),
490
 
            (int, format2, format1, "converter2")]
491
 
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
492
 
        suite = adapter.adapt(input_test)
493
 
        tests = list(iter(suite))
494
 
        self.assertEqual(2, len(tests))
495
 
        self.assertEqual(tests[0].intertree_class, formats[0][0])
496
 
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
497
 
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
498
 
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
499
 
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
500
 
        self.assertEqual(tests[0].transport_server, server1)
501
 
        self.assertEqual(tests[0].transport_readonly_server, server2)
502
 
        self.assertEqual(tests[1].intertree_class, formats[1][0])
503
 
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
504
 
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
505
 
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
506
 
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
507
 
        self.assertEqual(tests[1].transport_server, server1)
508
 
        self.assertEqual(tests[1].transport_readonly_server, server2)
509
 
 
510
 
 
511
 
class TestTestCaseInTempDir(TestCaseInTempDir):
 
446
        formats = [("1", str, format1, format2, "converter1"),
 
447
            ("2", int, format2, format1, "converter2")]
 
448
        scenarios = make_scenarios(server1, server2, formats)
 
449
        self.assertEqual(2, len(scenarios))
 
450
        expected_scenarios = [
 
451
            ("1", {
 
452
                "bzrdir_format": format1._matchingbzrdir,
 
453
                "intertree_class": formats[0][1],
 
454
                "workingtree_format": formats[0][2],
 
455
                "workingtree_format_to": formats[0][3],
 
456
                "mutable_trees_to_test_trees": formats[0][4],
 
457
                "_workingtree_to_test_tree": return_parameter,
 
458
                "transport_server": server1,
 
459
                "transport_readonly_server": server2,
 
460
                }),
 
461
            ("2", {
 
462
                "bzrdir_format": format2._matchingbzrdir,
 
463
                "intertree_class": formats[1][1],
 
464
                "workingtree_format": formats[1][2],
 
465
                "workingtree_format_to": formats[1][3],
 
466
                "mutable_trees_to_test_trees": formats[1][4],
 
467
                "_workingtree_to_test_tree": return_parameter,
 
468
                "transport_server": server1,
 
469
                "transport_readonly_server": server2,
 
470
                }),
 
471
            ]
 
472
        self.assertEqual(scenarios, expected_scenarios)
 
473
 
 
474
 
 
475
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
512
476
 
513
477
    def test_home_is_not_working(self):
514
478
        self.assertNotEqual(self.test_dir, self.test_home_dir)
516
480
        self.assertIsSameRealPath(self.test_dir, cwd)
517
481
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
518
482
 
519
 
 
520
 
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
483
    def test_assertEqualStat_equal(self):
 
484
        from bzrlib.tests.test_dirstate import _FakeStat
 
485
        self.build_tree(["foo"])
 
486
        real = os.lstat("foo")
 
487
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
 
488
            real.st_dev, real.st_ino, real.st_mode)
 
489
        self.assertEqualStat(real, fake)
 
490
 
 
491
    def test_assertEqualStat_notequal(self):
 
492
        self.build_tree(["foo", "bar"])
 
493
        self.assertRaises(AssertionError, self.assertEqualStat,
 
494
            os.lstat("foo"), os.lstat("bar"))
 
495
 
 
496
 
 
497
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
521
498
 
522
499
    def test_home_is_non_existant_dir_under_root(self):
523
500
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
524
501
 
525
502
        This is because TestCaseWithMemoryTransport is for tests that do not
526
 
        need any disk resources: they should be hooked into bzrlib in such a 
527
 
        way that no global settings are being changed by the test (only a 
 
503
        need any disk resources: they should be hooked into bzrlib in such a
 
504
        way that no global settings are being changed by the test (only a
528
505
        few tests should need to do that), and having a missing dir as home is
529
506
        an effective way to ensure that this is the case.
530
507
        """
532
509
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
533
510
            self.test_home_dir)
534
511
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
535
 
        
 
512
 
536
513
    def test_cwd_is_TEST_ROOT(self):
537
514
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
538
515
        cwd = osutils.getcwd()
562
539
        self.assertEqual(format.repository_format.__class__,
563
540
            tree.branch.repository._format.__class__)
564
541
 
 
542
    def test_make_branch_builder(self):
 
543
        builder = self.make_branch_builder('dir')
 
544
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
 
545
        # Guard against regression into MemoryTransport leaking
 
546
        # files to disk instead of keeping them in memory.
 
547
        self.failIf(osutils.lexists('dir'))
 
548
 
 
549
    def test_make_branch_builder_with_format(self):
 
550
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
 
551
        # that the format objects are used.
 
552
        format = bzrdir.BzrDirMetaFormat1()
 
553
        repo_format = weaverepo.RepositoryFormat7()
 
554
        format.repository_format = repo_format
 
555
        builder = self.make_branch_builder('dir', format=format)
 
556
        the_branch = builder.get_branch()
 
557
        # Guard against regression into MemoryTransport leaking
 
558
        # files to disk instead of keeping them in memory.
 
559
        self.failIf(osutils.lexists('dir'))
 
560
        self.assertEqual(format.repository_format.__class__,
 
561
                         the_branch.repository._format.__class__)
 
562
        self.assertEqual(repo_format.get_format_string(),
 
563
                         self.get_transport().get_bytes(
 
564
                            'dir/.bzr/repository/format'))
 
565
 
 
566
    def test_make_branch_builder_with_format_name(self):
 
567
        builder = self.make_branch_builder('dir', format='knit')
 
568
        the_branch = builder.get_branch()
 
569
        # Guard against regression into MemoryTransport leaking
 
570
        # files to disk instead of keeping them in memory.
 
571
        self.failIf(osutils.lexists('dir'))
 
572
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
573
        self.assertEqual(dir_format.repository_format.__class__,
 
574
                         the_branch.repository._format.__class__)
 
575
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
576
                         self.get_transport().get_bytes(
 
577
                            'dir/.bzr/repository/format'))
 
578
 
565
579
    def test_safety_net(self):
566
580
        """No test should modify the safety .bzr directory.
567
581
 
575
589
        # But we have a safety net in place.
576
590
        self.assertRaises(AssertionError, self._check_safety_net)
577
591
 
578
 
 
579
 
class TestTestCaseWithTransport(TestCaseWithTransport):
 
592
    def test_dangling_locks_cause_failures(self):
 
593
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
 
594
            def test_function(self):
 
595
                t = self.get_transport('.')
 
596
                l = lockdir.LockDir(t, 'lock')
 
597
                l.create()
 
598
                l.attempt_lock()
 
599
        test = TestDanglingLock('test_function')
 
600
        result = test.run()
 
601
        if self._lock_check_thorough:
 
602
            self.assertEqual(1, len(result.errors))
 
603
        else:
 
604
            # When _lock_check_thorough is disabled, then we don't trigger a
 
605
            # failure
 
606
            self.assertEqual(0, len(result.errors))
 
607
 
 
608
 
 
609
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
580
610
    """Tests for the convenience functions TestCaseWithTransport introduces."""
581
611
 
582
612
    def test_get_readonly_url_none(self):
620
650
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
621
651
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
622
652
 
623
 
 
624
 
class TestTestCaseTransports(TestCaseWithTransport):
 
653
    def test_make_branch_builder(self):
 
654
        builder = self.make_branch_builder('dir')
 
655
        rev_id = builder.build_commit()
 
656
        self.failUnlessExists('dir')
 
657
        a_dir = bzrdir.BzrDir.open('dir')
 
658
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
 
659
        a_branch = a_dir.open_branch()
 
660
        builder_branch = builder.get_branch()
 
661
        self.assertEqual(a_branch.base, builder_branch.base)
 
662
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
 
663
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
 
664
 
 
665
 
 
666
class TestTestCaseTransports(tests.TestCaseWithTransport):
625
667
 
626
668
    def setUp(self):
627
669
        super(TestTestCaseTransports, self).setUp()
630
672
    def test_make_bzrdir_preserves_transport(self):
631
673
        t = self.get_transport()
632
674
        result_bzrdir = self.make_bzrdir('subdir')
633
 
        self.assertIsInstance(result_bzrdir.transport, 
 
675
        self.assertIsInstance(result_bzrdir.transport,
634
676
                              MemoryTransport)
635
677
        # should not be on disk, should only be in memory
636
678
        self.failIfExists('subdir')
637
679
 
638
680
 
639
 
class TestChrootedTest(ChrootedTestCase):
 
681
class TestChrootedTest(tests.ChrootedTestCase):
640
682
 
641
683
    def test_root_is_root(self):
642
684
        from bzrlib.transport import get_transport
645
687
        self.assertEqual(url, t.clone('..').base)
646
688
 
647
689
 
648
 
class MockProgress(_BaseProgressBar):
649
 
    """Progress-bar standin that records calls.
650
 
 
651
 
    Useful for testing pb using code.
652
 
    """
653
 
 
654
 
    def __init__(self):
655
 
        _BaseProgressBar.__init__(self)
656
 
        self.calls = []
657
 
 
658
 
    def tick(self):
659
 
        self.calls.append(('tick',))
660
 
 
661
 
    def update(self, msg=None, current=None, total=None):
662
 
        self.calls.append(('update', msg, current, total))
663
 
 
664
 
    def clear(self):
665
 
        self.calls.append(('clear',))
666
 
 
667
 
    def note(self, msg, *args):
668
 
        self.calls.append(('note', msg, args))
669
 
 
670
 
 
671
 
class TestTestResult(TestCase):
 
690
class TestTestResult(tests.TestCase):
672
691
 
673
692
    def check_timing(self, test_case, expected_re):
674
693
        result = bzrlib.tests.TextTestResult(self._log_file,
680
699
        self.assertContainsRe(timed_string, expected_re)
681
700
 
682
701
    def test_test_reporting(self):
683
 
        class ShortDelayTestCase(TestCase):
 
702
        class ShortDelayTestCase(tests.TestCase):
684
703
            def test_short_delay(self):
685
704
                time.sleep(0.003)
686
705
            def test_short_benchmark(self):
687
706
                self.time(time.sleep, 0.003)
688
707
        self.check_timing(ShortDelayTestCase('test_short_delay'),
689
708
                          r"^ +[0-9]+ms$")
690
 
        # if a benchmark time is given, we want a x of y style result.
 
709
        # if a benchmark time is given, we now show just that time followed by
 
710
        # a star
691
711
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
692
 
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
 
712
                          r"^ +[0-9]+ms\*$")
693
713
 
694
714
    def test_unittest_reporting_unittest_class(self):
695
715
        # getting the time from a non-bzrlib test works ok
698
718
                time.sleep(0.003)
699
719
        self.check_timing(ShortDelayTestCase('test_short_delay'),
700
720
                          r"^ +[0-9]+ms$")
701
 
        
 
721
 
702
722
    def test_assigned_benchmark_file_stores_date(self):
703
723
        output = StringIO()
704
724
        result = bzrlib.tests.TextTestResult(self._log_file,
731
751
        self.assertContainsRe(lines[1],
732
752
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
733
753
            "._time_hello_world_encoding")
734
 
 
 
754
 
735
755
    def _time_hello_world_encoding(self):
736
756
        """Profile two sleep calls
737
 
        
 
757
 
738
758
        This is used to exercise the test framework.
739
759
        """
740
760
        self.time(unicode, 'hello', errors='replace')
758
778
        # execute the test, which should succeed and record profiles
759
779
        example_test_case.run(result)
760
780
        # lsprofile_something()
761
 
        # if this worked we want 
 
781
        # if this worked we want
762
782
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
763
783
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
764
784
        # (the lsprof header)
765
785
        # ... an arbitrary number of lines
766
786
        # and the function call which is time.sleep.
767
 
        #           1        0            ???         ???       ???(sleep) 
 
787
        #           1        0            ???         ???       ???(sleep)
768
788
        # and then repeated but with 'world', rather than 'hello'.
769
789
        # this should appear in the output stream of our test result.
770
790
        output = result_stream.getvalue()
779
799
 
780
800
    def test_known_failure(self):
781
801
        """A KnownFailure being raised should trigger several result actions."""
782
 
        class InstrumentedTestResult(ExtendedTestResult):
783
 
 
 
802
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
803
            def done(self): pass
 
804
            def startTests(self): pass
784
805
            def report_test_start(self, test): pass
785
806
            def report_known_failure(self, test, err):
786
807
                self._call = test, err
787
808
        result = InstrumentedTestResult(None, None, None, None)
788
809
        def test_function():
789
 
            raise KnownFailure('failed!')
 
810
            raise tests.KnownFailure('failed!')
790
811
        test = unittest.FunctionTestCase(test_function)
791
812
        test.run(result)
792
813
        # it should invoke 'report_known_failure'.
793
814
        self.assertEqual(2, len(result._call))
794
815
        self.assertEqual(test, result._call[0])
795
 
        self.assertEqual(KnownFailure, result._call[1][0])
796
 
        self.assertIsInstance(result._call[1][1], KnownFailure)
 
816
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
817
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
797
818
        # we dont introspec the traceback, if the rest is ok, it would be
798
819
        # exceptional for it not to be.
799
820
        # it should update the known_failure_count on the object.
816
837
        # (class, exception object, traceback)
817
838
        # KnownFailures dont get their tracebacks shown though, so we
818
839
        # can skip that.
819
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
840
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
820
841
        result.report_known_failure(test, err)
821
842
        output = result_stream.getvalue()[prefix:]
822
843
        lines = output.splitlines()
824
845
        self.assertEqual(lines[1], '    foo')
825
846
        self.assertEqual(2, len(lines))
826
847
 
827
 
    def test_text_report_known_failure(self):
828
 
        # text test output formatting
829
 
        pb = MockProgress()
830
 
        result = bzrlib.tests.TextTestResult(
831
 
            None,
832
 
            descriptions=0,
833
 
            verbosity=1,
834
 
            pb=pb,
835
 
            )
836
 
        test = self.get_passing_test()
837
 
        # this seeds the state to handle reporting the test.
838
 
        result.startTest(test)
839
 
        # the err parameter has the shape:
840
 
        # (class, exception object, traceback)
841
 
        # KnownFailures dont get their tracebacks shown though, so we
842
 
        # can skip that.
843
 
        err = (KnownFailure, KnownFailure('foo'), None)
844
 
        result.report_known_failure(test, err)
845
 
        self.assertEqual(
846
 
            [
847
 
            ('update', '[1 in 0s] passing_test', None, None),
848
 
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
849
 
            ],
850
 
            pb.calls)
851
 
        # known_failures should be printed in the summary, so if we run a test
852
 
        # after there are some known failures, the update prefix should match
853
 
        # this.
854
 
        result.known_failure_count = 3
855
 
        test.run(result)
856
 
        self.assertEqual(
857
 
            [
858
 
            ('update', '[2 in 0s] passing_test', None, None),
859
 
            ],
860
 
            pb.calls[2:])
861
 
 
862
848
    def get_passing_test(self):
863
849
        """Return a test object that can't be run usefully."""
864
850
        def passing_test():
867
853
 
868
854
    def test_add_not_supported(self):
869
855
        """Test the behaviour of invoking addNotSupported."""
870
 
        class InstrumentedTestResult(ExtendedTestResult):
 
856
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
857
            def done(self): pass
 
858
            def startTests(self): pass
871
859
            def report_test_start(self, test): pass
872
860
            def report_unsupported(self, test, feature):
873
861
                self._call = test, feature
874
862
        result = InstrumentedTestResult(None, None, None, None)
875
863
        test = SampleTestCase('_test_pass')
876
 
        feature = Feature()
 
864
        feature = tests.Feature()
877
865
        result.startTest(test)
878
866
        result.addNotSupported(test, feature)
879
867
        # it should invoke 'report_unsupported'.
898
886
            verbosity=2,
899
887
            )
900
888
        test = self.get_passing_test()
901
 
        feature = Feature()
 
889
        feature = tests.Feature()
902
890
        result.startTest(test)
903
891
        prefix = len(result_stream.getvalue())
904
892
        result.report_unsupported(test, feature)
905
893
        output = result_stream.getvalue()[prefix:]
906
894
        lines = output.splitlines()
907
 
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
908
 
    
909
 
    def test_text_report_unsupported(self):
910
 
        # text test output formatting
911
 
        pb = MockProgress()
912
 
        result = bzrlib.tests.TextTestResult(
913
 
            None,
914
 
            descriptions=0,
915
 
            verbosity=1,
916
 
            pb=pb,
917
 
            )
918
 
        test = self.get_passing_test()
919
 
        feature = Feature()
920
 
        # this seeds the state to handle reporting the test.
921
 
        result.startTest(test)
922
 
        result.report_unsupported(test, feature)
923
 
        # no output on unsupported features
924
 
        self.assertEqual(
925
 
            [('update', '[1 in 0s] passing_test', None, None)
926
 
            ],
927
 
            pb.calls)
928
 
        # the number of missing features should be printed in the progress
929
 
        # summary, so check for that.
930
 
        result.unsupported = {'foo':0, 'bar':0}
931
 
        test.run(result)
932
 
        self.assertEqual(
933
 
            [
934
 
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
935
 
            ],
936
 
            pb.calls[1:])
937
 
    
 
895
        # XXX: This is a timing dependent test. I've had it fail because it
 
896
        #      took 6ms to evaluate... :(
 
897
        self.assertEqual(lines, ['NODEP        0ms',
 
898
                                 "    The feature 'Feature' is not available."])
 
899
 
938
900
    def test_unavailable_exception(self):
939
901
        """An UnavailableFeature being raised should invoke addNotSupported."""
940
 
        class InstrumentedTestResult(ExtendedTestResult):
941
 
 
 
902
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
903
            def done(self): pass
 
904
            def startTests(self): pass
942
905
            def report_test_start(self, test): pass
943
906
            def addNotSupported(self, test, feature):
944
907
                self._call = test, feature
945
908
        result = InstrumentedTestResult(None, None, None, None)
946
 
        feature = Feature()
 
909
        feature = tests.Feature()
947
910
        def test_function():
948
 
            raise UnavailableFeature(feature)
 
911
            raise tests.UnavailableFeature(feature)
949
912
        test = unittest.FunctionTestCase(test_function)
950
913
        test.run(result)
951
914
        # it should invoke 'addNotSupported'.
963
926
        result.addNotSupported(test, feature)
964
927
        self.assertFalse(result.wasStrictlySuccessful())
965
928
        self.assertEqual(None, result._extractBenchmarkTime(test))
966
 
 
 
929
 
967
930
    def test_strict_with_known_failure(self):
968
931
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
969
932
                                             verbosity=1)
970
933
        test = self.get_passing_test()
971
 
        err = (KnownFailure, KnownFailure('foo'), None)
 
934
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
972
935
        result._addKnownFailure(test, err)
973
936
        self.assertFalse(result.wasStrictlySuccessful())
974
937
        self.assertEqual(None, result._extractBenchmarkTime(test))
981
944
        self.assertTrue(result.wasStrictlySuccessful())
982
945
        self.assertEqual(None, result._extractBenchmarkTime(test))
983
946
 
984
 
 
985
 
class TestUnicodeFilenameFeature(TestCase):
 
947
    def test_startTests(self):
 
948
        """Starting the first test should trigger startTests."""
 
949
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
950
            calls = 0
 
951
            def startTests(self): self.calls += 1
 
952
            def report_test_start(self, test): pass
 
953
        result = InstrumentedTestResult(None, None, None, None)
 
954
        def test_function():
 
955
            pass
 
956
        test = unittest.FunctionTestCase(test_function)
 
957
        test.run(result)
 
958
        self.assertEquals(1, result.calls)
 
959
 
 
960
 
 
961
class TestUnicodeFilenameFeature(tests.TestCase):
986
962
 
987
963
    def test_probe_passes(self):
988
964
        """UnicodeFilenameFeature._probe passes."""
991
967
        tests.UnicodeFilenameFeature._probe()
992
968
 
993
969
 
994
 
class TestRunner(TestCase):
 
970
class TestRunner(tests.TestCase):
995
971
 
996
972
    def dummy_test(self):
997
973
        pass
1001
977
 
1002
978
        This current saves and restores:
1003
979
        TestCaseInTempDir.TEST_ROOT
1004
 
        
1005
 
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
1006
 
        without using this convenience method, because of our use of global state.
 
980
 
 
981
        There should be no tests in this file that use
 
982
        bzrlib.tests.TextTestRunner without using this convenience method,
 
983
        because of our use of global state.
1007
984
        """
1008
 
        old_root = TestCaseInTempDir.TEST_ROOT
 
985
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1009
986
        try:
1010
 
            TestCaseInTempDir.TEST_ROOT = None
 
987
            tests.TestCaseInTempDir.TEST_ROOT = None
1011
988
            return testrunner.run(test)
1012
989
        finally:
1013
 
            TestCaseInTempDir.TEST_ROOT = old_root
 
990
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1014
991
 
1015
992
    def test_known_failure_failed_run(self):
1016
993
        # run a test that generates a known failure which should be printed in
1017
994
        # the final output when real failures occur.
1018
995
        def known_failure_test():
1019
 
            raise KnownFailure('failed')
 
996
            raise tests.KnownFailure('failed')
1020
997
        test = unittest.TestSuite()
1021
998
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1022
999
        def failing_test():
1023
1000
            raise AssertionError('foo')
1024
1001
        test.addTest(unittest.FunctionTestCase(failing_test))
1025
1002
        stream = StringIO()
1026
 
        runner = TextTestRunner(stream=stream)
 
1003
        runner = tests.TextTestRunner(stream=stream)
1027
1004
        result = self.run_test_runner(runner, test)
1028
1005
        lines = stream.getvalue().splitlines()
1029
 
        self.assertEqual([
1030
 
            '',
1031
 
            '======================================================================',
1032
 
            'FAIL: unittest.FunctionTestCase (failing_test)',
1033
 
            '----------------------------------------------------------------------',
1034
 
            'Traceback (most recent call last):',
1035
 
            '    raise AssertionError(\'foo\')',
1036
 
            'AssertionError: foo',
1037
 
            '',
1038
 
            '----------------------------------------------------------------------',
1039
 
            '',
1040
 
            'FAILED (failures=1, known_failure_count=1)'],
1041
 
            lines[0:5] + lines[6:10] + lines[11:])
 
1006
        self.assertContainsRe(stream.getvalue(),
 
1007
            '(?sm)^testing.*$'
 
1008
            '.*'
 
1009
            '^======================================================================\n'
 
1010
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
 
1011
            '^----------------------------------------------------------------------\n'
 
1012
            'Traceback \\(most recent call last\\):\n'
 
1013
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
 
1014
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1015
            '.*'
 
1016
            '^----------------------------------------------------------------------\n'
 
1017
            '.*'
 
1018
            'FAILED \\(failures=1, known_failure_count=1\\)'
 
1019
            )
1042
1020
 
1043
1021
    def test_known_failure_ok_run(self):
1044
1022
        # run a test that generates a known failure which should be printed in the final output.
1045
1023
        def known_failure_test():
1046
 
            raise KnownFailure('failed')
 
1024
            raise tests.KnownFailure('failed')
1047
1025
        test = unittest.FunctionTestCase(known_failure_test)
1048
1026
        stream = StringIO()
1049
 
        runner = TextTestRunner(stream=stream)
 
1027
        runner = tests.TextTestRunner(stream=stream)
1050
1028
        result = self.run_test_runner(runner, test)
1051
1029
        self.assertContainsRe(stream.getvalue(),
1052
1030
            '\n'
1059
1037
        # run a test that is skipped, and check the suite as a whole still
1060
1038
        # succeeds.
1061
1039
        # skipping_test must be hidden in here so it's not run as a real test
1062
 
        def skipping_test():
1063
 
            raise TestSkipped('test intentionally skipped')
1064
 
 
1065
 
        runner = TextTestRunner(stream=self._log_file)
1066
 
        test = unittest.FunctionTestCase(skipping_test)
 
1040
        class SkippingTest(tests.TestCase):
 
1041
            def skipping_test(self):
 
1042
                raise tests.TestSkipped('test intentionally skipped')
 
1043
        runner = tests.TextTestRunner(stream=self._log_file)
 
1044
        test = SkippingTest("skipping_test")
1067
1045
        result = self.run_test_runner(runner, test)
1068
1046
        self.assertTrue(result.wasSuccessful())
1069
1047
 
1070
1048
    def test_skipped_from_setup(self):
1071
1049
        calls = []
1072
 
        class SkippedSetupTest(TestCase):
 
1050
        class SkippedSetupTest(tests.TestCase):
1073
1051
 
1074
1052
            def setUp(self):
1075
1053
                calls.append('setUp')
1076
1054
                self.addCleanup(self.cleanup)
1077
 
                raise TestSkipped('skipped setup')
 
1055
                raise tests.TestSkipped('skipped setup')
1078
1056
 
1079
1057
            def test_skip(self):
1080
1058
                self.fail('test reached')
1082
1060
            def cleanup(self):
1083
1061
                calls.append('cleanup')
1084
1062
 
1085
 
        runner = TextTestRunner(stream=self._log_file)
 
1063
        runner = tests.TextTestRunner(stream=self._log_file)
1086
1064
        test = SkippedSetupTest('test_skip')
1087
1065
        result = self.run_test_runner(runner, test)
1088
1066
        self.assertTrue(result.wasSuccessful())
1091
1069
 
1092
1070
    def test_skipped_from_test(self):
1093
1071
        calls = []
1094
 
        class SkippedTest(TestCase):
 
1072
        class SkippedTest(tests.TestCase):
1095
1073
 
1096
1074
            def setUp(self):
 
1075
                tests.TestCase.setUp(self)
1097
1076
                calls.append('setUp')
1098
1077
                self.addCleanup(self.cleanup)
1099
1078
 
1100
1079
            def test_skip(self):
1101
 
                raise TestSkipped('skipped test')
 
1080
                raise tests.TestSkipped('skipped test')
1102
1081
 
1103
1082
            def cleanup(self):
1104
1083
                calls.append('cleanup')
1105
1084
 
1106
 
        runner = TextTestRunner(stream=self._log_file)
 
1085
        runner = tests.TextTestRunner(stream=self._log_file)
1107
1086
        test = SkippedTest('test_skip')
1108
1087
        result = self.run_test_runner(runner, test)
1109
1088
        self.assertTrue(result.wasSuccessful())
1113
1092
    def test_not_applicable(self):
1114
1093
        # run a test that is skipped because it's not applicable
1115
1094
        def not_applicable_test():
1116
 
            from bzrlib.tests import TestNotApplicable
1117
 
            raise TestNotApplicable('this test never runs')
 
1095
            raise tests.TestNotApplicable('this test never runs')
1118
1096
        out = StringIO()
1119
 
        runner = TextTestRunner(stream=out, verbosity=2)
 
1097
        runner = tests.TextTestRunner(stream=out, verbosity=2)
1120
1098
        test = unittest.FunctionTestCase(not_applicable_test)
1121
1099
        result = self.run_test_runner(runner, test)
1122
1100
        self._log_file.write(out.getvalue())
1129
1107
 
1130
1108
    def test_not_applicable_demo(self):
1131
1109
        # just so you can see it in the test output
1132
 
        raise TestNotApplicable('this test is just a demonstation')
 
1110
        raise tests.TestNotApplicable('this test is just a demonstation')
1133
1111
 
1134
1112
    def test_unsupported_features_listed(self):
1135
1113
        """When unsupported features are encountered they are detailed."""
1136
 
        class Feature1(Feature):
 
1114
        class Feature1(tests.Feature):
1137
1115
            def _probe(self): return False
1138
 
        class Feature2(Feature):
 
1116
        class Feature2(tests.Feature):
1139
1117
            def _probe(self): return False
1140
1118
        # create sample tests
1141
1119
        test1 = SampleTestCase('_test_pass')
1146
1124
        test.addTest(test1)
1147
1125
        test.addTest(test2)
1148
1126
        stream = StringIO()
1149
 
        runner = TextTestRunner(stream=stream)
 
1127
        runner = tests.TextTestRunner(stream=stream)
1150
1128
        result = self.run_test_runner(runner, test)
1151
1129
        lines = stream.getvalue().splitlines()
1152
1130
        self.assertEqual([
1163
1141
        workingtree = _get_bzr_source_tree()
1164
1142
        test = TestRunner('dummy_test')
1165
1143
        output = StringIO()
1166
 
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
1144
        runner = tests.TextTestRunner(stream=self._log_file,
 
1145
                                      bench_history=output)
1167
1146
        result = self.run_test_runner(runner, test)
1168
1147
        output_string = output.getvalue()
1169
1148
        self.assertContainsRe(output_string, "--date [0-9.]+")
1180
1159
    def test_success_log_deleted(self):
1181
1160
        """Successful tests have their log deleted"""
1182
1161
 
1183
 
        class LogTester(TestCase):
 
1162
        class LogTester(tests.TestCase):
1184
1163
 
1185
1164
            def test_success(self):
1186
1165
                self.log('this will be removed\n')
1187
1166
 
1188
 
        sio = cStringIO.StringIO()
1189
 
        runner = TextTestRunner(stream=sio)
 
1167
        sio = StringIO()
 
1168
        runner = tests.TextTestRunner(stream=sio)
1190
1169
        test = LogTester('test_success')
1191
1170
        result = self.run_test_runner(runner, test)
1192
1171
 
1195
1174
    def test_skipped_log_deleted(self):
1196
1175
        """Skipped tests have their log deleted"""
1197
1176
 
1198
 
        class LogTester(TestCase):
 
1177
        class LogTester(tests.TestCase):
1199
1178
 
1200
1179
            def test_skipped(self):
1201
1180
                self.log('this will be removed\n')
1202
1181
                raise tests.TestSkipped()
1203
1182
 
1204
 
        sio = cStringIO.StringIO()
1205
 
        runner = TextTestRunner(stream=sio)
 
1183
        sio = StringIO()
 
1184
        runner = tests.TextTestRunner(stream=sio)
1206
1185
        test = LogTester('test_skipped')
1207
1186
        result = self.run_test_runner(runner, test)
1208
1187
 
1211
1190
    def test_not_aplicable_log_deleted(self):
1212
1191
        """Not applicable tests have their log deleted"""
1213
1192
 
1214
 
        class LogTester(TestCase):
 
1193
        class LogTester(tests.TestCase):
1215
1194
 
1216
1195
            def test_not_applicable(self):
1217
1196
                self.log('this will be removed\n')
1218
1197
                raise tests.TestNotApplicable()
1219
1198
 
1220
 
        sio = cStringIO.StringIO()
1221
 
        runner = TextTestRunner(stream=sio)
 
1199
        sio = StringIO()
 
1200
        runner = tests.TextTestRunner(stream=sio)
1222
1201
        test = LogTester('test_not_applicable')
1223
1202
        result = self.run_test_runner(runner, test)
1224
1203
 
1227
1206
    def test_known_failure_log_deleted(self):
1228
1207
        """Know failure tests have their log deleted"""
1229
1208
 
1230
 
        class LogTester(TestCase):
 
1209
        class LogTester(tests.TestCase):
1231
1210
 
1232
1211
            def test_known_failure(self):
1233
1212
                self.log('this will be removed\n')
1234
1213
                raise tests.KnownFailure()
1235
1214
 
1236
 
        sio = cStringIO.StringIO()
1237
 
        runner = TextTestRunner(stream=sio)
 
1215
        sio = StringIO()
 
1216
        runner = tests.TextTestRunner(stream=sio)
1238
1217
        test = LogTester('test_known_failure')
1239
1218
        result = self.run_test_runner(runner, test)
1240
1219
 
1243
1222
    def test_fail_log_kept(self):
1244
1223
        """Failed tests have their log kept"""
1245
1224
 
1246
 
        class LogTester(TestCase):
 
1225
        class LogTester(tests.TestCase):
1247
1226
 
1248
1227
            def test_fail(self):
1249
1228
                self.log('this will be kept\n')
1250
1229
                self.fail('this test fails')
1251
1230
 
1252
 
        sio = cStringIO.StringIO()
1253
 
        runner = TextTestRunner(stream=sio)
 
1231
        sio = StringIO()
 
1232
        runner = tests.TextTestRunner(stream=sio)
1254
1233
        test = LogTester('test_fail')
1255
1234
        result = self.run_test_runner(runner, test)
1256
1235
 
1265
1244
    def test_error_log_kept(self):
1266
1245
        """Tests with errors have their log kept"""
1267
1246
 
1268
 
        class LogTester(TestCase):
 
1247
        class LogTester(tests.TestCase):
1269
1248
 
1270
1249
            def test_error(self):
1271
1250
                self.log('this will be kept\n')
1272
1251
                raise ValueError('random exception raised')
1273
1252
 
1274
 
        sio = cStringIO.StringIO()
1275
 
        runner = TextTestRunner(stream=sio)
 
1253
        sio = StringIO()
 
1254
        runner = tests.TextTestRunner(stream=sio)
1276
1255
        test = LogTester('test_error')
1277
1256
        result = self.run_test_runner(runner, test)
1278
1257
 
1285
1264
        self.assertEqual(log, test._log_contents)
1286
1265
 
1287
1266
 
1288
 
class SampleTestCase(TestCase):
 
1267
class SampleTestCase(tests.TestCase):
1289
1268
 
1290
1269
    def _test_pass(self):
1291
1270
        pass
1293
1272
class _TestException(Exception):
1294
1273
    pass
1295
1274
 
1296
 
class TestTestCase(TestCase):
 
1275
 
 
1276
class TestTestCase(tests.TestCase):
1297
1277
    """Tests that test the core bzrlib TestCase."""
1298
1278
 
 
1279
    def test_assertLength_matches_empty(self):
 
1280
        a_list = []
 
1281
        self.assertLength(0, a_list)
 
1282
 
 
1283
    def test_assertLength_matches_nonempty(self):
 
1284
        a_list = [1, 2, 3]
 
1285
        self.assertLength(3, a_list)
 
1286
 
 
1287
    def test_assertLength_fails_different(self):
 
1288
        a_list = []
 
1289
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
 
1290
 
 
1291
    def test_assertLength_shows_sequence_in_failure(self):
 
1292
        a_list = [1, 2, 3]
 
1293
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
 
1294
            a_list)
 
1295
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
 
1296
            exception.args[0])
 
1297
 
 
1298
    def test_base_setUp_not_called_causes_failure(self):
 
1299
        class TestCaseWithBrokenSetUp(tests.TestCase):
 
1300
            def setUp(self):
 
1301
                pass # does not call TestCase.setUp
 
1302
            def test_foo(self):
 
1303
                pass
 
1304
        test = TestCaseWithBrokenSetUp('test_foo')
 
1305
        result = unittest.TestResult()
 
1306
        test.run(result)
 
1307
        self.assertFalse(result.wasSuccessful())
 
1308
        self.assertEqual(1, result.testsRun)
 
1309
 
 
1310
    def test_base_tearDown_not_called_causes_failure(self):
 
1311
        class TestCaseWithBrokenTearDown(tests.TestCase):
 
1312
            def tearDown(self):
 
1313
                pass # does not call TestCase.tearDown
 
1314
            def test_foo(self):
 
1315
                pass
 
1316
        test = TestCaseWithBrokenTearDown('test_foo')
 
1317
        result = unittest.TestResult()
 
1318
        test.run(result)
 
1319
        self.assertFalse(result.wasSuccessful())
 
1320
        self.assertEqual(1, result.testsRun)
 
1321
 
1299
1322
    def test_debug_flags_sanitised(self):
1300
1323
        """The bzrlib debug flags should be sanitised by setUp."""
 
1324
        if 'allow_debug' in tests.selftest_debug_flags:
 
1325
            raise tests.TestNotApplicable(
 
1326
                '-Eallow_debug option prevents debug flag sanitisation')
1301
1327
        # we could set something and run a test that will check
1302
1328
        # it gets santised, but this is probably sufficient for now:
1303
1329
        # if someone runs the test with -Dsomething it will error.
1304
 
        self.assertEqual(set(), bzrlib.debug.debug_flags)
 
1330
        flags = set()
 
1331
        if self._lock_check_thorough:
 
1332
            flags.add('strict_locks')
 
1333
        self.assertEqual(flags, bzrlib.debug.debug_flags)
 
1334
 
 
1335
    def change_selftest_debug_flags(self, new_flags):
 
1336
        orig_selftest_flags = tests.selftest_debug_flags
 
1337
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1338
        tests.selftest_debug_flags = set(new_flags)
 
1339
 
 
1340
    def _restore_selftest_debug_flags(self, flags):
 
1341
        tests.selftest_debug_flags = flags
 
1342
 
 
1343
    def test_allow_debug_flag(self):
 
1344
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1345
        sanitised (i.e. cleared) before running a test.
 
1346
        """
 
1347
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1348
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1349
        class TestThatRecordsFlags(tests.TestCase):
 
1350
            def test_foo(nested_self):
 
1351
                self.flags = set(bzrlib.debug.debug_flags)
 
1352
        test = TestThatRecordsFlags('test_foo')
 
1353
        test.run(self.make_test_result())
 
1354
        flags = set(['a-flag'])
 
1355
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
 
1356
            flags.add('strict_locks')
 
1357
        self.assertEqual(flags, self.flags)
 
1358
 
 
1359
    def test_disable_lock_checks(self):
 
1360
        """The -Edisable_lock_checks flag disables thorough checks."""
 
1361
        class TestThatRecordsFlags(tests.TestCase):
 
1362
            def test_foo(nested_self):
 
1363
                self.flags = set(bzrlib.debug.debug_flags)
 
1364
                self.test_lock_check_thorough = nested_self._lock_check_thorough
 
1365
        self.change_selftest_debug_flags(set())
 
1366
        test = TestThatRecordsFlags('test_foo')
 
1367
        test.run(self.make_test_result())
 
1368
        # By default we do strict lock checking and thorough lock/unlock
 
1369
        # tracking.
 
1370
        self.assertTrue(self.test_lock_check_thorough)
 
1371
        self.assertEqual(set(['strict_locks']), self.flags)
 
1372
        # Now set the disable_lock_checks flag, and show that this changed.
 
1373
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
 
1374
        test = TestThatRecordsFlags('test_foo')
 
1375
        test.run(self.make_test_result())
 
1376
        self.assertFalse(self.test_lock_check_thorough)
 
1377
        self.assertEqual(set(), self.flags)
 
1378
 
 
1379
    def test_this_fails_strict_lock_check(self):
 
1380
        class TestThatRecordsFlags(tests.TestCase):
 
1381
            def test_foo(nested_self):
 
1382
                self.flags1 = set(bzrlib.debug.debug_flags)
 
1383
                self.thisFailsStrictLockCheck()
 
1384
                self.flags2 = set(bzrlib.debug.debug_flags)
 
1385
        # Make sure lock checking is active
 
1386
        self.change_selftest_debug_flags(set())
 
1387
        test = TestThatRecordsFlags('test_foo')
 
1388
        test.run(self.make_test_result())
 
1389
        self.assertEqual(set(['strict_locks']), self.flags1)
 
1390
        self.assertEqual(set(), self.flags2)
 
1391
 
 
1392
    def test_debug_flags_restored(self):
 
1393
        """The bzrlib debug flags should be restored to their original state
 
1394
        after the test was run, even if allow_debug is set.
 
1395
        """
 
1396
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1397
        # Now run a test that modifies debug.debug_flags.
 
1398
        bzrlib.debug.debug_flags = set(['original-state'])
 
1399
        class TestThatModifiesFlags(tests.TestCase):
 
1400
            def test_foo(self):
 
1401
                bzrlib.debug.debug_flags = set(['modified'])
 
1402
        test = TestThatModifiesFlags('test_foo')
 
1403
        test.run(self.make_test_result())
 
1404
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1405
 
 
1406
    def make_test_result(self):
 
1407
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1305
1408
 
1306
1409
    def inner_test(self):
1307
1410
        # the inner child test
1311
1414
        # the outer child test
1312
1415
        note("outer_start")
1313
1416
        self.inner_test = TestTestCase("inner_child")
1314
 
        result = bzrlib.tests.TextTestResult(self._log_file,
1315
 
                                        descriptions=0,
1316
 
                                        verbosity=1)
 
1417
        result = self.make_test_result()
1317
1418
        self.inner_test.run(result)
1318
1419
        note("outer finish")
1319
1420
 
1323
1424
        # should setup a new log, log content to it, setup a child case (B),
1324
1425
        # which should log independently, then case (A) should log a trailer
1325
1426
        # and return.
1326
 
        # we do two nested children so that we can verify the state of the 
 
1427
        # we do two nested children so that we can verify the state of the
1327
1428
        # logs after the outer child finishes is correct, which a bad clean
1328
1429
        # up routine in tearDown might trigger a fault in our test with only
1329
1430
        # one child, we should instead see the bad result inside our test with
1331
1432
        # the outer child test
1332
1433
        original_trace = bzrlib.trace._trace_file
1333
1434
        outer_test = TestTestCase("outer_child")
1334
 
        result = bzrlib.tests.TextTestResult(self._log_file,
1335
 
                                        descriptions=0,
1336
 
                                        verbosity=1)
 
1435
        result = self.make_test_result()
1337
1436
        outer_test.run(result)
1338
1437
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1339
1438
 
1349
1448
        result = bzrlib.tests.VerboseTestResult(
1350
1449
            unittest._WritelnDecorator(output_stream),
1351
1450
            descriptions=0,
1352
 
            verbosity=2,
1353
 
            num_tests=sample_test.countTestCases())
 
1451
            verbosity=2)
1354
1452
        sample_test.run(result)
1355
1453
        self.assertContainsRe(
1356
1454
            output_stream.getvalue(),
1357
 
            r"\d+ms/ +\d+ms\n$")
 
1455
            r"\d+ms\*\n$")
1358
1456
 
1359
1457
    def test_hooks_sanitised(self):
1360
1458
        """The bzrlib hooks should be sanitised by setUp."""
 
1459
        # Note this test won't fail with hooks that the core library doesn't
 
1460
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1461
        # useful warning in that case.
1361
1462
        self.assertEqual(bzrlib.branch.BranchHooks(),
1362
1463
            bzrlib.branch.Branch.hooks)
1363
1464
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1364
1465
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1466
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1467
            bzrlib.commands.Command.hooks)
1365
1468
 
1366
1469
    def test__gather_lsprof_in_benchmarks(self):
1367
1470
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1368
 
        
 
1471
 
1369
1472
        Each self.time() call is individually and separately profiled.
1370
1473
        """
1371
1474
        self.requireFeature(test_lsprof.LSProfFeature)
1372
 
        # overrides the class member with an instance member so no cleanup 
 
1475
        # overrides the class member with an instance member so no cleanup
1373
1476
        # needed.
1374
1477
        self._gather_lsprof_in_benchmarks = True
1375
1478
        self.time(time.sleep, 0.000)
1382
1485
 
1383
1486
    def test_knownFailure(self):
1384
1487
        """Self.knownFailure() should raise a KnownFailure exception."""
1385
 
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
 
1488
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1386
1489
 
1387
1490
    def test_requireFeature_available(self):
1388
1491
        """self.requireFeature(available) is a no-op."""
1389
 
        class Available(Feature):
 
1492
        class Available(tests.Feature):
1390
1493
            def _probe(self):return True
1391
1494
        feature = Available()
1392
1495
        self.requireFeature(feature)
1393
1496
 
1394
1497
    def test_requireFeature_unavailable(self):
1395
1498
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1396
 
        class Unavailable(Feature):
 
1499
        class Unavailable(tests.Feature):
1397
1500
            def _probe(self):return False
1398
1501
        feature = Unavailable()
1399
 
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
 
1502
        self.assertRaises(tests.UnavailableFeature,
 
1503
                          self.requireFeature, feature)
1400
1504
 
1401
1505
    def test_run_no_parameters(self):
1402
1506
        test = SampleTestCase('_test_pass')
1403
1507
        test.run()
1404
 
    
 
1508
 
1405
1509
    def test_run_enabled_unittest_result(self):
1406
1510
        """Test we revert to regular behaviour when the test is enabled."""
1407
1511
        test = SampleTestCase('_test_pass')
1511
1615
            self.assertListRaises, _TestException, success_generator)
1512
1616
 
1513
1617
 
1514
 
@symbol_versioning.deprecated_function(zero_eleven)
 
1618
# NB: Don't delete this; it's not actually from 0.11!
 
1619
@deprecated_function(deprecated_in((0, 11, 0)))
1515
1620
def sample_deprecated_function():
1516
1621
    """A deprecated function to test applyDeprecated with."""
1517
1622
    return 2
1524
1629
class ApplyDeprecatedHelper(object):
1525
1630
    """A helper class for ApplyDeprecated tests."""
1526
1631
 
1527
 
    @symbol_versioning.deprecated_method(zero_eleven)
 
1632
    @deprecated_method(deprecated_in((0, 11, 0)))
1528
1633
    def sample_deprecated_method(self, param_one):
1529
1634
        """A deprecated method for testing with."""
1530
1635
        return param_one
1532
1637
    def sample_normal_method(self):
1533
1638
        """A undeprecated method."""
1534
1639
 
1535
 
    @symbol_versioning.deprecated_method(zero_ten)
 
1640
    @deprecated_method(deprecated_in((0, 10, 0)))
1536
1641
    def sample_nested_deprecation(self):
1537
1642
        return sample_deprecated_function()
1538
1643
 
1539
1644
 
1540
 
class TestExtraAssertions(TestCase):
 
1645
class TestExtraAssertions(tests.TestCase):
1541
1646
    """Tests for new test assertions in bzrlib test suite"""
1542
1647
 
1543
1648
    def test_assert_isinstance(self):
1544
1649
        self.assertIsInstance(2, int)
1545
1650
        self.assertIsInstance(u'', basestring)
1546
 
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1651
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1652
        self.assertEquals(str(e),
 
1653
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
1547
1654
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1655
        e = self.assertRaises(AssertionError,
 
1656
            self.assertIsInstance, None, int, "it's just not")
 
1657
        self.assertEquals(str(e),
 
1658
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
 
1659
            ": it's just not")
1548
1660
 
1549
1661
    def test_assertEndsWith(self):
1550
1662
        self.assertEndsWith('foo', 'oo')
1553
1665
    def test_applyDeprecated_not_deprecated(self):
1554
1666
        sample_object = ApplyDeprecatedHelper()
1555
1667
        # calling an undeprecated callable raises an assertion
1556
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1668
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1669
            deprecated_in((0, 11, 0)),
1557
1670
            sample_object.sample_normal_method)
1558
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1671
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1672
            deprecated_in((0, 11, 0)),
1559
1673
            sample_undeprecated_function, "a param value")
1560
1674
        # calling a deprecated callable (function or method) with the wrong
1561
1675
        # expected deprecation fails.
1562
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1676
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1677
            deprecated_in((0, 10, 0)),
1563
1678
            sample_object.sample_deprecated_method, "a param value")
1564
 
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1679
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1680
            deprecated_in((0, 10, 0)),
1565
1681
            sample_deprecated_function)
1566
1682
        # calling a deprecated callable (function or method) with the right
1567
1683
        # expected deprecation returns the functions result.
1568
 
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
1684
        self.assertEqual("a param value",
 
1685
            self.applyDeprecated(deprecated_in((0, 11, 0)),
1569
1686
            sample_object.sample_deprecated_method, "a param value"))
1570
 
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
1687
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1571
1688
            sample_deprecated_function))
1572
1689
        # calling a nested deprecation with the wrong deprecation version
1573
 
        # fails even if a deeper nested function was deprecated with the 
 
1690
        # fails even if a deeper nested function was deprecated with the
1574
1691
        # supplied version.
1575
1692
        self.assertRaises(AssertionError, self.applyDeprecated,
1576
 
            zero_eleven, sample_object.sample_nested_deprecation)
 
1693
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1577
1694
        # calling a nested deprecation with the right deprecation value
1578
1695
        # returns the calls result.
1579
 
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
1696
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1580
1697
            sample_object.sample_nested_deprecation))
1581
1698
 
1582
1699
    def test_callDeprecated(self):
1583
1700
        def testfunc(be_deprecated, result=None):
1584
1701
            if be_deprecated is True:
1585
 
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
 
1702
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
1586
1703
                                       stacklevel=1)
1587
1704
            return result
1588
1705
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1593
1710
        self.callDeprecated([], testfunc, be_deprecated=False)
1594
1711
 
1595
1712
 
1596
 
class TestWarningTests(TestCase):
 
1713
class TestWarningTests(tests.TestCase):
1597
1714
    """Tests for calling methods that raise warnings."""
1598
1715
 
1599
1716
    def test_callCatchWarnings(self):
1609
1726
        self.assertEquals("this is your last warning", str(w0))
1610
1727
 
1611
1728
 
1612
 
class TestConvenienceMakers(TestCaseWithTransport):
 
1729
class TestConvenienceMakers(tests.TestCaseWithTransport):
1613
1730
    """Test for the make_* convenience functions."""
1614
1731
 
1615
1732
    def test_make_branch_and_tree_with_format(self):
1628
1745
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1629
1746
 
1630
1747
 
1631
 
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1748
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
1632
1749
 
1633
1750
    def test_make_tree_for_sftp_branch(self):
1634
1751
        """Transports backed by local directories create local trees."""
1635
 
 
 
1752
        # NB: This is arguably a bug in the definition of make_branch_and_tree.
1636
1753
        tree = self.make_branch_and_tree('t1')
1637
1754
        base = tree.bzrdir.root_transport.base
1638
1755
        self.failIf(base.startswith('sftp'),
1643
1760
                tree.branch.repository.bzrdir.root_transport)
1644
1761
 
1645
1762
 
1646
 
class TestSelftest(TestCase):
 
1763
class SelfTestHelper:
 
1764
 
 
1765
    def run_selftest(self, **kwargs):
 
1766
        """Run selftest returning its output."""
 
1767
        output = StringIO()
 
1768
        old_transport = bzrlib.tests.default_transport
 
1769
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
 
1770
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
 
1771
        try:
 
1772
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
 
1773
        finally:
 
1774
            bzrlib.tests.default_transport = old_transport
 
1775
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
1776
        output.seek(0)
 
1777
        return output
 
1778
 
 
1779
 
 
1780
class TestSelftest(tests.TestCase, SelfTestHelper):
1647
1781
    """Tests of bzrlib.tests.selftest."""
1648
1782
 
1649
1783
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1650
1784
        factory_called = []
1651
1785
        def factory():
1652
1786
            factory_called.append(True)
1653
 
            return TestSuite()
 
1787
            return TestUtil.TestSuite()
1654
1788
        out = StringIO()
1655
1789
        err = StringIO()
1656
 
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
 
1790
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1657
1791
            test_suite_factory=factory)
1658
1792
        self.assertEqual([True], factory_called)
1659
1793
 
1660
 
 
1661
 
class TestKnownFailure(TestCase):
 
1794
    def factory(self):
 
1795
        """A test suite factory."""
 
1796
        class Test(tests.TestCase):
 
1797
            def a(self):
 
1798
                pass
 
1799
            def b(self):
 
1800
                pass
 
1801
            def c(self):
 
1802
                pass
 
1803
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
1804
 
 
1805
    def test_list_only(self):
 
1806
        output = self.run_selftest(test_suite_factory=self.factory,
 
1807
            list_only=True)
 
1808
        self.assertEqual(3, len(output.readlines()))
 
1809
 
 
1810
    def test_list_only_filtered(self):
 
1811
        output = self.run_selftest(test_suite_factory=self.factory,
 
1812
            list_only=True, pattern="Test.b")
 
1813
        self.assertEndsWith(output.getvalue(), "Test.b\n")
 
1814
        self.assertLength(1, output.readlines())
 
1815
 
 
1816
    def test_list_only_excludes(self):
 
1817
        output = self.run_selftest(test_suite_factory=self.factory,
 
1818
            list_only=True, exclude_pattern="Test.b")
 
1819
        self.assertNotContainsRe("Test.b", output.getvalue())
 
1820
        self.assertLength(2, output.readlines())
 
1821
 
 
1822
    def test_random(self):
 
1823
        # test randomising by listing a number of tests.
 
1824
        output_123 = self.run_selftest(test_suite_factory=self.factory,
 
1825
            list_only=True, random_seed="123")
 
1826
        output_234 = self.run_selftest(test_suite_factory=self.factory,
 
1827
            list_only=True, random_seed="234")
 
1828
        self.assertNotEqual(output_123, output_234)
 
1829
        # "Randominzing test order..\n\n
 
1830
        self.assertLength(5, output_123.readlines())
 
1831
        self.assertLength(5, output_234.readlines())
 
1832
 
 
1833
    def test_random_reuse_is_same_order(self):
 
1834
        # test randomising by listing a number of tests.
 
1835
        expected = self.run_selftest(test_suite_factory=self.factory,
 
1836
            list_only=True, random_seed="123")
 
1837
        repeated = self.run_selftest(test_suite_factory=self.factory,
 
1838
            list_only=True, random_seed="123")
 
1839
        self.assertEqual(expected.getvalue(), repeated.getvalue())
 
1840
 
 
1841
    def test_runner_class(self):
 
1842
        self.requireFeature(SubUnitFeature)
 
1843
        from subunit import ProtocolTestCase
 
1844
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
1845
            test_suite_factory=self.factory)
 
1846
        test = ProtocolTestCase(stream)
 
1847
        result = unittest.TestResult()
 
1848
        test.run(result)
 
1849
        self.assertEqual(3, result.testsRun)
 
1850
 
 
1851
    def test_starting_with_single_argument(self):
 
1852
        output = self.run_selftest(test_suite_factory=self.factory,
 
1853
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
 
1854
            list_only=True)
 
1855
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
 
1856
            output.getvalue())
 
1857
 
 
1858
    def test_starting_with_multiple_argument(self):
 
1859
        output = self.run_selftest(test_suite_factory=self.factory,
 
1860
            starting_with=['bzrlib.tests.test_selftest.Test.a',
 
1861
                'bzrlib.tests.test_selftest.Test.b'],
 
1862
            list_only=True)
 
1863
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
 
1864
            'bzrlib.tests.test_selftest.Test.b\n',
 
1865
            output.getvalue())
 
1866
 
 
1867
    def check_transport_set(self, transport_server):
 
1868
        captured_transport = []
 
1869
        def seen_transport(a_transport):
 
1870
            captured_transport.append(a_transport)
 
1871
        class Capture(tests.TestCase):
 
1872
            def a(self):
 
1873
                seen_transport(bzrlib.tests.default_transport)
 
1874
        def factory():
 
1875
            return TestUtil.TestSuite([Capture("a")])
 
1876
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
 
1877
        self.assertEqual(transport_server, captured_transport[0])
 
1878
 
 
1879
    def test_transport_sftp(self):
 
1880
        try:
 
1881
            import bzrlib.transport.sftp
 
1882
        except errors.ParamikoNotPresent:
 
1883
            raise tests.TestSkipped("Paramiko not present")
 
1884
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
 
1885
 
 
1886
    def test_transport_memory(self):
 
1887
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
 
1888
 
 
1889
 
 
1890
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
 
1891
    # Does IO: reads test.list
 
1892
 
 
1893
    def test_load_list(self):
 
1894
        # Provide a list with one test - this test.
 
1895
        test_id_line = '%s\n' % self.id()
 
1896
        self.build_tree_contents([('test.list', test_id_line)])
 
1897
        # And generate a list of the tests in  the suite.
 
1898
        stream = self.run_selftest(load_list='test.list', list_only=True)
 
1899
        self.assertEqual(test_id_line, stream.getvalue())
 
1900
 
 
1901
    def test_load_unknown(self):
 
1902
        # Provide a list with one test - this test.
 
1903
        # And generate a list of the tests in  the suite.
 
1904
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
 
1905
            load_list='missing file name', list_only=True)
 
1906
 
 
1907
 
 
1908
class TestRunBzr(tests.TestCase):
 
1909
 
 
1910
    out = ''
 
1911
    err = ''
 
1912
 
 
1913
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
 
1914
                         working_dir=None):
 
1915
        """Override _run_bzr_core to test how it is invoked by run_bzr.
 
1916
 
 
1917
        Attempts to run bzr from inside this class don't actually run it.
 
1918
 
 
1919
        We test how run_bzr actually invokes bzr in another location.
 
1920
        Here we only need to test that it is run_bzr passes the right
 
1921
        parameters to run_bzr.
 
1922
        """
 
1923
        self.argv = list(argv)
 
1924
        self.retcode = retcode
 
1925
        self.encoding = encoding
 
1926
        self.stdin = stdin
 
1927
        self.working_dir = working_dir
 
1928
        return self.out, self.err
 
1929
 
 
1930
    def test_run_bzr_error(self):
 
1931
        self.out = "It sure does!\n"
 
1932
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
 
1933
        self.assertEqual(['rocks'], self.argv)
 
1934
        self.assertEqual(34, self.retcode)
 
1935
        self.assertEqual(out, 'It sure does!\n')
 
1936
 
 
1937
    def test_run_bzr_error_regexes(self):
 
1938
        self.out = ''
 
1939
        self.err = "bzr: ERROR: foobarbaz is not versioned"
 
1940
        out, err = self.run_bzr_error(
 
1941
                ["bzr: ERROR: foobarbaz is not versioned"],
 
1942
                ['file-id', 'foobarbaz'])
 
1943
 
 
1944
    def test_encoding(self):
 
1945
        """Test that run_bzr passes encoding to _run_bzr_core"""
 
1946
        self.run_bzr('foo bar')
 
1947
        self.assertEqual(None, self.encoding)
 
1948
        self.assertEqual(['foo', 'bar'], self.argv)
 
1949
 
 
1950
        self.run_bzr('foo bar', encoding='baz')
 
1951
        self.assertEqual('baz', self.encoding)
 
1952
        self.assertEqual(['foo', 'bar'], self.argv)
 
1953
 
 
1954
    def test_retcode(self):
 
1955
        """Test that run_bzr passes retcode to _run_bzr_core"""
 
1956
        # Default is retcode == 0
 
1957
        self.run_bzr('foo bar')
 
1958
        self.assertEqual(0, self.retcode)
 
1959
        self.assertEqual(['foo', 'bar'], self.argv)
 
1960
 
 
1961
        self.run_bzr('foo bar', retcode=1)
 
1962
        self.assertEqual(1, self.retcode)
 
1963
        self.assertEqual(['foo', 'bar'], self.argv)
 
1964
 
 
1965
        self.run_bzr('foo bar', retcode=None)
 
1966
        self.assertEqual(None, self.retcode)
 
1967
        self.assertEqual(['foo', 'bar'], self.argv)
 
1968
 
 
1969
        self.run_bzr(['foo', 'bar'], retcode=3)
 
1970
        self.assertEqual(3, self.retcode)
 
1971
        self.assertEqual(['foo', 'bar'], self.argv)
 
1972
 
 
1973
    def test_stdin(self):
 
1974
        # test that the stdin keyword to run_bzr is passed through to
 
1975
        # _run_bzr_core as-is. We do this by overriding
 
1976
        # _run_bzr_core in this class, and then calling run_bzr,
 
1977
        # which is a convenience function for _run_bzr_core, so
 
1978
        # should invoke it.
 
1979
        self.run_bzr('foo bar', stdin='gam')
 
1980
        self.assertEqual('gam', self.stdin)
 
1981
        self.assertEqual(['foo', 'bar'], self.argv)
 
1982
 
 
1983
        self.run_bzr('foo bar', stdin='zippy')
 
1984
        self.assertEqual('zippy', self.stdin)
 
1985
        self.assertEqual(['foo', 'bar'], self.argv)
 
1986
 
 
1987
    def test_working_dir(self):
 
1988
        """Test that run_bzr passes working_dir to _run_bzr_core"""
 
1989
        self.run_bzr('foo bar')
 
1990
        self.assertEqual(None, self.working_dir)
 
1991
        self.assertEqual(['foo', 'bar'], self.argv)
 
1992
 
 
1993
        self.run_bzr('foo bar', working_dir='baz')
 
1994
        self.assertEqual('baz', self.working_dir)
 
1995
        self.assertEqual(['foo', 'bar'], self.argv)
 
1996
 
 
1997
    def test_reject_extra_keyword_arguments(self):
 
1998
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
 
1999
                          error_regex=['error message'])
 
2000
 
 
2001
 
 
2002
class TestRunBzrCaptured(tests.TestCaseWithTransport):
 
2003
    # Does IO when testing the working_dir parameter.
 
2004
 
 
2005
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
2006
                         a_callable=None, *args, **kwargs):
 
2007
        self.stdin = stdin
 
2008
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
 
2009
        self.factory = bzrlib.ui.ui_factory
 
2010
        self.working_dir = osutils.getcwd()
 
2011
        stdout.write('foo\n')
 
2012
        stderr.write('bar\n')
 
2013
        return 0
 
2014
 
 
2015
    def test_stdin(self):
 
2016
        # test that the stdin keyword to _run_bzr_core is passed through to
 
2017
        # apply_redirected as a StringIO. We do this by overriding
 
2018
        # apply_redirected in this class, and then calling _run_bzr_core,
 
2019
        # which calls apply_redirected.
 
2020
        self.run_bzr(['foo', 'bar'], stdin='gam')
 
2021
        self.assertEqual('gam', self.stdin.read())
 
2022
        self.assertTrue(self.stdin is self.factory_stdin)
 
2023
        self.run_bzr(['foo', 'bar'], stdin='zippy')
 
2024
        self.assertEqual('zippy', self.stdin.read())
 
2025
        self.assertTrue(self.stdin is self.factory_stdin)
 
2026
 
 
2027
    def test_ui_factory(self):
 
2028
        # each invocation of self.run_bzr should get its
 
2029
        # own UI factory, which is an instance of TestUIFactory,
 
2030
        # with stdin, stdout and stderr attached to the stdin,
 
2031
        # stdout and stderr of the invoked run_bzr
 
2032
        current_factory = bzrlib.ui.ui_factory
 
2033
        self.run_bzr(['foo'])
 
2034
        self.failIf(current_factory is self.factory)
 
2035
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
2036
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
2037
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
2038
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
2039
        self.assertIsInstance(self.factory, tests.TestUIFactory)
 
2040
 
 
2041
    def test_working_dir(self):
 
2042
        self.build_tree(['one/', 'two/'])
 
2043
        cwd = osutils.getcwd()
 
2044
 
 
2045
        # Default is to work in the current directory
 
2046
        self.run_bzr(['foo', 'bar'])
 
2047
        self.assertEqual(cwd, self.working_dir)
 
2048
 
 
2049
        self.run_bzr(['foo', 'bar'], working_dir=None)
 
2050
        self.assertEqual(cwd, self.working_dir)
 
2051
 
 
2052
        # The function should be run in the alternative directory
 
2053
        # but afterwards the current working dir shouldn't be changed
 
2054
        self.run_bzr(['foo', 'bar'], working_dir='one')
 
2055
        self.assertNotEqual(cwd, self.working_dir)
 
2056
        self.assertEndsWith(self.working_dir, 'one')
 
2057
        self.assertEqual(cwd, osutils.getcwd())
 
2058
 
 
2059
        self.run_bzr(['foo', 'bar'], working_dir='two')
 
2060
        self.assertNotEqual(cwd, self.working_dir)
 
2061
        self.assertEndsWith(self.working_dir, 'two')
 
2062
        self.assertEqual(cwd, osutils.getcwd())
 
2063
 
 
2064
 
 
2065
class StubProcess(object):
 
2066
    """A stub process for testing run_bzr_subprocess."""
 
2067
    
 
2068
    def __init__(self, out="", err="", retcode=0):
 
2069
        self.out = out
 
2070
        self.err = err
 
2071
        self.returncode = retcode
 
2072
 
 
2073
    def communicate(self):
 
2074
        return self.out, self.err
 
2075
 
 
2076
 
 
2077
class TestRunBzrSubprocess(tests.TestCaseWithTransport):
 
2078
 
 
2079
    def setUp(self):
 
2080
        tests.TestCaseWithTransport.setUp(self)
 
2081
        self.subprocess_calls = []
 
2082
 
 
2083
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
2084
                             skip_if_plan_to_signal=False,
 
2085
                             working_dir=None,
 
2086
                             allow_plugins=False):
 
2087
        """capture what run_bzr_subprocess tries to do."""
 
2088
        self.subprocess_calls.append({'process_args':process_args,
 
2089
            'env_changes':env_changes,
 
2090
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
 
2091
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
 
2092
        return self.next_subprocess
 
2093
 
 
2094
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
 
2095
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
 
2096
 
 
2097
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
 
2098
        that will return static results. This assertion method populates those
 
2099
        results and also checks the arguments run_bzr_subprocess generates.
 
2100
        """
 
2101
        self.next_subprocess = process
 
2102
        try:
 
2103
            result = self.run_bzr_subprocess(*args, **kwargs)
 
2104
        except:
 
2105
            self.next_subprocess = None
 
2106
            for key, expected in expected_args.iteritems():
 
2107
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2108
            raise
 
2109
        else:
 
2110
            self.next_subprocess = None
 
2111
            for key, expected in expected_args.iteritems():
 
2112
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2113
            return result
 
2114
 
 
2115
    def test_run_bzr_subprocess(self):
 
2116
        """The run_bzr_helper_external command behaves nicely."""
 
2117
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2118
            StubProcess(), '--version')
 
2119
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2120
            StubProcess(), ['--version'])
 
2121
        # retcode=None disables retcode checking
 
2122
        result = self.assertRunBzrSubprocess({},
 
2123
            StubProcess(retcode=3), '--version', retcode=None)
 
2124
        result = self.assertRunBzrSubprocess({},
 
2125
            StubProcess(out="is free software"), '--version')
 
2126
        self.assertContainsRe(result[0], 'is free software')
 
2127
        # Running a subcommand that is missing errors
 
2128
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
 
2129
            {'process_args':['--versionn']}, StubProcess(retcode=3),
 
2130
            '--versionn')
 
2131
        # Unless it is told to expect the error from the subprocess
 
2132
        result = self.assertRunBzrSubprocess({},
 
2133
            StubProcess(retcode=3), '--versionn', retcode=3)
 
2134
        # Or to ignore retcode checking
 
2135
        result = self.assertRunBzrSubprocess({},
 
2136
            StubProcess(err="unknown command", retcode=3), '--versionn',
 
2137
            retcode=None)
 
2138
        self.assertContainsRe(result[1], 'unknown command')
 
2139
 
 
2140
    def test_env_change_passes_through(self):
 
2141
        self.assertRunBzrSubprocess(
 
2142
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
 
2143
            StubProcess(), '',
 
2144
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
 
2145
 
 
2146
    def test_no_working_dir_passed_as_None(self):
 
2147
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
 
2148
 
 
2149
    def test_no_working_dir_passed_through(self):
 
2150
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
 
2151
            working_dir='dir')
 
2152
 
 
2153
    def test_run_bzr_subprocess_no_plugins(self):
 
2154
        self.assertRunBzrSubprocess({'allow_plugins': False},
 
2155
            StubProcess(), '')
 
2156
 
 
2157
    def test_allow_plugins(self):
 
2158
        self.assertRunBzrSubprocess({'allow_plugins': True},
 
2159
            StubProcess(), '', allow_plugins=True)
 
2160
 
 
2161
 
 
2162
class _DontSpawnProcess(Exception):
 
2163
    """A simple exception which just allows us to skip unnecessary steps"""
 
2164
 
 
2165
 
 
2166
class TestStartBzrSubProcess(tests.TestCase):
 
2167
 
 
2168
    def check_popen_state(self):
 
2169
        """Replace to make assertions when popen is called."""
 
2170
 
 
2171
    def _popen(self, *args, **kwargs):
 
2172
        """Record the command that is run, so that we can ensure it is correct"""
 
2173
        self.check_popen_state()
 
2174
        self._popen_args = args
 
2175
        self._popen_kwargs = kwargs
 
2176
        raise _DontSpawnProcess()
 
2177
 
 
2178
    def test_run_bzr_subprocess_no_plugins(self):
 
2179
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
 
2180
        command = self._popen_args[0]
 
2181
        self.assertEqual(sys.executable, command[0])
 
2182
        self.assertEqual(self.get_bzr_path(), command[1])
 
2183
        self.assertEqual(['--no-plugins'], command[2:])
 
2184
 
 
2185
    def test_allow_plugins(self):
 
2186
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2187
            allow_plugins=True)
 
2188
        command = self._popen_args[0]
 
2189
        self.assertEqual([], command[2:])
 
2190
 
 
2191
    def test_set_env(self):
 
2192
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2193
        # set in the child
 
2194
        def check_environment():
 
2195
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2196
        self.check_popen_state = check_environment
 
2197
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2198
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2199
        # not set in theparent
 
2200
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2201
 
 
2202
    def test_run_bzr_subprocess_env_del(self):
 
2203
        """run_bzr_subprocess can remove environment variables too."""
 
2204
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2205
        def check_environment():
 
2206
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2207
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
 
2208
        self.check_popen_state = check_environment
 
2209
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2210
            env_changes={'EXISTANT_ENV_VAR':None})
 
2211
        # Still set in parent
 
2212
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2213
        del os.environ['EXISTANT_ENV_VAR']
 
2214
 
 
2215
    def test_env_del_missing(self):
 
2216
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2217
        def check_environment():
 
2218
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2219
        self.check_popen_state = check_environment
 
2220
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2221
            env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2222
 
 
2223
    def test_working_dir(self):
 
2224
        """Test that we can specify the working dir for the child"""
 
2225
        orig_getcwd = osutils.getcwd
 
2226
        orig_chdir = os.chdir
 
2227
        chdirs = []
 
2228
        def chdir(path):
 
2229
            chdirs.append(path)
 
2230
        os.chdir = chdir
 
2231
        try:
 
2232
            def getcwd():
 
2233
                return 'current'
 
2234
            osutils.getcwd = getcwd
 
2235
            try:
 
2236
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2237
                    working_dir='foo')
 
2238
            finally:
 
2239
                osutils.getcwd = orig_getcwd
 
2240
        finally:
 
2241
            os.chdir = orig_chdir
 
2242
        self.assertEqual(['foo', 'current'], chdirs)
 
2243
 
 
2244
 
 
2245
class TestBzrSubprocess(tests.TestCaseWithTransport):
 
2246
 
 
2247
    def test_start_and_stop_bzr_subprocess(self):
 
2248
        """We can start and perform other test actions while that process is
 
2249
        still alive.
 
2250
        """
 
2251
        process = self.start_bzr_subprocess(['--version'])
 
2252
        result = self.finish_bzr_subprocess(process)
 
2253
        self.assertContainsRe(result[0], 'is free software')
 
2254
        self.assertEqual('', result[1])
 
2255
 
 
2256
    def test_start_and_stop_bzr_subprocess_with_error(self):
 
2257
        """finish_bzr_subprocess allows specification of the desired exit code.
 
2258
        """
 
2259
        process = self.start_bzr_subprocess(['--versionn'])
 
2260
        result = self.finish_bzr_subprocess(process, retcode=3)
 
2261
        self.assertEqual('', result[0])
 
2262
        self.assertContainsRe(result[1], 'unknown command')
 
2263
 
 
2264
    def test_start_and_stop_bzr_subprocess_ignoring_retcode(self):
 
2265
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
2266
        process = self.start_bzr_subprocess(['--versionn'])
 
2267
        result = self.finish_bzr_subprocess(process, retcode=None)
 
2268
        self.assertEqual('', result[0])
 
2269
        self.assertContainsRe(result[1], 'unknown command')
 
2270
 
 
2271
    def test_start_and_stop_bzr_subprocess_with_unexpected_retcode(self):
 
2272
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2273
        not the expected one.
 
2274
        """
 
2275
        process = self.start_bzr_subprocess(['--versionn'])
 
2276
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
2277
                          process)
 
2278
 
 
2279
    def test_start_and_stop_bzr_subprocess_send_signal(self):
 
2280
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2281
        not the expected one.
 
2282
        """
 
2283
        process = self.start_bzr_subprocess(['wait-until-signalled'],
 
2284
                                            skip_if_plan_to_signal=True)
 
2285
        self.assertEqual('running\n', process.stdout.readline())
 
2286
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
 
2287
                                            retcode=3)
 
2288
        self.assertEqual('', result[0])
 
2289
        self.assertEqual('bzr: interrupted\n', result[1])
 
2290
 
 
2291
    def test_start_and_stop_working_dir(self):
 
2292
        cwd = osutils.getcwd()
 
2293
        self.make_branch_and_tree('one')
 
2294
        process = self.start_bzr_subprocess(['root'], working_dir='one')
 
2295
        result = self.finish_bzr_subprocess(process, universal_newlines=True)
 
2296
        self.assertEndsWith(result[0], 'one\n')
 
2297
        self.assertEqual('', result[1])
 
2298
 
 
2299
 
 
2300
class TestKnownFailure(tests.TestCase):
1662
2301
 
1663
2302
    def test_known_failure(self):
1664
2303
        """Check that KnownFailure is defined appropriately."""
1665
2304
        # a KnownFailure is an assertion error for compatability with unaware
1666
2305
        # runners.
1667
 
        self.assertIsInstance(KnownFailure(""), AssertionError)
 
2306
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
1668
2307
 
1669
2308
    def test_expect_failure(self):
1670
2309
        try:
1671
2310
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1672
 
        except KnownFailure, e:
 
2311
        except tests.KnownFailure, e:
1673
2312
            self.assertEqual('Doomed to failure', e.args[0])
1674
2313
        try:
1675
2314
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1680
2319
            self.fail('Assertion not raised')
1681
2320
 
1682
2321
 
1683
 
class TestFeature(TestCase):
 
2322
class TestFeature(tests.TestCase):
1684
2323
 
1685
2324
    def test_caching(self):
1686
2325
        """Feature._probe is called by the feature at most once."""
1687
 
        class InstrumentedFeature(Feature):
 
2326
        class InstrumentedFeature(tests.Feature):
1688
2327
            def __init__(self):
1689
 
                Feature.__init__(self)
 
2328
                super(InstrumentedFeature, self).__init__()
1690
2329
                self.calls = []
1691
2330
            def _probe(self):
1692
2331
                self.calls.append('_probe')
1699
2338
 
1700
2339
    def test_named_str(self):
1701
2340
        """Feature.__str__ should thunk to feature_name()."""
1702
 
        class NamedFeature(Feature):
 
2341
        class NamedFeature(tests.Feature):
1703
2342
            def feature_name(self):
1704
2343
                return 'symlinks'
1705
2344
        feature = NamedFeature()
1707
2346
 
1708
2347
    def test_default_str(self):
1709
2348
        """Feature.__str__ should default to __class__.__name__."""
1710
 
        class NamedFeature(Feature):
 
2349
        class NamedFeature(tests.Feature):
1711
2350
            pass
1712
2351
        feature = NamedFeature()
1713
2352
        self.assertEqual('NamedFeature', str(feature))
1714
2353
 
1715
2354
 
1716
 
class TestUnavailableFeature(TestCase):
 
2355
class TestUnavailableFeature(tests.TestCase):
1717
2356
 
1718
2357
    def test_access_feature(self):
1719
 
        feature = Feature()
1720
 
        exception = UnavailableFeature(feature)
 
2358
        feature = tests.Feature()
 
2359
        exception = tests.UnavailableFeature(feature)
1721
2360
        self.assertIs(feature, exception.args[0])
1722
2361
 
1723
2362
 
1724
 
class TestSelftestFiltering(TestCase):
 
2363
class TestSelftestFiltering(tests.TestCase):
1725
2364
 
1726
2365
    def setUp(self):
 
2366
        tests.TestCase.setUp(self)
1727
2367
        self.suite = TestUtil.TestSuite()
1728
2368
        self.loader = TestUtil.TestLoader()
1729
 
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1730
 
            'bzrlib.tests.test_selftest']))
 
2369
        self.suite.addTest(self.loader.loadTestsFromModule(
 
2370
            sys.modules['bzrlib.tests.test_selftest']))
1731
2371
        self.all_names = _test_ids(self.suite)
1732
2372
 
1733
2373
    def test_condition_id_re(self):
1734
2374
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1735
2375
            'test_condition_id_re')
1736
 
        filtered_suite = filter_suite_by_condition(self.suite,
1737
 
            condition_id_re('test_condition_id_re'))
 
2376
        filtered_suite = tests.filter_suite_by_condition(
 
2377
            self.suite, tests.condition_id_re('test_condition_id_re'))
1738
2378
        self.assertEqual([test_name], _test_ids(filtered_suite))
1739
2379
 
1740
2380
    def test_condition_id_in_list(self):
1741
2381
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1742
2382
                      'test_condition_id_in_list']
1743
2383
        id_list = tests.TestIdList(test_names)
1744
 
        filtered_suite = filter_suite_by_condition(
 
2384
        filtered_suite = tests.filter_suite_by_condition(
1745
2385
            self.suite, tests.condition_id_in_list(id_list))
1746
2386
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1747
 
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
 
2387
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
1748
2388
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1749
2389
 
1750
2390
    def test_condition_id_startswith(self):
1751
2391
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1752
 
        start = klass + 'test_condition_id_starts'
1753
 
        test_names = [klass + 'test_condition_id_startswith']
1754
 
        filtered_suite = filter_suite_by_condition(
1755
 
            self.suite, tests.condition_id_startswith(start))
1756
 
        my_pattern = 'TestSelftestFiltering.*test_condition_id_startswith'
1757
 
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
1758
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2392
        start1 = klass + 'test_condition_id_starts'
 
2393
        start2 = klass + 'test_condition_id_in'
 
2394
        test_names = [ klass + 'test_condition_id_in_list',
 
2395
                      klass + 'test_condition_id_startswith',
 
2396
                     ]
 
2397
        filtered_suite = tests.filter_suite_by_condition(
 
2398
            self.suite, tests.condition_id_startswith([start1, start2]))
 
2399
        self.assertEqual(test_names, _test_ids(filtered_suite))
1759
2400
 
1760
2401
    def test_condition_isinstance(self):
1761
 
        filtered_suite = filter_suite_by_condition(self.suite,
1762
 
            condition_isinstance(self.__class__))
 
2402
        filtered_suite = tests.filter_suite_by_condition(
 
2403
            self.suite, tests.condition_isinstance(self.__class__))
1763
2404
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1764
 
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
 
2405
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
1765
2406
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1766
2407
 
1767
2408
    def test_exclude_tests_by_condition(self):
1768
2409
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1769
2410
            'test_exclude_tests_by_condition')
1770
 
        filtered_suite = exclude_tests_by_condition(self.suite,
 
2411
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
1771
2412
            lambda x:x.id() == excluded_name)
1772
2413
        self.assertEqual(len(self.all_names) - 1,
1773
2414
            filtered_suite.countTestCases())
1778
2419
 
1779
2420
    def test_exclude_tests_by_re(self):
1780
2421
        self.all_names = _test_ids(self.suite)
1781
 
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
 
2422
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
2423
                                                   'exclude_tests_by_re')
1782
2424
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1783
2425
            'test_exclude_tests_by_re')
1784
2426
        self.assertEqual(len(self.all_names) - 1,
1791
2433
    def test_filter_suite_by_condition(self):
1792
2434
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1793
2435
            'test_filter_suite_by_condition')
1794
 
        filtered_suite = filter_suite_by_condition(self.suite,
 
2436
        filtered_suite = tests.filter_suite_by_condition(self.suite,
1795
2437
            lambda x:x.id() == test_name)
1796
2438
        self.assertEqual([test_name], _test_ids(filtered_suite))
1797
2439
 
1798
2440
    def test_filter_suite_by_re(self):
1799
 
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
2441
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
2442
                                                  'test_filter_suite_by_r')
1800
2443
        filtered_names = _test_ids(filtered_suite)
1801
2444
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1802
2445
            'TestSelftestFiltering.test_filter_suite_by_re'])
1814
2457
 
1815
2458
    def test_filter_suite_by_id_startswith(self):
1816
2459
        # By design this test may fail if another test is added whose name also
1817
 
        # begins with the start value used.
 
2460
        # begins with one of the start value used.
1818
2461
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1819
 
        start = klass + 'test_filter_suite_by_id_starts'
1820
 
        test_list = [klass + 'test_filter_suite_by_id_startswith']
1821
 
        filtered_suite = tests.filter_suite_by_id_startswith(self.suite, start)
1822
 
        filtered_names = _test_ids(filtered_suite)
 
2462
        start1 = klass + 'test_filter_suite_by_id_starts'
 
2463
        start2 = klass + 'test_filter_suite_by_id_li'
 
2464
        test_list = [klass + 'test_filter_suite_by_id_list',
 
2465
                     klass + 'test_filter_suite_by_id_startswith',
 
2466
                     ]
 
2467
        filtered_suite = tests.filter_suite_by_id_startswith(
 
2468
            self.suite, [start1, start2])
1823
2469
        self.assertEqual(
1824
 
            filtered_names,
1825
 
            ['bzrlib.tests.test_selftest.'
1826
 
             'TestSelftestFiltering.test_filter_suite_by_id_startswith'])
 
2470
            test_list,
 
2471
            _test_ids(filtered_suite),
 
2472
            )
1827
2473
 
1828
2474
    def test_preserve_input(self):
1829
2475
        # NB: Surely this is something in the stdlib to do this?
1830
 
        self.assertTrue(self.suite is preserve_input(self.suite))
1831
 
        self.assertTrue("@#$" is preserve_input("@#$"))
 
2476
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
2477
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
1832
2478
 
1833
2479
    def test_randomize_suite(self):
1834
 
        randomized_suite = randomize_suite(self.suite)
 
2480
        randomized_suite = tests.randomize_suite(self.suite)
1835
2481
        # randomizing should not add or remove test names.
1836
2482
        self.assertEqual(set(_test_ids(self.suite)),
1837
2483
                         set(_test_ids(randomized_suite)))
1847
2493
 
1848
2494
    def test_split_suit_by_condition(self):
1849
2495
        self.all_names = _test_ids(self.suite)
1850
 
        condition = condition_id_re('test_filter_suite_by_r')
1851
 
        split_suite = split_suite_by_condition(self.suite, condition)
 
2496
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2497
        split_suite = tests.split_suite_by_condition(self.suite, condition)
1852
2498
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1853
2499
            'test_filter_suite_by_re')
1854
2500
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1859
2505
 
1860
2506
    def test_split_suit_by_re(self):
1861
2507
        self.all_names = _test_ids(self.suite)
1862
 
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
2508
        split_suite = tests.split_suite_by_re(self.suite,
 
2509
                                              'test_filter_suite_by_r')
1863
2510
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1864
2511
            'test_filter_suite_by_re')
1865
2512
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1869
2516
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1870
2517
 
1871
2518
 
1872
 
class TestCheckInventoryShape(TestCaseWithTransport):
 
2519
class TestCheckInventoryShape(tests.TestCaseWithTransport):
1873
2520
 
1874
2521
    def test_check_inventory_shape(self):
1875
2522
        files = ['a', 'b/', 'b/c']
1883
2530
            tree.unlock()
1884
2531
 
1885
2532
 
1886
 
class TestBlackboxSupport(TestCase):
 
2533
class TestBlackboxSupport(tests.TestCase):
1887
2534
    """Tests for testsuite blackbox features."""
1888
2535
 
1889
2536
    def test_run_bzr_failure_not_caught(self):
1910
2557
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1911
2558
 
1912
2559
 
1913
 
class TestTestLoader(TestCase):
 
2560
class TestTestLoader(tests.TestCase):
1914
2561
    """Tests for the test loader."""
1915
2562
 
1916
2563
    def _get_loader_and_module(self):
1917
2564
        """Gets a TestLoader and a module with one test in it."""
1918
2565
        loader = TestUtil.TestLoader()
1919
2566
        module = {}
1920
 
        class Stub(TestCase):
 
2567
        class Stub(tests.TestCase):
1921
2568
            def test_foo(self):
1922
2569
                pass
1923
2570
        class MyModule(object):
1936
2583
        # load_tests do not need that :)
1937
2584
        def load_tests(self, standard_tests, module, loader):
1938
2585
            result = loader.suiteClass()
1939
 
            for test in iter_suite_tests(standard_tests):
 
2586
            for test in tests.iter_suite_tests(standard_tests):
1940
2587
                result.addTests([test, test])
1941
2588
            return result
1942
2589
        # add a load_tests() method which multiplies the tests from the module.
1961
2608
 
1962
2609
    def _create_suite(self, test_id_list):
1963
2610
 
1964
 
        class Stub(TestCase):
 
2611
        class Stub(tests.TestCase):
1965
2612
            def test_foo(self):
1966
2613
                pass
1967
2614
 
1977
2624
 
1978
2625
    def _test_ids(self, test_suite):
1979
2626
        """Get the ids for the tests in a test suite."""
1980
 
        return [t.id() for t in iter_suite_tests(test_suite)]
 
2627
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
1981
2628
 
1982
2629
    def test_empty_list(self):
1983
2630
        id_list = self._create_id_list([])
2009
2656
        self.assertTrue(id_list.refers_to('mod.class'))
2010
2657
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2011
2658
 
2012
 
    def test_test_suite(self):
2013
 
        # This test is slow, so we do a single test with one test in each
2014
 
        # category
2015
 
        test_list = [
2016
 
            # testmod_names
2017
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2018
 
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
2019
 
            # transport implementations
2020
 
            'bzrlib.tests.test_transport_implementations.TransportTests'
2021
 
            '.test_abspath(LocalURLServer)',
2022
 
            # modules_to_doctest
2023
 
            'bzrlib.timestamp.format_highres_date',
2024
 
            # plugins can't be tested that way since selftest may be run with
2025
 
            # --no-plugins
2026
 
            ]
2027
 
        suite = tests.test_suite(test_list)
2028
 
        self.assertEquals(test_list, _test_ids(suite))
2029
 
 
2030
2659
    def test_test_suite_matches_id_list_with_unknown(self):
2031
2660
        loader = TestUtil.TestLoader()
2032
2661
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2040
2669
        loader = TestUtil.TestLoader()
2041
2670
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2042
2671
        dupes = loader.suiteClass()
2043
 
        for test in iter_suite_tests(suite):
 
2672
        for test in tests.iter_suite_tests(suite):
2044
2673
            dupes.addTest(test)
2045
2674
            dupes.addTest(test) # Add it again
2046
2675
 
2052
2681
                          duplicates)
2053
2682
 
2054
2683
 
 
2684
class TestTestSuite(tests.TestCase):
 
2685
 
 
2686
    def test_test_suite(self):
 
2687
        # This test is slow - it loads the entire test suite to operate, so we
 
2688
        # do a single test with one test in each category
 
2689
        test_list = [
 
2690
            # testmod_names
 
2691
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2692
            ('bzrlib.tests.per_transport.TransportTests'
 
2693
             '.test_abspath(LocalURLServer)'),
 
2694
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2695
            # modules_to_doctest
 
2696
            'bzrlib.timestamp.format_highres_date',
 
2697
            # plugins can't be tested that way since selftest may be run with
 
2698
            # --no-plugins
 
2699
            ]
 
2700
        suite = tests.test_suite(test_list)
 
2701
        self.assertEquals(test_list, _test_ids(suite))
 
2702
 
 
2703
    def test_test_suite_list_and_start(self):
 
2704
        # We cannot test this at the same time as the main load, because we want
 
2705
        # to know that starting_with == None works. So a second full load is
 
2706
        # incurred.
 
2707
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
2708
        suite = tests.test_suite(test_list,
 
2709
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
2710
        # test_test_suite_list_and_start is not included 
 
2711
        self.assertEquals(test_list, _test_ids(suite))
 
2712
 
 
2713
 
2055
2714
class TestLoadTestIdList(tests.TestCaseInTempDir):
2056
2715
 
2057
2716
    def _create_test_list_file(self, file_name, content):
2135
2794
 
2136
2795
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2137
2796
        self.assertEquals([], _test_ids(suite))
 
2797
 
 
2798
 
 
2799
class TestTestPrefixRegistry(tests.TestCase):
 
2800
 
 
2801
    def _get_registry(self):
 
2802
        tp_registry = tests.TestPrefixAliasRegistry()
 
2803
        return tp_registry
 
2804
 
 
2805
    def test_register_new_prefix(self):
 
2806
        tpr = self._get_registry()
 
2807
        tpr.register('foo', 'fff.ooo.ooo')
 
2808
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
2809
 
 
2810
    def test_register_existing_prefix(self):
 
2811
        tpr = self._get_registry()
 
2812
        tpr.register('bar', 'bbb.aaa.rrr')
 
2813
        tpr.register('bar', 'bBB.aAA.rRR')
 
2814
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
2815
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
2816
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
2817
 
 
2818
    def test_get_unknown_prefix(self):
 
2819
        tpr = self._get_registry()
 
2820
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
2821
 
 
2822
    def test_resolve_prefix(self):
 
2823
        tpr = self._get_registry()
 
2824
        tpr.register('bar', 'bb.aa.rr')
 
2825
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
2826
 
 
2827
    def test_resolve_unknown_alias(self):
 
2828
        tpr = self._get_registry()
 
2829
        self.assertRaises(errors.BzrCommandError,
 
2830
                          tpr.resolve_alias, 'I am not a prefix')
 
2831
 
 
2832
    def test_predefined_prefixes(self):
 
2833
        tpr = tests.test_prefix_alias_registry
 
2834
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
2835
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
2836
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
2837
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
2838
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
2839
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
2840
 
 
2841
 
 
2842
class TestRunSuite(tests.TestCase):
 
2843
 
 
2844
    def test_runner_class(self):
 
2845
        """run_suite accepts and uses a runner_class keyword argument."""
 
2846
        class Stub(tests.TestCase):
 
2847
            def test_foo(self):
 
2848
                pass
 
2849
        suite = Stub("test_foo")
 
2850
        calls = []
 
2851
        class MyRunner(tests.TextTestRunner):
 
2852
            def run(self, test):
 
2853
                calls.append(test)
 
2854
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
2855
                                                self.verbosity)
 
2856
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
2857
        self.assertLength(1, calls)
 
2858
 
 
2859
    def test_done(self):
 
2860
        """run_suite should call result.done()"""
 
2861
        self.calls = 0
 
2862
        def one_more_call(): self.calls += 1
 
2863
        def test_function():
 
2864
            pass
 
2865
        test = unittest.FunctionTestCase(test_function)
 
2866
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
2867
            def done(self): one_more_call()
 
2868
        class MyRunner(tests.TextTestRunner):
 
2869
            def run(self, test):
 
2870
                return InstrumentedTestResult(self.stream, self.descriptions,
 
2871
                                              self.verbosity)
 
2872
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
 
2873
        self.assertEquals(1, self.calls)