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