/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005, 2006 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
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
17
"""Tests for the test framework."""
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
18
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
19
import cStringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
20
import os
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
21
from StringIO import StringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
22
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).
23
import time
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
24
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.
25
import warnings
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
26
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.
27
import bzrlib
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
28
from bzrlib import (
29
    bzrdir,
30
    memorytree,
31
    osutils,
32
    repository,
33
    )
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
34
from bzrlib.progress import _BaseProgressBar
1526.1.3 by Robert Collins
Merge from upstream.
35
from bzrlib.tests import (
1534.4.31 by Robert Collins
cleanedup test_outside_wt
36
                          ChrootedTestCase,
1526.1.3 by Robert Collins
Merge from upstream.
37
                          TestCase,
38
                          TestCaseInTempDir,
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
39
                          TestCaseWithMemoryTransport,
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
40
                          TestCaseWithTransport,
1526.1.3 by Robert Collins
Merge from upstream.
41
                          TestSkipped,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
42
                          TestSuite,
1526.1.3 by Robert Collins
Merge from upstream.
43
                          TextTestRunner,
44
                          )
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
45
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
46
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.
47
import bzrlib.errors as errors
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
48
from bzrlib import symbol_versioning
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
49
from bzrlib.symbol_versioning import zero_ten, zero_eleven
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
50
from bzrlib.trace import note
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
51
from bzrlib.transport.memory import MemoryServer, MemoryTransport
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
52
from bzrlib.version import _get_bzr_source_tree
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
53
54
55
class SelftestTests(TestCase):
56
57
    def test_import_tests(self):
58
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
59
        self.assertEqual(mod.SelftestTests, SelftestTests)
60
61
    def test_import_test_failure(self):
62
        self.assertRaises(ImportError,
63
                          _load_module_by_name,
64
                          'bzrlib.no-name-yet')
65
66
67
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.
68
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
69
    def test_logging(self):
70
        """Test logs are captured when a test fails."""
71
        self.log('a test message')
72
        self._log_file.flush()
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
73
        self.assertContainsRe(self._get_log(keep_log_file=True),
74
                              'a test message\n')
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
75
76
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.
77
class TestTreeShape(TestCaseInTempDir):
78
79
    def test_unicode_paths(self):
80
        filename = u'hell\u00d8'
1526.1.4 by Robert Collins
forgot my self.
81
        try:
82
            self.build_tree_contents([(filename, 'contents of hello')])
83
        except UnicodeEncodeError:
