/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1
# Copyright (C) 2005, 2006 by Canonical Ltd
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License version 2 as published by
5
# the Free Software Foundation.
6
#
7
# This program is distributed in the hope that it will be useful,
8
# but WITHOUT ANY WARRANTY; without even the implied warranty of
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
# GNU General Public License for more details.
11
#
12
# You should have received a copy of the GNU General Public License
13
# along with this program; if not, write to the Free Software
14
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
16
"""Tests for the test framework."""
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
17
18
import os
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
19
from StringIO import StringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
20
import sys
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
21
import time
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
22
import unittest
1185.62.24 by John Arbash Meinel
Changing the exception that sftp.py throws when it can't find paramiko, so that the test suite can handle it.
23
import warnings
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
24
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
25
from bzrlib import osutils
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
26
import bzrlib
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
27
from bzrlib.progress import _BaseProgressBar
1526.1.3 by Robert Collins
Merge from upstream.
28
from bzrlib.tests import (
1534.4.31 by Robert Collins
cleanedup test_outside_wt
29
                          ChrootedTestCase,
1526.1.3 by Robert Collins
Merge from upstream.
30
                          TestCase,
31
                          TestCaseInTempDir,
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
32
                          TestCaseWithTransport,
1526.1.3 by Robert Collins
Merge from upstream.
33
                          TestSkipped,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
34
                          TestSuite,
1526.1.3 by Robert Collins
Merge from upstream.
35
                          TextTestRunner,
36
                          )
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
37
from bzrlib.tests.TestUtil import _load_module_by_name
1185.62.24 by John Arbash Meinel
Changing the exception that sftp.py throws when it can't find paramiko, so that the test suite can handle it.
38
import bzrlib.errors as errors
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
39
from bzrlib import symbol_versioning
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
40
from bzrlib.trace import note
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
41
from bzrlib.version import _get_bzr_source_tree
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
42
43
44
class SelftestTests(TestCase):
45
46
    def test_import_tests(self):
47
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
48
        self.assertEqual(mod.SelftestTests, SelftestTests)
49
50
    def test_import_test_failure(self):
51
        self.assertRaises(ImportError,
52
                          _load_module_by_name,
53
                          'bzrlib.no-name-yet')
54
55
56
class MetaTestLog(TestCase):
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
57
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
58
    def test_logging(self):
59
        """Test logs are captured when a test fails."""
60
        self.log('a test message')
61
        self._log_file.flush()
62
        self.assertContainsRe(self._get_log(), 'a test message\n')
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
63
64
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
65
class TestTreeShape(TestCaseInTempDir):
66
67
    def test_unicode_paths(self):
68
        filename = u'hell\u00d8'
1526.1.4 by Robert Collins
forgot my self.
69
        try:
70
            self.build_tree_contents([(filename, 'contents of hello')])
71
        except UnicodeEncodeError:
72
            raise TestSkipped("can't build unicode working tree in "
73
                "filesystem encoding %s" % sys.getfilesystemencoding())
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
74
        self.failUnlessExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