84
            raise TestSkipped("can't build unicode working tree in "
85
                "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.
86
        self.failUnlessExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
87
88
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
89
class TestTransportProviderAdapter(TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
90
    """A group of tests that test the transport implementation adaption core.
91
1551.1.1 by Martin Pool
[merge] branch-formats branch, and reconcile changes
92
    This is a meta test that the tests are applied to all available 
93
    transports.
94
1530.1.21 by Robert Collins
Review feedback fixes.
95
    This will be generalised in the future which is why it is in this 
96
    test file even though it is specific to transport tests at the moment.
97
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
98
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.
99
    def test_get_transport_permutations(self):
1530.1.21 by Robert Collins
Review feedback fixes.
100
        # this checks that we the module get_test_permutations call
101
        # 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.
102
        class MockModule(object):
103
            def get_test_permutations(self):
104
                return sample_permutation
105
        sample_permutation = [(1,2), (3,4)]
106
        from bzrlib.transport import TransportTestProviderAdapter
107
        adapter = TransportTestProviderAdapter()
108
        self.assertEqual(sample_permutation,
109
                         adapter.get_transport_test_permutations(MockModule()))
110
111
    def test_adapter_checks_all_modules(self):
1530.1.21 by Robert Collins
Review feedback fixes.
112
        # this checks that the adapter returns as many permurtations as
113
        # there are in all the registered# transport modules for there
114
        # - we assume if this matches its probably doing the right thing
115
        # especially in combination with the tests for setting the right
116
        # 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.
117
        from bzrlib.transport import (TransportTestProviderAdapter,
118
                                      _get_transport_modules
119
                                      )
120
        modules = _get_transport_modules()
121
        permutation_count = 0
122
        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.
123
            try:
124
                permutation_count += len(reduce(getattr, 
125
                    (module + ".get_test_permutations").split('.')[1:],
126
                     __import__(module))())
127
            except errors.DependencyNotPresent:
128
                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.
129
        input_test = TestTransportProviderAdapter(
130
            "test_adapter_sets_transport_class")
131
        adapter = TransportTestProviderAdapter()
132
        self.assertEqual(permutation_count,
133
                         len(list(iter(adapter.adapt(input_test)))))
134
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
135
    def test_adapter_sets_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
136
        # Check that the test adapter inserts a transport and server into the
137
        # generated test.
138
        #
139
        # This test used to know about all the possible transports and the
140
        # order they were returned but that seems overly brittle (mbp
141
        # 20060307)
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
142
        input_test = TestTransportProviderAdapter(
143
            "test_adapter_sets_transport_class")
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
144
        from bzrlib.transport import TransportTestProviderAdapter
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
145
        suite = TransportTestProviderAdapter().adapt(input_test)
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
146
        tests = list(iter(suite))
147
        self.assertTrue(len(tests) > 6)
148
        # there are at least that many builtin transports
149
        one_test = tests[0]
150
        self.assertTrue(issubclass(one_test.transport_class, 
151
                                   bzrlib.transport.Transport))
152
        self.assertTrue(issubclass(one_test.transport_server, 
153
                                   bzrlib.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
154
155
156
class TestBranchProviderAdapter(TestCase):
157
    """A group of tests that test the branch implementation test adapter."""
158
159
    def test_adapted_tests(self):
160
        # check that constructor parameters are passed through to the adapted
161
        # test.
162
        from bzrlib.branch import BranchTestProviderAdapter
163
        input_test = TestBranchProviderAdapter(
164
            "test_adapted_tests")
165
        server1 = "a"
166
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
167
        formats = [("c", "C"), ("d", "D")]
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
168
        adapter = BranchTestProviderAdapter(server1, server2, formats)
169
        suite = adapter.adapt(input_test)
170
        tests = list(iter(suite))
171
        self.assertEqual(2, len(tests))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
172
        self.assertEqual(tests[0].branch_format, formats[0][0])
173
        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.
174
        self.assertEqual(tests[0].transport_server, server1)
175
        self.assertEqual(tests[0].transport_readonly_server, server2)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
176
        self.assertEqual(tests[1].branch_format, formats[1][0])
177
        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.
178
        self.assertEqual(tests[1].transport_server, server1)
179
        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.
180
181
1534.4.39 by Robert Collins
Basic BzrDir support.
182
class TestBzrDirProviderAdapter(TestCase):
183
    """A group of tests that test the bzr dir implementation test adapter."""
184
185
    def test_adapted_tests(self):
186
        # check that constructor parameters are passed through to the adapted
187
        # test.
188
        from bzrlib.bzrdir import BzrDirTestProviderAdapter
189
        input_test = TestBzrDirProviderAdapter(
190
            "test_adapted_tests")
191
        server1 = "a"
192
        server2 = "b"
193
        formats = ["c", "d"]
194
        adapter = BzrDirTestProviderAdapter(server1, server2, formats)
195
        suite = adapter.adapt(input_test)
196
        tests = list(iter(suite))
197
        self.assertEqual(2, len(tests))
198
        self.assertEqual(tests[0].bzrdir_format, formats[0])
199
        self.assertEqual(tests[0].transport_server, server1)
200
        self.assertEqual(tests[0].transport_readonly_server, server2)
201
        self.assertEqual(tests[1].bzrdir_format, formats[1])
202
        self.assertEqual(tests[1].transport_server, server1)
203
        self.assertEqual(tests[1].transport_readonly_server, server2)
204
205
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
206
class TestRepositoryProviderAdapter(TestCase):
207
    """A group of tests that test the repository implementation test adapter."""
208
209
    def test_adapted_tests(self):
210
        # check that constructor parameters are passed through to the adapted
211
        # test.
212
        from bzrlib.repository import RepositoryTestProviderAdapter
213
        input_test = TestRepositoryProviderAdapter(
214
            "test_adapted_tests")
215
        server1 = "a"
216
        server2 = "b"
217
        formats = [("c", "C"), ("d", "D")]
218
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
219
        suite = adapter.adapt(input_test)
220
        tests = list(iter(suite))
221
        self.assertEqual(2, len(tests))
222
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
223
        self.assertEqual(tests[0].repository_format, formats[0][0])
224
        self.assertEqual(tests[0].transport_server, server1)
225
        self.assertEqual(tests[0].transport_readonly_server, server2)
226
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
227
        self.assertEqual(tests[1].repository_format, formats[1][0])
228
        self.assertEqual(tests[1].transport_server, server1)
229
        self.assertEqual(tests[1].transport_readonly_server, server2)
230
231
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
232
class TestInterRepositoryProviderAdapter(TestCase):
233
    """A group of tests that test the InterRepository test adapter."""
234
235
    def test_adapted_tests(self):
236
        # check that constructor parameters are passed through to the adapted
237
        # test.
238
        from bzrlib.repository import InterRepositoryTestProviderAdapter
239
        input_test = TestInterRepositoryProviderAdapter(
240
            "test_adapted_tests")
241
        server1 = "a"
242
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
243
        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.
244
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
245
        suite = adapter.adapt(input_test)
246
        tests = list(iter(suite))
247
        self.assertEqual(2, len(tests))
248
        self.assertEqual(tests[0].interrepo_class, formats[0][0])
249
        self.assertEqual(tests[0].repository_format, formats[0][1])
250
        self.assertEqual(tests[0].repository_format_to, formats[0][2])
251
        self.assertEqual(tests[0].transport_server, server1)
252
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
253
        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.
254
        self.assertEqual(tests[1].repository_format, formats[1][1])
255
        self.assertEqual(tests[1].repository_format_to, formats[1][2])
256
        self.assertEqual(tests[1].transport_server, server1)
257
        self.assertEqual(tests[1].transport_readonly_server, server2)
258
259
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
class TestInterVersionedFileProviderAdapter(TestCase):
261
    """A group of tests that test the InterVersionedFile test adapter."""
262
263
    def test_adapted_tests(self):
264
        # check that constructor parameters are passed through to the adapted
265
        # test.
266
        from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
267
        input_test = TestInterRepositoryProviderAdapter(
268
            "test_adapted_tests")
269
        server1 = "a"
270
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
271
        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.
272
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
273
        suite = adapter.adapt(input_test)
274
        tests = list(iter(suite))
275
        self.assertEqual(2, len(tests))
276
        self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
277
        self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
278
        self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
279
        self.assertEqual(tests[0].transport_server, server1)
280
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
281
        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.
282
        self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
283
        self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
284
        self.assertEqual(tests[1].transport_server, server1)
285
        self.assertEqual(tests[1].transport_readonly_server, server2)
286
287
1563.2.20 by Robert Collins
Add a revision store test adapter.
288
class TestRevisionStoreProviderAdapter(TestCase):
289
    """A group of tests that test the RevisionStore test adapter."""
290
291
    def test_adapted_tests(self):
292
        # check that constructor parameters are passed through to the adapted
293
        # test.
294
        from bzrlib.store.revision import RevisionStoreTestProviderAdapter
295
        input_test = TestRevisionStoreProviderAdapter(
296
            "test_adapted_tests")
297
        # revision stores need a store factory - i.e. RevisionKnit
298
        #, a readonly and rw transport 
299
        # transport servers:
300
        server1 = "a"
301
        server2 = "b"
302
        store_factories = ["c", "d"]
303
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
304
        suite = adapter.adapt(input_test)
305
        tests = list(iter(suite))
306
        self.assertEqual(2, len(tests))
307
        self.assertEqual(tests[0].store_factory, store_factories[0][0])
308
        self.assertEqual(tests[0].transport_server, server1)
309
        self.assertEqual(tests[0].transport_readonly_server, server2)
310
        self.assertEqual(tests[1].store_factory, store_factories[1][0])
311
        self.assertEqual(tests[1].transport_server, server1)
312
        self.assertEqual(tests[1].transport_readonly_server, server2)
313
314
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
315
class TestWorkingTreeProviderAdapter(TestCase):
316
    """A group of tests that test the workingtree implementation test adapter."""
317
318
    def test_adapted_tests(self):
319
        # check that constructor parameters are passed through to the adapted
320
        # test.
321
        from bzrlib.workingtree import WorkingTreeTestProviderAdapter
322
        input_test = TestWorkingTreeProviderAdapter(
323
            "test_adapted_tests")
324
        server1 = "a"
325
        server2 = "b"
326
        formats = [("c", "C"), ("d", "D")]
327
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
328
        suite = adapter.adapt(input_test)
329
        tests = list(iter(suite))
330
        self.assertEqual(2, len(tests))
331
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
332
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
333
        self.assertEqual(tests[0].transport_server, server1)
334
        self.assertEqual(tests[0].transport_readonly_server, server2)
335
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
336
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
337
        self.assertEqual(tests[1].transport_server, server1)
338
        self.assertEqual(tests[1].transport_readonly_server, server2)
339
340
1852.6.1 by Robert Collins
Start tree implementation tests.
341
class TestTreeProviderAdapter(TestCase):
342
    """Test the setup of tree_implementation tests."""
343
344
    def test_adapted_tests(self):
345
        # the tree implementation adapter is meant to setup one instance for
346
        # each working tree format, and one additional instance that will
347
        # use the default wt format, but create a revision tree for the tests.
348
        # this means that the wt ones should have the workingtree_to_test_tree
349
        # attribute set to 'return_parameter' and the revision one set to
350
        # revision_tree_from_workingtree.
351
352
        from bzrlib.tests.tree_implementations import (
353
            TreeTestProviderAdapter,
354
            return_parameter,
355
            revision_tree_from_workingtree
356
            )
357
        from bzrlib.workingtree import WorkingTreeFormat
358
        input_test = TestTreeProviderAdapter(
359
            "test_adapted_tests")
360
        server1 = "a"
361
        server2 = "b"
362
        formats = [("c", "C"), ("d", "D")]
363
        adapter = TreeTestProviderAdapter(server1, server2, formats)
364
        suite = adapter.adapt(input_test)
365
        tests = list(iter(suite))
366
        self.assertEqual(3, len(tests))
367
        default_format = WorkingTreeFormat.get_default_format()
368
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
369
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
370
        self.assertEqual(tests[0].transport_server, server1)
371
        self.assertEqual(tests[0].transport_readonly_server, server2)
372
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
373
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
374
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
375
        self.assertEqual(tests[1].transport_server, server1)
376
        self.assertEqual(tests[1].transport_readonly_server, server2)
377
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
378
        self.assertEqual(tests[2].workingtree_format, default_format)
379
        self.assertEqual(tests[2].bzrdir_format, default_format._matchingbzrdir)
380
        self.assertEqual(tests[2].transport_server, server1)
381
        self.assertEqual(tests[2].transport_readonly_server, server2)
382
        self.assertEqual(tests[2].workingtree_to_test_tree,
383
            revision_tree_from_workingtree)
384
385
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
386
class TestInterTreeProviderAdapter(TestCase):
387
    """A group of tests that test the InterTreeTestAdapter."""
388
389
    def test_adapted_tests(self):
390
        # check that constructor parameters are passed through to the adapted
391
        # test.
392
        # for InterTree tests we want the machinery to bring up two trees in
393
        # each instance: the base one, and the one we are interacting with.
394
        # because each optimiser can be direction specific, we need to test
395
        # each optimiser in its chosen direction.
396
        # unlike the TestProviderAdapter we dont want to automatically add a
397
        # parameterised one for WorkingTree - the optimisers will tell us what
398
        # ones to add.
399
        from bzrlib.tests.tree_implementations import (
400
            return_parameter,
401
            revision_tree_from_workingtree
402
            )
403
        from bzrlib.tests.intertree_implementations import (
404
            InterTreeTestProviderAdapter,
405
            )
406
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
407
        input_test = TestInterTreeProviderAdapter(
408
            "test_adapted_tests")
409
        server1 = "a"
410
        server2 = "b"
411
        format1 = WorkingTreeFormat2()
412
        format2 = WorkingTreeFormat3()
413
        formats = [(str, format1, format2, False, True),
414
            (int, format2, format1, False, True)]
415
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
416
        suite = adapter.adapt(input_test)
417
        tests = list(iter(suite))
418
        self.assertEqual(2, len(tests))
419
        self.assertEqual(tests[0].intertree_class, formats[0][0])
420
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
421
        self.assertEqual(tests[0].workingtree_to_test_tree, formats[0][2])
422
        self.assertEqual(tests[0].workingtree_format_to, formats[0][3])
423
        self.assertEqual(tests[0].workingtree_to_test_tree_to, formats[0][4])
424
        self.assertEqual(tests[0].transport_server, server1)
425
        self.assertEqual(tests[0].transport_readonly_server, server2)
426
        self.assertEqual(tests[1].intertree_class, formats[1][0])
427
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
428
        self.assertEqual(tests[1].workingtree_to_test_tree, formats[1][2])
429
        self.assertEqual(tests[1].workingtree_format_to, formats[1][3])
430
        self.assertEqual(tests[1].workingtree_to_test_tree_to, formats[1][4])
431
        self.assertEqual(tests[1].transport_server, server1)
432
        self.assertEqual(tests[1].transport_readonly_server, server2)
433
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
434
435
class TestTestCaseInTempDir(TestCaseInTempDir):
436
437
    def test_home_is_not_working(self):
438
        self.assertNotEqual(self.test_dir, self.test_home_dir)
439
        cwd = osutils.getcwd()
1987.1.4 by John Arbash Meinel
fix the home_is_not_working test
440
        self.assertEqual(self.test_dir, cwd)
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
441
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
442
443
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
444
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
445
446
    def test_home_is_non_existant_dir_under_root(self):
447
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
448
449
        This is because TestCaseWithMemoryTransport is for tests that do not
450
        need any disk resources: they should be hooked into bzrlib in such a 
451
        way that no global settings are being changed by the test (only a 
452
        few tests should need to do that), and having a missing dir as home is
453
        an effective way to ensure that this is the case.
454
        """
455
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
456
            self.test_home_dir)
457
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
458
        
459
    def test_cwd_is_TEST_ROOT(self):
460
        self.assertEqual(self.test_dir, self.TEST_ROOT)
461
        cwd = osutils.getcwd()
462
        self.assertEqual(self.test_dir, cwd)
463
464
    def test_make_branch_and_memory_tree(self):
465
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
466
467
        This is hard to comprehensively robustly test, so we settle for making
468
        a branch and checking no directory was created at its relpath.
469
        """
470
        tree = self.make_branch_and_memory_tree('dir')
471
        self.failIfExists('dir')
472
        self.assertIsInstance(tree, memorytree.MemoryTree)
473
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
474
    def test_make_branch_and_memory_tree_with_format(self):
475
        """make_branch_and_memory_tree should accept a format option."""
476
        format = bzrdir.BzrDirMetaFormat1()
477
        format.repository_format = repository.RepositoryFormat7()
478
        tree = self.make_branch_and_memory_tree('dir', format=format)
479
        self.failIfExists('dir')
480
        self.assertIsInstance(tree, memorytree.MemoryTree)
481
        self.assertEqual(format.repository_format.__class__,
482
            tree.branch.repository._format.__class__)
483
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
484
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
485
class TestTestCaseWithTransport(TestCaseWithTransport):
486
    """Tests for the convenience functions TestCaseWithTransport introduces."""
487
488
    def test_get_readonly_url_none(self):
489
        from bzrlib.transport import get_transport
490
        from bzrlib.transport.memory import MemoryServer
491
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
492
        self.transport_server = MemoryServer
493
        self.transport_readonly_server = None
494
        # calling get_readonly_transport() constructs a decorator on the url
495
        # for the server
496
        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.
497
        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.
498
        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.
499
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
500
        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.
501
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
502
        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.
503
504
    def test_get_readonly_url_http(self):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
505
        from bzrlib.tests.HttpServer import HttpServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
506
        from bzrlib.transport import get_transport
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
507
        from bzrlib.transport.local import LocalURLServer
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
508
        from bzrlib.transport.http import HttpTransportBase
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
509
        self.transport_server = LocalURLServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
510
        self.transport_readonly_server = HttpServer
511
        # calling get_readonly_transport() gives us a HTTP server instance.
512
        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.
513
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
514
        # 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.
515
        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.
516
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
517
        self.failUnless(isinstance(t, HttpTransportBase))
518
        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.
519
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
520
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
521
    def test_is_directory(self):
522
        """Test assertIsDirectory assertion"""
523
        t = self.get_transport()
524
        self.build_tree(['a_dir/', 'a_file'], transport=t)
525
        self.assertIsDirectory('a_dir', t)
526
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
527
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
528
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
529
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
530
class TestTestCaseTransports(TestCaseWithTransport):
531
532
    def setUp(self):
533
        super(TestTestCaseTransports, self).setUp()
534
        self.transport_server = MemoryServer
535
536
    def test_make_bzrdir_preserves_transport(self):
537
        t = self.get_transport()
538
        result_bzrdir = self.make_bzrdir('subdir')
539
        self.assertIsInstance(result_bzrdir.transport, 
540
                              MemoryTransport)
541
        # should not be on disk, should only be in memory
542
        self.failIfExists('subdir')
543
544
1534.4.31 by Robert Collins
cleanedup test_outside_wt
545
class TestChrootedTest(ChrootedTestCase):
546
547
    def test_root_is_root(self):
548
        from bzrlib.transport import get_transport
549
        t = get_transport(self.get_readonly_url())
550
        url = t.base
551
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
552
553
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
554
class MockProgress(_BaseProgressBar):
555
    """Progress-bar standin that records calls.
556
557
    Useful for testing pb using code.
558
    """
559
560
    def __init__(self):
561
        _BaseProgressBar.__init__(self)
562
        self.calls = []
563
564
    def tick(self):
565
        self.calls.append(('tick',))
566
567
    def update(self, msg=None, current=None, total=None):
568
        self.calls.append(('update', msg, current, total))
569
570
    def clear(self):
571
        self.calls.append(('clear',))
572
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
573
    def note(self, msg, *args):
574
        self.calls.append(('note', msg, args))
575
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
576
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
577
class TestTestResult(TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
578
579
    def test_progress_bar_style_quiet(self):
580
        # test using a progress bar.
1728.1.2 by Robert Collins
Bugfix missing search-and-replace of TestResult.
581
        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.
582
        dummy_error = (Exception, None, [])
583
        mypb = MockProgress()
584
        mypb.update('Running tests', 0, 4)
585
        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
586
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
587
        result = bzrlib.tests._MyResult(self._log_file,
588
                                        descriptions=0,
589
                                        verbosity=1,
590
                                        pb=mypb)
591
        self.assertEqual(last_calls, mypb.calls)
592
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
593
        def shorten(s):
594
            """Shorten a string based on the terminal width"""
595
            return result._ellipsise_unimportant_words(s,
596
                                 osutils.terminal_width())
597
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
598
        # an error 
599
        result.startTest(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
600
        # 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
601
        last_calls += [('update', '...tyle_quiet', 0, None)]
602
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
603
        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
604
        last_calls += [('update', 'ERROR        ', 1, None),
605
                       ('note', shorten(dummy_test.id() + ': ERROR'), ())
606
                      ]
607
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
608
609
        # a failure
610
        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
611
        last_calls += [('update', '...tyle_quiet', 1, None)]
612
        self.assertEqual(last_calls, mypb.calls)
613
        last_calls += [('update', 'FAIL         ', 2, None),
614
                       ('note', shorten(dummy_test.id() + ': FAIL'), ())
615
                      ]
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
616
        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
617
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
618
619
        # a success
620
        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
621
        last_calls += [('update', '...tyle_quiet', 2, None)]
622
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
623
        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
624
        last_calls += [('update', 'OK           ', 3, None)]
625
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
626
627
        # a skip
628
        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
629
        last_calls += [('update', '...tyle_quiet', 3, None)]
630
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
631
        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
632
        last_calls += [('update', 'SKIP         ', 4, None)]
633
        self.assertEqual(last_calls, mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
634
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
635
    def test_elapsed_time_with_benchmarking(self):
636
        result = bzrlib.tests._MyResult(self._log_file,
637
                                        descriptions=0,
638
                                        verbosity=1,
639
                                        )
640
        result._recordTestStartTime()
641
        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)
642
        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).
643
        timed_string = result._testTimeString()
644
        # 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)
645
        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).
646
        # 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)
647
        self.time(time.sleep, 0.001)
648
        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).
649
        timed_string = result._testTimeString()
1740.2.5 by Aaron Bentley
Merge from bzr.dev
650
        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)
651
        # 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).
652
        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)
653
        result.extractBenchmarkTime(
654
            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).
655
        timed_string = result._testTimeString()
1740.2.5 by Aaron Bentley
Merge from bzr.dev
656
        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)
657
        # cheat. Yes, wash thy mouth out with soap.
658
        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).
659
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
660
    def test_assigned_benchmark_file_stores_date(self):
661
        output = StringIO()
662
        result = bzrlib.tests._MyResult(self._log_file,
663
                                        descriptions=0,
664
                                        verbosity=1,
665
                                        bench_history=output
666
                                        )
667
        output_string = output.getvalue()
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
668
        # if you are wondering about the regexp please read the comment in
669
        # 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.
670
        # XXX: what comment?  -- Andrew Bennetts
671
        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
672
673
    def test_benchhistory_records_test_times(self):
674
        result_stream = StringIO()
675
        result = bzrlib.tests._MyResult(
676
            self._log_file,
677
            descriptions=0,
678
            verbosity=1,
679
            bench_history=result_stream
680
            )
681
682
        # we want profile a call and check that its test duration is recorded
683
        # make a new test instance that when run will generate a benchmark
684
        example_test_case = TestTestResult("_time_hello_world_encoding")
685
        # execute the test, which should succeed and record times
686
        example_test_case.run(result)
687
        lines = result_stream.getvalue().splitlines()
688
        self.assertEqual(2, len(lines))
689
        self.assertContainsRe(lines[1],
690
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
691
            "._time_hello_world_encoding")
692
 
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
693
    def _time_hello_world_encoding(self):
694
        """Profile two sleep calls
695
        
696
        This is used to exercise the test framework.
697
        """
698
        self.time(unicode, 'hello', errors='replace')
699
        self.time(unicode, 'world', errors='replace')
700
701
    def test_lsprofiling(self):
702
        """Verbose test result prints lsprof statistics from test cases."""
703
        try:
704
            import bzrlib.lsprof
705
        except ImportError:
706
            raise TestSkipped("lsprof not installed.")
707
        result_stream = StringIO()
708
        result = bzrlib.tests._MyResult(
709
            unittest._WritelnDecorator(result_stream),
710
            descriptions=0,
711
            verbosity=2,
712
            )
713
        # we want profile a call of some sort and check it is output by
714
        # addSuccess. We dont care about addError or addFailure as they
715
        # are not that interesting for performance tuning.
716
        # make a new test instance that when run will generate a profile
717
        example_test_case = TestTestResult("_time_hello_world_encoding")
718
        example_test_case._gather_lsprof_in_benchmarks = True
719
        # execute the test, which should succeed and record profiles
720
        example_test_case.run(result)
721
        # lsprofile_something()
722
        # if this worked we want 
723
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
724
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
725
        # (the lsprof header)
726
        # ... an arbitrary number of lines
727
        # and the function call which is time.sleep.
728
        #           1        0            ???         ???       ???(sleep) 
729
        # and then repeated but with 'world', rather than 'hello'.
730
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
731
        output = result_stream.getvalue()
732
        self.assertContainsRe(output,
733
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
734
        self.assertContainsRe(output,
735
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
736
        self.assertContainsRe(output,
737
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
738
        self.assertContainsRe(output,
739
            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
740
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
741
742
class TestRunner(TestCase):
743
744
    def dummy_test(self):
745
        pass
746
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
747
    def run_test_runner(self, testrunner, test):
748
        """Run suite in testrunner, saving global state and restoring it.
749
750
        This current saves and restores:
751
        TestCaseInTempDir.TEST_ROOT
752
        
753
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
754
        without using this convenience method, because of our use of global state.
755
        """
756
        old_root = TestCaseInTempDir.TEST_ROOT
757
        try:
758
            TestCaseInTempDir.TEST_ROOT = None
759
            return testrunner.run(test)
760
        finally:
761
            TestCaseInTempDir.TEST_ROOT = old_root
762
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
763
    def test_accepts_and_uses_pb_parameter(self):
764
        test = TestRunner('dummy_test')
765
        mypb = MockProgress()
766
        self.assertEqual([], mypb.calls)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
767
        runner = TextTestRunner(stream=self._log_file, pb=mypb)
768
        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.
769
        self.assertEqual(1, result.testsRun)
770
        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.
771
        self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
772
        self.assertEqual(('update', 'OK           ', 1, None), mypb.calls[2])
773
        self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
774
        self.assertEqual(('clear',), mypb.calls[4])
775
        self.assertEqual(5, len(mypb.calls))
1534.11.4 by Robert Collins
Merge from mainline.
776
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
777
    def test_skipped_test(self):
778
        # run a test that is skipped, and check the suite as a whole still
779
        # succeeds.
780
        # skipping_test must be hidden in here so it's not run as a real test
781
        def skipping_test():
782
            raise TestSkipped('test intentionally skipped')
783
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
784
        test = unittest.FunctionTestCase(skipping_test)
785
        result = self.run_test_runner(runner, test)
786
        self.assertTrue(result.wasSuccessful())
787
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
788
    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.
789
        # tests that the running the benchmark produces a history file
790
        # containing a timestamp and the revision id of the bzrlib source which
791
        # was tested.
792
        workingtree = _get_bzr_source_tree()
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
793
        test = TestRunner('dummy_test')
794
        output = StringIO()
795
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
796
        result = self.run_test_runner(runner, test)
797
        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.
798
        self.assertContainsRe(output_string, "--date [0-9.]+")
799
        if workingtree is not None:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
800
            revision_id = workingtree.get_parent_ids()[0]
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
801
            self.assertEndsWith(output_string.rstrip(), revision_id)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
802
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
803
    def test_success_log_deleted(self):
804
        """Successful tests have their log deleted"""
805
806
        class LogTester(TestCase):
807
808
            def test_success(self):
809
                self.log('this will be removed\n')
810
811
        sio = cStringIO.StringIO()
812
        runner = TextTestRunner(stream=sio)
813
        test = LogTester('test_success')
814
        result = self.run_test_runner(runner, test)
815
816
        log = test._get_log()
817
        self.assertEqual("DELETED log file to reduce memory footprint", log)
818
        self.assertEqual('', test._log_contents)
819
        self.assertIs(None, test._log_file_name)
820
821
    def test_fail_log_kept(self):
822
        """Failed tests have their log kept"""
823
824
        class LogTester(TestCase):
825
826
            def test_fail(self):
827
                self.log('this will be kept\n')
828
                self.fail('this test fails')
829
830
        sio = cStringIO.StringIO()
831
        runner = TextTestRunner(stream=sio)
832
        test = LogTester('test_fail')
833
        result = self.run_test_runner(runner, test)
834
835
        text = sio.getvalue()
836
        self.assertContainsRe(text, 'this will be kept')
837
        self.assertContainsRe(text, 'this test fails')
838
839
        log = test._get_log()
840
        self.assertContainsRe(log, 'this will be kept')
841
        self.assertEqual(log, test._log_contents)
842
843
    def test_error_log_kept(self):
844
        """Tests with errors have their log kept"""
845
846
        class LogTester(TestCase):
847
848
            def test_error(self):
849
                self.log('this will be kept\n')
850
                raise ValueError('random exception raised')
851
852
        sio = cStringIO.StringIO()
853
        runner = TextTestRunner(stream=sio)
854
        test = LogTester('test_error')
855
        result = self.run_test_runner(runner, test)
856
857
        text = sio.getvalue()
858
        self.assertContainsRe(text, 'this will be kept')
859
        self.assertContainsRe(text, 'random exception raised')
860
861
        log = test._get_log()
862
        self.assertContainsRe(log, 'this will be kept')
863
        self.assertEqual(log, test._log_contents)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
864
2036.1.2 by John Arbash Meinel
whitespace fix
865
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
866
class TestTestCase(TestCase):
867
    """Tests that test the core bzrlib TestCase."""
868
869
    def inner_test(self):
870
        # the inner child test
871
        note("inner_test")
872
873
    def outer_child(self):
874
        # the outer child test
875
        note("outer_start")
876
        self.inner_test = TestTestCase("inner_child")
877
        result = bzrlib.tests._MyResult(self._log_file,
878
                                        descriptions=0,
879
                                        verbosity=1)
880
        self.inner_test.run(result)
881
        note("outer finish")
882
883
    def test_trace_nesting(self):
884
        # this tests that each test case nests its trace facility correctly.
885
        # we do this by running a test case manually. That test case (A)
886
        # should setup a new log, log content to it, setup a child case (B),
887
        # which should log independently, then case (A) should log a trailer
888
        # and return.
889
        # we do two nested children so that we can verify the state of the 
890
        # logs after the outer child finishes is correct, which a bad clean
891
        # up routine in tearDown might trigger a fault in our test with only
892
        # one child, we should instead see the bad result inside our test with
893
        # the two children.
894
        # the outer child test
895
        original_trace = bzrlib.trace._trace_file
896
        outer_test = TestTestCase("outer_child")
897
        result = bzrlib.tests._MyResult(self._log_file,
898
                                        descriptions=0,
899
                                        verbosity=1)
900
        outer_test.run(result)
901
        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)
902
903
    def method_that_times_a_bit_twice(self):
904
        # 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.
905
        self.time(time.sleep, 0.007)
906
        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)
907
908
    def test_time_creates_benchmark_in_result(self):
909
        """Test that the TestCase.time() method accumulates a benchmark time."""
910
        sample_test = TestTestCase("method_that_times_a_bit_twice")
911
        output_stream = StringIO()
912
        result = bzrlib.tests._MyResult(
913
            unittest._WritelnDecorator(output_stream),
914
            descriptions=0,
915
            verbosity=2)
916
        sample_test.run(result)
917
        self.assertContainsRe(
918
            output_stream.getvalue(),
919
            "[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.
920
        
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
921
    def test__gather_lsprof_in_benchmarks(self):
922
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
923
        
924
        Each self.time() call is individually and separately profiled.
925
        """
926
        try:
927
            import bzrlib.lsprof
928
        except ImportError:
929
            raise TestSkipped("lsprof not installed.")
930
        # overrides the class member with an instance member so no cleanup 
931
        # needed.
932
        self._gather_lsprof_in_benchmarks = True
933
        self.time(time.sleep, 0.000)
934
        self.time(time.sleep, 0.003)
935
        self.assertEqual(2, len(self._benchcalls))
936
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
937
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
938
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
939
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
940
1534.11.4 by Robert Collins
Merge from mainline.
941
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
942
@symbol_versioning.deprecated_function(zero_eleven)
943
def sample_deprecated_function():
944
    """A deprecated function to test applyDeprecated with."""
945
    return 2
946
947
948
def sample_undeprecated_function(a_param):
949
    """A undeprecated function to test applyDeprecated with."""
950
951
952
class ApplyDeprecatedHelper(object):
953
    """A helper class for ApplyDeprecated tests."""
954
955
    @symbol_versioning.deprecated_method(zero_eleven)
956
    def sample_deprecated_method(self, param_one):
957
        """A deprecated method for testing with."""
958
        return param_one
959
960
    def sample_normal_method(self):
961
        """A undeprecated method."""
962
963
    @symbol_versioning.deprecated_method(zero_ten)
964
    def sample_nested_deprecation(self):
965
        return sample_deprecated_function()
966
967
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
968
class TestExtraAssertions(TestCase):
969
    """Tests for new test assertions in bzrlib test suite"""
970
971
    def test_assert_isinstance(self):
972
        self.assertIsInstance(2, int)
973
        self.assertIsInstance(u'', basestring)
974
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
975
        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
976
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
977
    def test_assertEndsWith(self):
978
        self.assertEndsWith('foo', 'oo')
979
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
980
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
981
    def test_applyDeprecated_not_deprecated(self):
982
        sample_object = ApplyDeprecatedHelper()
983
        # calling an undeprecated callable raises an assertion
984
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
985
            sample_object.sample_normal_method)
986
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
987
            sample_undeprecated_function, "a param value")
988
        # calling a deprecated callable (function or method) with the wrong
989
        # expected deprecation fails.
990
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
991
            sample_object.sample_deprecated_method, "a param value")
992
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
993
            sample_deprecated_function)
994
        # calling a deprecated callable (function or method) with the right
995
        # expected deprecation returns the functions result.
996
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
997
            sample_object.sample_deprecated_method, "a param value"))
998
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
999
            sample_deprecated_function))
1000
        # calling a nested deprecation with the wrong deprecation version
1001
        # fails even if a deeper nested function was deprecated with the 
1002
        # supplied version.
1003
        self.assertRaises(AssertionError, self.applyDeprecated,
1004
            zero_eleven, sample_object.sample_nested_deprecation)
1005
        # calling a nested deprecation with the right deprecation value
1006
        # returns the calls result.
1007
        self.assertEqual(2, self.applyDeprecated(zero_ten,
1008
            sample_object.sample_nested_deprecation))
1009
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1010
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1011
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1012
            if be_deprecated is True:
1013
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
1014
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1015
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1016
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1017
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1018
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1019
        self.assertEqual('result', result)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1020
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1021
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1022
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1023
1024
class TestConvenienceMakers(TestCaseWithTransport):
1025
    """Test for the make_* convenience functions."""