75
76
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
77
class TestTransportProviderAdapter(TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
78
    """A group of tests that test the transport implementation adaption core.
79
1551.1.1 by Martin Pool
[merge] branch-formats branch, and reconcile changes
80
    This is a meta test that the tests are applied to all available 
81
    transports.
82
1530.1.21 by Robert Collins
Review feedback fixes.
83
    This will be generalised in the future which is why it is in this 
84
    test file even though it is specific to transport tests at the moment.
85
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
86
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
87
    def test_get_transport_permutations(self):
1530.1.21 by Robert Collins
Review feedback fixes.
88
        # this checks that we the module get_test_permutations call
89
        # is made by the adapter get_transport_test_permitations method.
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
90
        class MockModule(object):
91
            def get_test_permutations(self):
92
                return sample_permutation
93
        sample_permutation = [(1,2), (3,4)]
94
        from bzrlib.transport import TransportTestProviderAdapter
95
        adapter = TransportTestProviderAdapter()
96
        self.assertEqual(sample_permutation,
97
                         adapter.get_transport_test_permutations(MockModule()))
98
99
    def test_adapter_checks_all_modules(self):
1530.1.21 by Robert Collins
Review feedback fixes.
100
        # this checks that the adapter returns as many permurtations as
101
        # there are in all the registered# transport modules for there
102
        # - we assume if this matches its probably doing the right thing
103
        # especially in combination with the tests for setting the right
104
        # classes below.
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
105
        from bzrlib.transport import (TransportTestProviderAdapter,
106
                                      _get_transport_modules
107
                                      )
108
        modules = _get_transport_modules()
109
        permutation_count = 0
110
        for module in modules:
1185.62.24 by John Arbash Meinel
Changing the exception that sftp.py throws when it can't find paramiko, so that the test suite can handle it.
111
            try:
112
                permutation_count += len(reduce(getattr, 
113
                    (module + ".get_test_permutations").split('.')[1:],
114
                     __import__(module))())
115
            except errors.DependencyNotPresent:
116
                pass
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
117
        input_test = TestTransportProviderAdapter(
118
            "test_adapter_sets_transport_class")
119
        adapter = TransportTestProviderAdapter()
120
        self.assertEqual(permutation_count,
121
                         len(list(iter(adapter.adapt(input_test)))))
122
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
123
    def test_adapter_sets_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
124
        # Check that the test adapter inserts a transport and server into the
125
        # generated test.
126
        #
127
        # This test used to know about all the possible transports and the
128
        # order they were returned but that seems overly brittle (mbp
129
        # 20060307)
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
130
        input_test = TestTransportProviderAdapter(
131
            "test_adapter_sets_transport_class")
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
132
        from bzrlib.transport import TransportTestProviderAdapter
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
133
        suite = TransportTestProviderAdapter().adapt(input_test)
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
134
        tests = list(iter(suite))
135
        self.assertTrue(len(tests) > 6)
136
        # there are at least that many builtin transports
137
        one_test = tests[0]
138
        self.assertTrue(issubclass(one_test.transport_class, 
139
                                   bzrlib.transport.Transport))
140
        self.assertTrue(issubclass(one_test.transport_server, 
141
                                   bzrlib.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
142
143
144
class TestBranchProviderAdapter(TestCase):
145
    """A group of tests that test the branch implementation test adapter."""
146
147
    def test_adapted_tests(self):
148
        # check that constructor parameters are passed through to the adapted
149
        # test.
150
        from bzrlib.branch import BranchTestProviderAdapter
151
        input_test = TestBranchProviderAdapter(
152
            "test_adapted_tests")
153
        server1 = "a"
154
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
155
        formats = [("c", "C"), ("d", "D")]
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
156
        adapter = BranchTestProviderAdapter(server1, server2, formats)
157
        suite = adapter.adapt(input_test)
158
        tests = list(iter(suite))
159
        self.assertEqual(2, len(tests))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
160
        self.assertEqual(tests[0].branch_format, formats[0][0])
161
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
162
        self.assertEqual(tests[0].transport_server, server1)
163
        self.assertEqual(tests[0].transport_readonly_server, server2)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
164
        self.assertEqual(tests[1].branch_format, formats[1][0])
165
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
166
        self.assertEqual(tests[1].transport_server, server1)
167
        self.assertEqual(tests[1].transport_readonly_server, server2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
168
169
1534.4.39 by Robert Collins
Basic BzrDir support.
170
class TestBzrDirProviderAdapter(TestCase):
171
    """A group of tests that test the bzr dir implementation test adapter."""
172
173
    def test_adapted_tests(self):
174
        # check that constructor parameters are passed through to the adapted
175
        # test.
176
        from bzrlib.bzrdir import BzrDirTestProviderAdapter
177
        input_test = TestBzrDirProviderAdapter(
178
            "test_adapted_tests")
179
        server1 = "a"
180
        server2 = "b"
181
        formats = ["c", "d"]
182
        adapter = BzrDirTestProviderAdapter(server1, server2, formats)
183
        suite = adapter.adapt(input_test)
184
        tests = list(iter(suite))
185
        self.assertEqual(2, len(tests))
186
        self.assertEqual(tests[0].bzrdir_format, formats[0])
187
        self.assertEqual(tests[0].transport_server, server1)
188
        self.assertEqual(tests[0].transport_readonly_server, server2)
189
        self.assertEqual(tests[1].bzrdir_format, formats[1])
190
        self.assertEqual(tests[1].transport_server, server1)
191
        self.assertEqual(tests[1].transport_readonly_server, server2)
192
193
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
194
class TestRepositoryProviderAdapter(TestCase):
195
    """A group of tests that test the repository implementation test adapter."""
196
197
    def test_adapted_tests(self):
198
        # check that constructor parameters are passed through to the adapted
199
        # test.
200
        from bzrlib.repository import RepositoryTestProviderAdapter
201
        input_test = TestRepositoryProviderAdapter(
202
            "test_adapted_tests")
203
        server1 = "a"
204
        server2 = "b"
205
        formats = [("c", "C"), ("d", "D")]
206
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
207
        suite = adapter.adapt(input_test)
208
        tests = list(iter(suite))
209
        self.assertEqual(2, len(tests))
210
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
211
        self.assertEqual(tests[0].repository_format, formats[0][0])
212
        self.assertEqual(tests[0].transport_server, server1)
213
        self.assertEqual(tests[0].transport_readonly_server, server2)
214
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
215
        self.assertEqual(tests[1].repository_format, formats[1][0])
216
        self.assertEqual(tests[1].transport_server, server1)
217
        self.assertEqual(tests[1].transport_readonly_server, server2)
218
219
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
220
class TestInterRepositoryProviderAdapter(TestCase):
221
    """A group of tests that test the InterRepository test adapter."""
222
223
    def test_adapted_tests(self):
224
        # check that constructor parameters are passed through to the adapted
225
        # test.
226
        from bzrlib.repository import InterRepositoryTestProviderAdapter
227
        input_test = TestInterRepositoryProviderAdapter(
228
            "test_adapted_tests")
229
        server1 = "a"
230
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
231
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
232
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
233
        suite = adapter.adapt(input_test)
234
        tests = list(iter(suite))
235
        self.assertEqual(2, len(tests))
236
        self.assertEqual(tests[0].interrepo_class, formats[0][0])
237
        self.assertEqual(tests[0].repository_format, formats[0][1])
238
        self.assertEqual(tests[0].repository_format_to, formats[0][2])
239
        self.assertEqual(tests[0].transport_server, server1)
240
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
241
        self.assertEqual(tests[1].interrepo_class, formats[1][0])
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
242
        self.assertEqual(tests[1].repository_format, formats[1][1])
243
        self.assertEqual(tests[1].repository_format_to, formats[1][2])
244
        self.assertEqual(tests[1].transport_server, server1)
245
        self.assertEqual(tests[1].transport_readonly_server, server2)
246
247
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
248
class TestInterVersionedFileProviderAdapter(TestCase):
249
    """A group of tests that test the InterVersionedFile test adapter."""
250
251
    def test_adapted_tests(self):
252
        # check that constructor parameters are passed through to the adapted
253
        # test.
254
        from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
255
        input_test = TestInterRepositoryProviderAdapter(
256
            "test_adapted_tests")
257
        server1 = "a"
258
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
259
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
260
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
261
        suite = adapter.adapt(input_test)
262
        tests = list(iter(suite))
263
        self.assertEqual(2, len(tests))
264
        self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
265
        self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
266
        self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
267
        self.assertEqual(tests[0].transport_server, server1)
268
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
269
        self.assertEqual(tests[1].interversionedfile_class, formats[1][0])
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
270
        self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
271
        self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
272
        self.assertEqual(tests[1].transport_server, server1)
273
        self.assertEqual(tests[1].transport_readonly_server, server2)
274
275
1563.2.20 by Robert Collins
Add a revision store test adapter.
276
class TestRevisionStoreProviderAdapter(TestCase):
277
    """A group of tests that test the RevisionStore test adapter."""
278
279
    def test_adapted_tests(self):
280
        # check that constructor parameters are passed through to the adapted
281
        # test.
282
        from bzrlib.store.revision import RevisionStoreTestProviderAdapter
283
        input_test = TestRevisionStoreProviderAdapter(
284
            "test_adapted_tests")
285
        # revision stores need a store factory - i.e. RevisionKnit
286
        #, a readonly and rw transport 
287
        # transport servers:
288
        server1 = "a"
289
        server2 = "b"
290
        store_factories = ["c", "d"]
291
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
292
        suite = adapter.adapt(input_test)
293
        tests = list(iter(suite))
294
        self.assertEqual(2, len(tests))
295
        self.assertEqual(tests[0].store_factory, store_factories[0][0])
296
        self.assertEqual(tests[0].transport_server, server1)
297
        self.assertEqual(tests[0].transport_readonly_server, server2)
298
        self.assertEqual(tests[1].store_factory, store_factories[1][0])
299
        self.assertEqual(tests[1].transport_server, server1)
300
        self.assertEqual(tests[1].transport_readonly_server, server2)
301
302
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
303
class TestWorkingTreeProviderAdapter(TestCase):
304
    """A group of tests that test the workingtree implementation test adapter."""
305
306
    def test_adapted_tests(self):
307
        # check that constructor parameters are passed through to the adapted
308
        # test.
309
        from bzrlib.workingtree import WorkingTreeTestProviderAdapter
310
        input_test = TestWorkingTreeProviderAdapter(
311
            "test_adapted_tests")
312
        server1 = "a"
313
        server2 = "b"
314
        formats = [("c", "C"), ("d", "D")]
315
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
316
        suite = adapter.adapt(input_test)
317
        tests = list(iter(suite))
318
        self.assertEqual(2, len(tests))
319
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
320
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
321
        self.assertEqual(tests[0].transport_server, server1)
322
        self.assertEqual(tests[0].transport_readonly_server, server2)
323
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
324
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
325
        self.assertEqual(tests[1].transport_server, server1)
326
        self.assertEqual(tests[1].transport_readonly_server, server2)
327
328
1852.6.1 by Robert Collins
Start tree implementation tests.
329
class TestTreeProviderAdapter(TestCase):
330
    """Test the setup of tree_implementation tests."""
331
332
    def test_adapted_tests(self):
333
        # the tree implementation adapter is meant to setup one instance for
334
        # each working tree format, and one additional instance that will
335
        # use the default wt format, but create a revision tree for the tests.
336
        # this means that the wt ones should have the workingtree_to_test_tree
337
        # attribute set to 'return_parameter' and the revision one set to
338
        # revision_tree_from_workingtree.
339
340
        from bzrlib.tests.tree_implementations import (
341
            TreeTestProviderAdapter,
342
            return_parameter,
343
            revision_tree_from_workingtree
344
            )
345
        from bzrlib.workingtree import WorkingTreeFormat
346
        input_test = TestTreeProviderAdapter(
347
            "test_adapted_tests")
348
        server1 = "a"
349
        server2 = "b"
350
        formats = [("c", "C"), ("d", "D")]
351
        adapter = TreeTestProviderAdapter(server1, server2, formats)
352
        suite = adapter.adapt(input_test)
353
        tests = list(iter(suite))
354
        self.assertEqual(3, len(tests))
355
        default_format = WorkingTreeFormat.get_default_format()
356
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
357
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
358
        self.assertEqual(tests[0].transport_server, server1)
359
        self.assertEqual(tests[0].transport_readonly_server, server2)
360
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
361
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
362
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
363
        self.assertEqual(tests[1].transport_server, server1)
364
        self.assertEqual(tests[1].transport_readonly_server, server2)
365
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
366
        self.assertEqual(tests[2].workingtree_format, default_format)
367
        self.assertEqual(tests[2].bzrdir_format, default_format._matchingbzrdir)
368
        self.assertEqual(tests[2].transport_server, server1)
369
        self.assertEqual(tests[2].transport_readonly_server, server2)
370
        self.assertEqual(tests[2].workingtree_to_test_tree,
371
            revision_tree_from_workingtree)
372
373
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
374
class TestInterTreeProviderAdapter(TestCase):
375
    """A group of tests that test the InterTreeTestAdapter."""
376
377
    def test_adapted_tests(self):
378
        # check that constructor parameters are passed through to the adapted
379
        # test.
380
        # for InterTree tests we want the machinery to bring up two trees in
381
        # each instance: the base one, and the one we are interacting with.
382
        # because each optimiser can be direction specific, we need to test
383
        # each optimiser in its chosen direction.
384
        # unlike the TestProviderAdapter we dont want to automatically add a
385
        # parameterised one for WorkingTree - the optimisers will tell us what
386
        # ones to add.
387
        from bzrlib.tests.tree_implementations import (
388
            return_parameter,
389
            revision_tree_from_workingtree
390
            )
391
        from bzrlib.tests.intertree_implementations import (
392
            InterTreeTestProviderAdapter,
393
            )
394
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
395
        input_test = TestInterTreeProviderAdapter(
396
            "test_adapted_tests")
397
        server1 = "a"
398
        server2 = "b"
399
        format1 = WorkingTreeFormat2()
400
        format2 = WorkingTreeFormat3()
401
        formats = [(str, format1, format2, False, True),
402
            (int, format2, format1, False, True)]
403
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
404
        suite = adapter.adapt(input_test)
405
        tests = list(iter(suite))
406
        self.assertEqual(2, len(tests))
407
        self.assertEqual(tests[0].intertree_class, formats[0][0])
408
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
409
        self.assertEqual(tests[0].workingtree_to_test_tree, formats[0][2])
410
        self.assertEqual(tests[0].workingtree_format_to, formats[0][3])
411
        self.assertEqual(tests[0].workingtree_to_test_tree_to, formats[0][4])
412
        self.assertEqual(tests[0].transport_server, server1)
413
        self.assertEqual(tests[0].transport_readonly_server, server2)
414
        self.assertEqual(tests[1].intertree_class, formats[1][0])
415
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
416
        self.assertEqual(tests[1].workingtree_to_test_tree, formats[1][2])
417
        self.assertEqual(tests[1].workingtree_format_to, formats[1][3])
418
        self.assertEqual(tests[1].workingtree_to_test_tree_to, formats[1][4])
419
        self.assertEqual(tests[1].transport_server, server1)
420
        self.assertEqual(tests[1].transport_readonly_server, server2)
421
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
422
class TestTestCaseWithTransport(TestCaseWithTransport):
423
    """Tests for the convenience functions TestCaseWithTransport introduces."""
424
425
    def test_get_readonly_url_none(self):
426
        from bzrlib.transport import get_transport
427
        from bzrlib.transport.memory import MemoryServer
428
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
429
        self.transport_server = MemoryServer
430
        self.transport_readonly_server = None
431
        # calling get_readonly_transport() constructs a decorator on the url
432
        # for the server
433
        url = self.get_readonly_url()
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
434
        url2 = self.get_readonly_url('foo/bar')
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
435
        t = get_transport(url)
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
436
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
437
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
438
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
439
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
440
441
    def test_get_readonly_url_http(self):
442
        from bzrlib.transport import get_transport
443
        from bzrlib.transport.local import LocalRelpathServer
1540.3.6 by Martin Pool
[merge] update from bzr.dev
444
        from bzrlib.transport.http import HttpServer, HttpTransportBase
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
445
        self.transport_server = LocalRelpathServer
446
        self.transport_readonly_server = HttpServer
447
        # calling get_readonly_transport() gives us a HTTP server instance.
448
        url = self.get_readonly_url()
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
449
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
450
        # the transport returned may be any HttpTransportBase subclass
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
451
        t = get_transport(url)
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
452
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
453
        self.failUnless(isinstance(t, HttpTransportBase))
454
        self.failUnless(isinstance(t2, HttpTransportBase))
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
455
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
456
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
457
    def test_is_directory(self):
458
        """Test assertIsDirectory assertion"""
459
        t = self.get_transport()
460
        self.build_tree(['a_dir/', 'a_file'], transport=t)
461
        self.assertIsDirectory('a_dir', t)
462
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
463
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
464
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
465
1534.4.31 by Robert Collins
cleanedup test_outside_wt
466
class TestChrootedTest(ChrootedTestCase):
467
468
    def test_root_is_root(self):
469
        from bzrlib.transport import get_transport
470
        t = get_transport(self.get_readonly_url())
471
        url = t.base
472
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
473
474
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
475
class MockProgress(_BaseProgressBar):
476
    """Progress-bar standin that records calls.
477
478
    Useful for testing pb using code.
479
    """
480
481
    def __init__(self):
482
        _BaseProgressBar.__init__(self)
483
        self.calls = []
484
485
    def tick(self):
486
        self.calls.append(('tick',))
487
488
    def update(self, msg=None, current=None, total=None):
489
        self.calls.append(('update', msg, current, total))
490
491
    def clear(self):
492
        self.calls.append(('clear',))
493
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
494
    def note(self, msg, *args):
495
        self.calls.append(('note', msg, args))
496
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
497
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
498
class TestTestResult(TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
499
500
    def test_progress_bar_style_quiet(self):
501
        # test using a progress bar.
1728.1.2 by Robert Collins
Bugfix missing search-and-replace of TestResult.
502
        dummy_test = TestTestResult('test_progress_bar_style_quiet')
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
503
        dummy_error = (Exception, None, [])
504
        mypb = MockProgress()
505
        mypb.update('Running tests', 0, 4)
506
        last_calls = mypb.calls[:]
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
507
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
508
        result = bzrlib.tests._MyResult(self._log_file,
509
                                        descriptions=0,
510
                                        verbosity=1,
511
                                        pb=mypb)
512
        self.assertEqual(last_calls, mypb.calls)
513
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
514
        def shorten(s):
515
            """Shorten a string based on the terminal width"""
516
            return result._ellipsise_unimportant_words(s,
517
                                 osutils.terminal_width())
518
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
519
        # an error 
520
        result.startTest(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
521
        # starting a test prints the test name
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
522
        last_calls += [('update', '...tyle_quiet', 0, None)]
523
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
524
        result.addError(dummy_test, dummy_error)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
525
        last_calls += [('update', 'ERROR        ', 1, None),
526
                       ('note', shorten(dummy_test.id() + ': ERROR'), ())
527
                      ]
528
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
529
530
        # a failure
531
        result.startTest(dummy_test)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
532
        last_calls += [('update', '...tyle_quiet', 1, None)]
533
        self.assertEqual(last_calls, mypb.calls)
534
        last_calls += [('update', 'FAIL         ', 2, None),
535
                       ('note', shorten(dummy_test.id() + ': FAIL'), ())
536
                      ]
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
537
        result.addFailure(dummy_test, dummy_error)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
538
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
539
540
        # a success
541
        result.startTest(dummy_test)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
542
        last_calls += [('update', '...tyle_quiet', 2, None)]
543
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
544
        result.addSuccess(dummy_test)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
545
        last_calls += [('update', 'OK           ', 3, None)]
546
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
547
548
        # a skip
549
        result.startTest(dummy_test)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
550
        last_calls += [('update', '...tyle_quiet', 3, None)]
551
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
552
        result.addSkipped(dummy_test, dummy_error)
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
553
        last_calls += [('update', 'SKIP         ', 4, None)]
554
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
555
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
556
    def test_elapsed_time_with_benchmarking(self):
557
        result = bzrlib.tests._MyResult(self._log_file,
558
                                        descriptions=0,
559
                                        verbosity=1,
560
                                        )
561
        result._recordTestStartTime()
562
        time.sleep(0.003)
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
563
        result.extractBenchmarkTime(self)
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
564
        timed_string = result._testTimeString()
565
        # without explicit benchmarking, we should get a simple time.
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
566
        self.assertContainsRe(timed_string, "^         [ 1-9][0-9]ms$")
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
567
        # if a benchmark time is given, we want a x of y style result.
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
568
        self.time(time.sleep, 0.001)
569
        result.extractBenchmarkTime(self)
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
570
        timed_string = result._testTimeString()
1740.2.5 by Aaron Bentley
Merge from bzr.dev
571
        self.assertContainsRe(timed_string, "^   [ 1-9][0-9]ms/   [ 1-9][0-9]ms$")
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
572
        # extracting the time from a non-bzrlib testcase sets to None
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
573
        result._recordTestStartTime()
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
574
        result.extractBenchmarkTime(
575
            unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
576
        timed_string = result._testTimeString()
1740.2.5 by Aaron Bentley
Merge from bzr.dev
577
        self.assertContainsRe(timed_string, "^         [ 1-9][0-9]ms$")
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
578
        # cheat. Yes, wash thy mouth out with soap.
579
        self._benchtime = None
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
580
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
581
    def test_assigned_benchmark_file_stores_date(self):
582
        output = StringIO()
583
        result = bzrlib.tests._MyResult(self._log_file,
584
                                        descriptions=0,
585
                                        verbosity=1,
586
                                        bench_history=output
587
                                        )
588
        output_string = output.getvalue()
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
589
        # if you are wondering about the regexp please read the comment in
590
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
1951.1.2 by Andrew Bennetts
Relax test_assigned_benchmark_file_stores_date's regexp the same way we relaxed test_bench_history's.
591
        # XXX: what comment?  -- Andrew Bennetts
592
        self.assertContainsRe(output_string, "--date [0-9.]+")
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
593
594
    def test_benchhistory_records_test_times(self):
595
        result_stream = StringIO()
596
        result = bzrlib.tests._MyResult(
597
            self._log_file,
598
            descriptions=0,
599
            verbosity=1,
600
            bench_history=result_stream
601
            )
602
603
        # we want profile a call and check that its test duration is recorded
604
        # make a new test instance that when run will generate a benchmark
605
        example_test_case = TestTestResult("_time_hello_world_encoding")
606
        # execute the test, which should succeed and record times
607
        example_test_case.run(result)
608
        lines = result_stream.getvalue().splitlines()
609
        self.assertEqual(2, len(lines))
610
        self.assertContainsRe(lines[1],
611
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
612
            "._time_hello_world_encoding")
613
 
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
614
    def _time_hello_world_encoding(self):
615
        """Profile two sleep calls
616
        
617
        This is used to exercise the test framework.
618
        """
619
        self.time(unicode, 'hello', errors='replace')
620
        self.time(unicode, 'world', errors='replace')
621
622
    def test_lsprofiling(self):
623
        """Verbose test result prints lsprof statistics from test cases."""
624
        try:
625
            import bzrlib.lsprof
626
        except ImportError:
627
            raise TestSkipped("lsprof not installed.")
628
        result_stream = StringIO()
629
        result = bzrlib.tests._MyResult(
630
            unittest._WritelnDecorator(result_stream),
631
            descriptions=0,
632
            verbosity=2,
633
            )
634
        # we want profile a call of some sort and check it is output by
635
        # addSuccess. We dont care about addError or addFailure as they
636
        # are not that interesting for performance tuning.
637
        # make a new test instance that when run will generate a profile
638
        example_test_case = TestTestResult("_time_hello_world_encoding")
639
        example_test_case._gather_lsprof_in_benchmarks = True
640
        # execute the test, which should succeed and record profiles
641
        example_test_case.run(result)
642
        # lsprofile_something()
643
        # if this worked we want 
644
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
645
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
646
        # (the lsprof header)
647
        # ... an arbitrary number of lines
648
        # and the function call which is time.sleep.
649
        #           1        0            ???         ???       ???(sleep) 
650
        # and then repeated but with 'world', rather than 'hello'.
651
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
652
        output = result_stream.getvalue()
653
        self.assertContainsRe(output,
654
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
655
        self.assertContainsRe(output,
656
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
657
        self.assertContainsRe(output,
658
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
659
        self.assertContainsRe(output,
660
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
661
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
662
663
class TestRunner(TestCase):
664
665
    def dummy_test(self):
666
        pass
667
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
668
    def run_test_runner(self, testrunner, test):
669
        """Run suite in testrunner, saving global state and restoring it.
670
671
        This current saves and restores:
672
        TestCaseInTempDir.TEST_ROOT
673
        
674
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
675
        without using this convenience method, because of our use of global state.
676
        """
677
        old_root = TestCaseInTempDir.TEST_ROOT
678
        try:
679
            TestCaseInTempDir.TEST_ROOT = None
680
            return testrunner.run(test)
681
        finally:
682
            TestCaseInTempDir.TEST_ROOT = old_root
683
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
684
    def test_accepts_and_uses_pb_parameter(self):
685
        test = TestRunner('dummy_test')
686
        mypb = MockProgress()
687
        self.assertEqual([], mypb.calls)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
688
        runner = TextTestRunner(stream=self._log_file, pb=mypb)
689
        result = self.run_test_runner(runner, test)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
690
        self.assertEqual(1, result.testsRun)
691
        self.assertEqual(('update', 'Running tests', 0, 1), mypb.calls[0])
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
692
        self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
693
        self.assertEqual(('update', 'OK           ', 1, None), mypb.calls[2])
694
        self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
695
        self.assertEqual(('clear',), mypb.calls[4])
696
        self.assertEqual(5, len(mypb.calls))
1534.11.4 by Robert Collins
Merge from mainline.
697
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
698
    def test_skipped_test(self):
699
        # run a test that is skipped, and check the suite as a whole still
700
        # succeeds.
701
        # skipping_test must be hidden in here so it's not run as a real test
702
        def skipping_test():
703
            raise TestSkipped('test intentionally skipped')
704
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
705
        test = unittest.FunctionTestCase(skipping_test)
706
        result = self.run_test_runner(runner, test)
707
        self.assertTrue(result.wasSuccessful())
708
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
709
    def test_bench_history(self):
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
710
        # tests that the running the benchmark produces a history file
711
        # containing a timestamp and the revision id of the bzrlib source which
712
        # was tested.
713
        workingtree = _get_bzr_source_tree()
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
714
        test = TestRunner('dummy_test')
715
        output = StringIO()
716
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
717
        result = self.run_test_runner(runner, test)
718
        output_string = output.getvalue()
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
719
        self.assertContainsRe(output_string, "--date [0-9.]+")
720
        if workingtree is not None:
721
            revision_id = workingtree.last_revision()
722
            self.assertEndsWith(output_string.rstrip(), revision_id)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
723
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
724
725
class TestTestCase(TestCase):
726
    """Tests that test the core bzrlib TestCase."""
727
728
    def inner_test(self):
729
        # the inner child test
730
        note("inner_test")
731
732
    def outer_child(self):
733
        # the outer child test
734
        note("outer_start")
735
        self.inner_test = TestTestCase("inner_child")
736
        result = bzrlib.tests._MyResult(self._log_file,
737
                                        descriptions=0,
738
                                        verbosity=1)
739
        self.inner_test.run(result)
740
        note("outer finish")
741
742
    def test_trace_nesting(self):
743
        # this tests that each test case nests its trace facility correctly.
744
        # we do this by running a test case manually. That test case (A)
745
        # should setup a new log, log content to it, setup a child case (B),
746
        # which should log independently, then case (A) should log a trailer
747
        # and return.
748
        # we do two nested children so that we can verify the state of the 
749
        # logs after the outer child finishes is correct, which a bad clean
750
        # up routine in tearDown might trigger a fault in our test with only
751
        # one child, we should instead see the bad result inside our test with
752
        # the two children.
753
        # the outer child test
754
        original_trace = bzrlib.trace._trace_file
755
        outer_test = TestTestCase("outer_child")
756
        result = bzrlib.tests._MyResult(self._log_file,
757
                                        descriptions=0,
758
                                        verbosity=1)
759
        outer_test.run(result)
760
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
761
762
    def method_that_times_a_bit_twice(self):
763
        # call self.time twice to ensure it aggregates
1713.1.4 by Robert Collins
Make the test test_time_creates_benchmark_in_result more robust to timing variation.
764
        self.time(time.sleep, 0.007)
765
        self.time(time.sleep, 0.007)
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
766
767
    def test_time_creates_benchmark_in_result(self):
768
        """Test that the TestCase.time() method accumulates a benchmark time."""
769
        sample_test = TestTestCase("method_that_times_a_bit_twice")
770
        output_stream = StringIO()
771
        result = bzrlib.tests._MyResult(
772
            unittest._WritelnDecorator(output_stream),
773
            descriptions=0,
774
            verbosity=2)
775
        sample_test.run(result)
776
        self.assertContainsRe(
777
            output_stream.getvalue(),
778
            "[1-9][0-9]ms/   [1-9][0-9]ms\n$")
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
779
        
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
780
    def test__gather_lsprof_in_benchmarks(self):
781
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
782
        
783
        Each self.time() call is individually and separately profiled.
784
        """
785
        try:
786
            import bzrlib.lsprof
787
        except ImportError:
788
            raise TestSkipped("lsprof not installed.")
789
        # overrides the class member with an instance member so no cleanup 
790
        # needed.
791
        self._gather_lsprof_in_benchmarks = True
792
        self.time(time.sleep, 0.000)
793
        self.time(time.sleep, 0.003)
794
        self.assertEqual(2, len(self._benchcalls))
795
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
796
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
797
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
798
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
799
1534.11.4 by Robert Collins
Merge from mainline.
800
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
801
class TestExtraAssertions(TestCase):
802
    """Tests for new test assertions in bzrlib test suite"""
803
804
    def test_assert_isinstance(self):
805
        self.assertIsInstance(2, int)
806
        self.assertIsInstance(u'', basestring)
807
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
808
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
809
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
810
    def test_assertEndsWith(self):
811
        self.assertEndsWith('foo', 'oo')
812
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
813
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
814
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
815
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
816
            if be_deprecated is True:
817
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
818
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
819
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
820
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
821
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
822
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
823
        self.assertEqual('result', result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
824
        self.callDeprecated(['i am deprecated'], testfunc, 
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
825
                              be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
826
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
827
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
828
829
class TestConvenienceMakers(TestCaseWithTransport):
830
    """Test for the make_* convenience functions."""
831
832
    def test_make_branch_and_tree_with_format(self):
833
        # we should be able to supply a format to make_branch_and_tree
834
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
835
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
836
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
837
                              bzrlib.bzrdir.BzrDirMetaFormat1)
838
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
839
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
840
841
842
class TestSelftest(TestCase):
843
    """Tests of bzrlib.tests.selftest."""
844
845
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
846
        factory_called = []
847
        def factory():
848
            factory_called.append(True)
849
            return TestSuite()
850
        out = StringIO()
851
        err = StringIO()
852
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
853
            test_suite_factory=factory)
854
        self.assertEqual([True], factory_called)