1026
1027
    def test_make_branch_and_tree_with_format(self):
1028
        # we should be able to supply a format to make_branch_and_tree
1029
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1030
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1031
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1032
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1033
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1034
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1035
1986.2.1 by Robert Collins
Bugfix - the name of the test for make_branch_and_memory_tree was wrong.
1036
    def test_make_branch_and_memory_tree(self):
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
1037
        # we should be able to get a new branch and a mutable tree from
1038
        # TestCaseWithTransport
1039
        tree = self.make_branch_and_memory_tree('a')
1040
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1041
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1042
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
1043
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1044
1045
    def test_make_tree_for_sftp_branch(self):
1046
        """Transports backed by local directories create local trees."""
1047
1048
        tree = self.make_branch_and_tree('t1')
1049
        base = tree.bzrdir.root_transport.base
1050
        self.failIf(base.startswith('sftp'),
1051
                'base %r is on sftp but should be local' % base)
1052
        self.assertEquals(tree.bzrdir.root_transport,
1053
                tree.branch.bzrdir.root_transport)
1054
        self.assertEquals(tree.bzrdir.root_transport,
1055
                tree.branch.repository.bzrdir.root_transport)
1056
1057
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1058
class TestSelftest(TestCase):
1059
    """Tests of bzrlib.tests.selftest."""
1060
1061
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1062
        factory_called = []
1063
        def factory():
1064
            factory_called.append(True)
1065
            return TestSuite()
1066
        out = StringIO()
1067
        err = StringIO()
1068
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
1069
            test_suite_factory=factory)
1070
        self.assertEqual([True], factory_called)