/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1
# Copyright (C) 2005, 2006, 2007 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,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
30
    errors,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
31
    memorytree,
32
    osutils,
33
    repository,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
34
    symbol_versioning,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
35
    )
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
36
from bzrlib.progress import _BaseProgressBar
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
37
from bzrlib.repofmt import weaverepo
38
from bzrlib.symbol_versioning import zero_ten, zero_eleven
1526.1.3 by Robert Collins
Merge from upstream.
39
from bzrlib.tests import (
1534.4.31 by Robert Collins
cleanedup test_outside_wt
40
                          ChrootedTestCase,
1526.1.3 by Robert Collins
Merge from upstream.
41
                          TestCase,
42
                          TestCaseInTempDir,
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
43
                          TestCaseWithMemoryTransport,
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
44
                          TestCaseWithTransport,
1526.1.3 by Robert Collins
Merge from upstream.
45
                          TestSkipped,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
46
                          TestSuite,
1526.1.3 by Robert Collins
Merge from upstream.
47
                          TextTestRunner,
48
                          )
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
49
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
50
from bzrlib.tests.TestUtil import _load_module_by_name
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
51
from bzrlib.trace import note
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
52
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.
53
from bzrlib.version import _get_bzr_source_tree
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
54
55
56
class SelftestTests(TestCase):
57
58
    def test_import_tests(self):
59
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
60
        self.assertEqual(mod.SelftestTests, SelftestTests)
61
62
    def test_import_test_failure(self):
63
        self.assertRaises(ImportError,
64
                          _load_module_by_name,
65
                          'bzrlib.no-name-yet')
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")
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
191
        vfs_factory = "v"
1534.4.39 by Robert Collins
Basic BzrDir support.
192
        server1 = "a"
193
        server2 = "b"
194
        formats = ["c", "d"]
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
195
        adapter = BzrDirTestProviderAdapter(vfs_factory,
196
            server1, server2, formats)
1534.4.39 by Robert Collins
Basic BzrDir support.
197
        suite = adapter.adapt(input_test)
198
        tests = list(iter(suite))
199
        self.assertEqual(2, len(tests))
200
        self.assertEqual(tests[0].bzrdir_format, formats[0])
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
201
        self.assertEqual(tests[0].vfs_transport_factory, vfs_factory)
1534.4.39 by Robert Collins
Basic BzrDir support.
202
        self.assertEqual(tests[0].transport_server, server1)
203
        self.assertEqual(tests[0].transport_readonly_server, server2)
204
        self.assertEqual(tests[1].bzrdir_format, formats[1])
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
205
        self.assertEqual(tests[1].vfs_transport_factory, vfs_factory)
1534.4.39 by Robert Collins
Basic BzrDir support.
206
        self.assertEqual(tests[1].transport_server, server1)
207
        self.assertEqual(tests[1].transport_readonly_server, server2)
208
209
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
210
class TestRepositoryProviderAdapter(TestCase):
211
    """A group of tests that test the repository implementation test adapter."""
212
213
    def test_adapted_tests(self):
214
        # check that constructor parameters are passed through to the adapted
215
        # test.
216
        from bzrlib.repository import RepositoryTestProviderAdapter
217
        input_test = TestRepositoryProviderAdapter(
218
            "test_adapted_tests")
219
        server1 = "a"
220
        server2 = "b"
221
        formats = [("c", "C"), ("d", "D")]
222
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
223
        suite = adapter.adapt(input_test)
224
        tests = list(iter(suite))
225
        self.assertEqual(2, len(tests))
226
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
227
        self.assertEqual(tests[0].repository_format, formats[0][0])
228
        self.assertEqual(tests[0].transport_server, server1)
229
        self.assertEqual(tests[0].transport_readonly_server, server2)
230
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
231
        self.assertEqual(tests[1].repository_format, formats[1][0])
232
        self.assertEqual(tests[1].transport_server, server1)
233
        self.assertEqual(tests[1].transport_readonly_server, server2)
234
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
235
    def test_setting_vfs_transport(self):
236
        """The vfs_transport_factory can be set optionally."""
237
        from bzrlib.repository import RepositoryTestProviderAdapter
238
        input_test = TestRepositoryProviderAdapter(
239
            "test_adapted_tests")
240
        formats = [("c", "C")]
241
        adapter = RepositoryTestProviderAdapter(None, None, formats,
242
            vfs_transport_factory="vfs")
243
        suite = adapter.adapt(input_test)
244
        tests = list(iter(suite))
245
        self.assertEqual(1, len(tests))
246
        self.assertEqual(tests[0].vfs_transport_factory, "vfs")
247
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
248
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
249
class TestInterRepositoryProviderAdapter(TestCase):
250
    """A group of tests that test the InterRepository test adapter."""
251
252
    def test_adapted_tests(self):
253
        # check that constructor parameters are passed through to the adapted
254
        # test.
255
        from bzrlib.repository import InterRepositoryTestProviderAdapter
256
        input_test = TestInterRepositoryProviderAdapter(
257
            "test_adapted_tests")
258
        server1 = "a"
259
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
260
        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.
261
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
262
        suite = adapter.adapt(input_test)
263
        tests = list(iter(suite))
264
        self.assertEqual(2, len(tests))
265
        self.assertEqual(tests[0].interrepo_class, formats[0][0])
266
        self.assertEqual(tests[0].repository_format, formats[0][1])
267
        self.assertEqual(tests[0].repository_format_to, formats[0][2])
268
        self.assertEqual(tests[0].transport_server, server1)
269
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
270
        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.
271
        self.assertEqual(tests[1].repository_format, formats[1][1])
272
        self.assertEqual(tests[1].repository_format_to, formats[1][2])
273
        self.assertEqual(tests[1].transport_server, server1)
274
        self.assertEqual(tests[1].transport_readonly_server, server2)
275
276
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.
277
class TestInterVersionedFileProviderAdapter(TestCase):
278
    """A group of tests that test the InterVersionedFile test adapter."""
279
280
    def test_adapted_tests(self):
281
        # check that constructor parameters are passed through to the adapted
282
        # test.
283
        from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
284
        input_test = TestInterRepositoryProviderAdapter(
285
            "test_adapted_tests")
286
        server1 = "a"
287
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
288
        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.
289
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
290
        suite = adapter.adapt(input_test)
291
        tests = list(iter(suite))
292
        self.assertEqual(2, len(tests))
293
        self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
294
        self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
295
        self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
296
        self.assertEqual(tests[0].transport_server, server1)
297
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
298
        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.
299
        self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
300
        self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
301
        self.assertEqual(tests[1].transport_server, server1)
302
        self.assertEqual(tests[1].transport_readonly_server, server2)
303
304
1563.2.20 by Robert Collins
Add a revision store test adapter.
305
class TestRevisionStoreProviderAdapter(TestCase):
306
    """A group of tests that test the RevisionStore test adapter."""
307
308
    def test_adapted_tests(self):
309
        # check that constructor parameters are passed through to the adapted
310
        # test.
311
        from bzrlib.store.revision import RevisionStoreTestProviderAdapter
312
        input_test = TestRevisionStoreProviderAdapter(
313
            "test_adapted_tests")
314
        # revision stores need a store factory - i.e. RevisionKnit
315
        #, a readonly and rw transport 
316
        # transport servers:
317
        server1 = "a"
318
        server2 = "b"
319
        store_factories = ["c", "d"]
320
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
321
        suite = adapter.adapt(input_test)
322
        tests = list(iter(suite))
323
        self.assertEqual(2, len(tests))
324
        self.assertEqual(tests[0].store_factory, store_factories[0][0])
325
        self.assertEqual(tests[0].transport_server, server1)
326
        self.assertEqual(tests[0].transport_readonly_server, server2)
327
        self.assertEqual(tests[1].store_factory, store_factories[1][0])
328
        self.assertEqual(tests[1].transport_server, server1)
329
        self.assertEqual(tests[1].transport_readonly_server, server2)
330
331
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
332
class TestWorkingTreeProviderAdapter(TestCase):
333
    """A group of tests that test the workingtree implementation test adapter."""
334
335
    def test_adapted_tests(self):
336
        # check that constructor parameters are passed through to the adapted
337
        # test.
338
        from bzrlib.workingtree import WorkingTreeTestProviderAdapter
339
        input_test = TestWorkingTreeProviderAdapter(
340
            "test_adapted_tests")
341
        server1 = "a"
342
        server2 = "b"
343
        formats = [("c", "C"), ("d", "D")]
344
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
345
        suite = adapter.adapt(input_test)
346
        tests = list(iter(suite))
347
        self.assertEqual(2, len(tests))
348
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
349
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
350
        self.assertEqual(tests[0].transport_server, server1)
351
        self.assertEqual(tests[0].transport_readonly_server, server2)
352
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
353
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
354
        self.assertEqual(tests[1].transport_server, server1)
355
        self.assertEqual(tests[1].transport_readonly_server, server2)
356
357
1852.6.1 by Robert Collins
Start tree implementation tests.
358
class TestTreeProviderAdapter(TestCase):
359
    """Test the setup of tree_implementation tests."""
360
361
    def test_adapted_tests(self):
362
        # the tree implementation adapter is meant to setup one instance for
363
        # each working tree format, and one additional instance that will
364
        # use the default wt format, but create a revision tree for the tests.
365
        # this means that the wt ones should have the workingtree_to_test_tree
366
        # attribute set to 'return_parameter' and the revision one set to
367
        # revision_tree_from_workingtree.
368
369
        from bzrlib.tests.tree_implementations import (
370
            TreeTestProviderAdapter,
371
            return_parameter,
372
            revision_tree_from_workingtree
373
            )
2255.2.164 by Martin Pool
Change the default format for some tests from AB1 back to WorkingTreeFormat3
374
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
1852.6.1 by Robert Collins
Start tree implementation tests.
375
        input_test = TestTreeProviderAdapter(
376
            "test_adapted_tests")
377
        server1 = "a"
378
        server2 = "b"
379
        formats = [("c", "C"), ("d", "D")]
380
        adapter = TreeTestProviderAdapter(server1, server2, formats)
381
        suite = adapter.adapt(input_test)
382
        tests = list(iter(suite))
2255.6.3 by Aaron Bentley
tweak tests
383
        self.assertEqual(4, len(tests))
2255.2.164 by Martin Pool
Change the default format for some tests from AB1 back to WorkingTreeFormat3
384
        # this must match the default format setp up in
385
        # TreeTestProviderAdapter.adapt
386
        default_format = WorkingTreeFormat3
1852.6.1 by Robert Collins
Start tree implementation tests.
387
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
388
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
389
        self.assertEqual(tests[0].transport_server, server1)
390
        self.assertEqual(tests[0].transport_readonly_server, server2)
391
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
392
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
393
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
394
        self.assertEqual(tests[1].transport_server, server1)
395
        self.assertEqual(tests[1].transport_readonly_server, server2)
396
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
397
        self.assertIsInstance(tests[2].workingtree_format, default_format)
398
        #self.assertEqual(tests[2].bzrdir_format,
399
        #                 default_format._matchingbzrdir)
1852.6.1 by Robert Collins
Start tree implementation tests.
400
        self.assertEqual(tests[2].transport_server, server1)
401
        self.assertEqual(tests[2].transport_readonly_server, server2)
402
        self.assertEqual(tests[2].workingtree_to_test_tree,
403
            revision_tree_from_workingtree)
404
405
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
406
class TestInterTreeProviderAdapter(TestCase):
407
    """A group of tests that test the InterTreeTestAdapter."""
408
409
    def test_adapted_tests(self):
410
        # check that constructor parameters are passed through to the adapted
411
        # test.
412
        # for InterTree tests we want the machinery to bring up two trees in
413
        # each instance: the base one, and the one we are interacting with.
414
        # because each optimiser can be direction specific, we need to test
415
        # each optimiser in its chosen direction.
416
        # unlike the TestProviderAdapter we dont want to automatically add a
417
        # parameterised one for WorkingTree - the optimisers will tell us what
418
        # ones to add.
419
        from bzrlib.tests.tree_implementations import (
420
            return_parameter,
421
            revision_tree_from_workingtree
422
            )
423
        from bzrlib.tests.intertree_implementations import (
424
            InterTreeTestProviderAdapter,
425
            )
426
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
427
        input_test = TestInterTreeProviderAdapter(
428
            "test_adapted_tests")
429
        server1 = "a"
430
        server2 = "b"
431
        format1 = WorkingTreeFormat2()
432
        format2 = WorkingTreeFormat3()
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
433
        formats = [(str, format1, format2, "converter1"),
434
            (int, format2, format1, "converter2")]
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
435
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
436
        suite = adapter.adapt(input_test)
437
        tests = list(iter(suite))
438
        self.assertEqual(2, len(tests))
439
        self.assertEqual(tests[0].intertree_class, formats[0][0])
440
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
441
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
442
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
443
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
444
        self.assertEqual(tests[0].transport_server, server1)
445
        self.assertEqual(tests[0].transport_readonly_server, server2)
446
        self.assertEqual(tests[1].intertree_class, formats[1][0])
447
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
448
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
449
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
450
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
451
        self.assertEqual(tests[1].transport_server, server1)
452
        self.assertEqual(tests[1].transport_readonly_server, server2)
453
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
454
455
class TestTestCaseInTempDir(TestCaseInTempDir):
456
457
    def test_home_is_not_working(self):
458
        self.assertNotEqual(self.test_dir, self.test_home_dir)
459
        cwd = osutils.getcwd()
1987.1.4 by John Arbash Meinel
fix the home_is_not_working test
460
        self.assertEqual(self.test_dir, cwd)
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
461
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
462
463
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
464
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
465
466
    def test_home_is_non_existant_dir_under_root(self):
467
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
468
469
        This is because TestCaseWithMemoryTransport is for tests that do not
470
        need any disk resources: they should be hooked into bzrlib in such a 
471
        way that no global settings are being changed by the test (only a 
472
        few tests should need to do that), and having a missing dir as home is
473
        an effective way to ensure that this is the case.
474
        """
475
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
476
            self.test_home_dir)
477
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
478
        
479
    def test_cwd_is_TEST_ROOT(self):
480
        self.assertEqual(self.test_dir, self.TEST_ROOT)
481
        cwd = osutils.getcwd()
482
        self.assertEqual(self.test_dir, cwd)
483
484
    def test_make_branch_and_memory_tree(self):
485
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
486
487
        This is hard to comprehensively robustly test, so we settle for making
488
        a branch and checking no directory was created at its relpath.
489
        """
490
        tree = self.make_branch_and_memory_tree('dir')
2227.2.2 by v.ladeuil+lp at free
Cleanup.
491
        # Guard against regression into MemoryTransport leaking
492
        # files to disk instead of keeping them in memory.
493
        self.failIf(osutils.lexists('dir'))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
494
        self.assertIsInstance(tree, memorytree.MemoryTree)
495
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
496
    def test_make_branch_and_memory_tree_with_format(self):
497
        """make_branch_and_memory_tree should accept a format option."""
498
        format = bzrdir.BzrDirMetaFormat1()
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
499
        format.repository_format = weaverepo.RepositoryFormat7()
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
500
        tree = self.make_branch_and_memory_tree('dir', format=format)
2227.2.2 by v.ladeuil+lp at free
Cleanup.
501
        # Guard against regression into MemoryTransport leaking
502
        # files to disk instead of keeping them in memory.
503
        self.failIf(osutils.lexists('dir'))
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
504
        self.assertIsInstance(tree, memorytree.MemoryTree)
505
        self.assertEqual(format.repository_format.__class__,
506
            tree.branch.repository._format.__class__)
507
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
508
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
509
class TestTestCaseWithTransport(TestCaseWithTransport):
510
    """Tests for the convenience functions TestCaseWithTransport introduces."""
511
512
    def test_get_readonly_url_none(self):
513
        from bzrlib.transport import get_transport
514
        from bzrlib.transport.memory import MemoryServer
515
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
516
        self.vfs_transport_factory = MemoryServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
517
        self.transport_readonly_server = None
518
        # calling get_readonly_transport() constructs a decorator on the url
519
        # for the server
520
        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.
521
        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.
522
        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.
523
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
524
        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.
525
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
526
        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.
527
528
    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 :)
529
        from bzrlib.tests.HttpServer import HttpServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
530
        from bzrlib.transport import get_transport
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
531
        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 :)
532
        from bzrlib.transport.http import HttpTransportBase
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
533
        self.transport_server = LocalURLServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
534
        self.transport_readonly_server = HttpServer
535
        # calling get_readonly_transport() gives us a HTTP server instance.
536
        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.
537
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
538
        # 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.
539
        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.
540
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
541
        self.failUnless(isinstance(t, HttpTransportBase))
542
        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.
543
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
544
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
545
    def test_is_directory(self):
546
        """Test assertIsDirectory assertion"""
547
        t = self.get_transport()
548
        self.build_tree(['a_dir/', 'a_file'], transport=t)
549
        self.assertIsDirectory('a_dir', t)
550
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
551
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
552
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
553
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
554
class TestTestCaseTransports(TestCaseWithTransport):
555
556
    def setUp(self):
557
        super(TestTestCaseTransports, self).setUp()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
558
        self.vfs_transport_factory = MemoryServer
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
559
560
    def test_make_bzrdir_preserves_transport(self):
561
        t = self.get_transport()
562
        result_bzrdir = self.make_bzrdir('subdir')
563
        self.assertIsInstance(result_bzrdir.transport, 
564
                              MemoryTransport)
565
        # should not be on disk, should only be in memory
566
        self.failIfExists('subdir')
567
568
1534.4.31 by Robert Collins
cleanedup test_outside_wt
569
class TestChrootedTest(ChrootedTestCase):
570
571
    def test_root_is_root(self):
572
        from bzrlib.transport import get_transport
573
        t = get_transport(self.get_readonly_url())
574
        url = t.base
575
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
576
577
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
578
class MockProgress(_BaseProgressBar):
579
    """Progress-bar standin that records calls.
580
581
    Useful for testing pb using code.
582
    """
583
584
    def __init__(self):
585
        _BaseProgressBar.__init__(self)
586
        self.calls = []
587
588
    def tick(self):
589
        self.calls.append(('tick',))
590
591
    def update(self, msg=None, current=None, total=None):
592
        self.calls.append(('update', msg, current, total))
593
594
    def clear(self):
595
        self.calls.append(('clear',))
596
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
597
    def note(self, msg, *args):
598
        self.calls.append(('note', msg, args))
599
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
600
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
601
class TestTestResult(TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
602
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
603
    def test_elapsed_time_with_benchmarking(self):
2095.4.1 by Martin Pool
Better progress bars during tests
604
        result = bzrlib.tests.TextTestResult(self._log_file,
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
605
                                        descriptions=0,
606
                                        verbosity=1,
607
                                        )
608
        result._recordTestStartTime()
609
        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)
610
        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).
611
        timed_string = result._testTimeString()
612
        # without explicit benchmarking, we should get a simple time.
2196.1.2 by Martin Pool
Loosen requirements for benchmark formatting in selftest
613
        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).
614
        # 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)
615
        self.time(time.sleep, 0.001)
616
        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).
617
        timed_string = result._testTimeString()
2196.1.2 by Martin Pool
Loosen requirements for benchmark formatting in selftest
618
        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)
619
        # 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).
620
        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)
621
        result.extractBenchmarkTime(
622
            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).
623
        timed_string = result._testTimeString()
2196.1.2 by Martin Pool
Loosen requirements for benchmark formatting in selftest
624
        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)
625
        # cheat. Yes, wash thy mouth out with soap.
626
        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).
627
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
628
    def test_assigned_benchmark_file_stores_date(self):
629
        output = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
630
        result = bzrlib.tests.TextTestResult(self._log_file,
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
631
                                        descriptions=0,
632
                                        verbosity=1,
633
                                        bench_history=output
634
                                        )
635
        output_string = output.getvalue()
2095.4.1 by Martin Pool
Better progress bars during tests
636
        
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
637
        # if you are wondering about the regexp please read the comment in
638
        # 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.
639
        # XXX: what comment?  -- Andrew Bennetts
640
        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
641
642
    def test_benchhistory_records_test_times(self):
643
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
644
        result = bzrlib.tests.TextTestResult(
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
645
            self._log_file,
646
            descriptions=0,
647
            verbosity=1,
648
            bench_history=result_stream
649
            )
650
651
        # we want profile a call and check that its test duration is recorded
652
        # make a new test instance that when run will generate a benchmark
653
        example_test_case = TestTestResult("_time_hello_world_encoding")
654
        # execute the test, which should succeed and record times
655
        example_test_case.run(result)
656
        lines = result_stream.getvalue().splitlines()
657
        self.assertEqual(2, len(lines))
658
        self.assertContainsRe(lines[1],
659
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
660
            "._time_hello_world_encoding")
661
 
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
662
    def _time_hello_world_encoding(self):
663
        """Profile two sleep calls
664
        
665
        This is used to exercise the test framework.
666
        """
667
        self.time(unicode, 'hello', errors='replace')
668
        self.time(unicode, 'world', errors='replace')
669
670
    def test_lsprofiling(self):
671
        """Verbose test result prints lsprof statistics from test cases."""
672
        try:
673
            import bzrlib.lsprof
674
        except ImportError:
675
            raise TestSkipped("lsprof not installed.")
676
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
677
        result = bzrlib.tests.VerboseTestResult(
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
678
            unittest._WritelnDecorator(result_stream),
679
            descriptions=0,
680
            verbosity=2,
681
            )
682
        # we want profile a call of some sort and check it is output by
683
        # addSuccess. We dont care about addError or addFailure as they
684
        # are not that interesting for performance tuning.
685
        # make a new test instance that when run will generate a profile
686
        example_test_case = TestTestResult("_time_hello_world_encoding")
687
        example_test_case._gather_lsprof_in_benchmarks = True
688
        # execute the test, which should succeed and record profiles
689
        example_test_case.run(result)
690
        # lsprofile_something()
691
        # if this worked we want 
692
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
693
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
694
        # (the lsprof header)
695
        # ... an arbitrary number of lines
696
        # and the function call which is time.sleep.
697
        #           1        0            ???         ???       ???(sleep) 
698
        # and then repeated but with 'world', rather than 'hello'.
699
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
700
        output = result_stream.getvalue()
701
        self.assertContainsRe(output,
702
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
703
        self.assertContainsRe(output,
704
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
705
        self.assertContainsRe(output,
706
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
707
        self.assertContainsRe(output,
708
            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
709
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
710
711
class TestRunner(TestCase):
712
713
    def dummy_test(self):
714
        pass
715
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
716
    def run_test_runner(self, testrunner, test):
717
        """Run suite in testrunner, saving global state and restoring it.
718
719
        This current saves and restores:
720
        TestCaseInTempDir.TEST_ROOT
721
        
722
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
723
        without using this convenience method, because of our use of global state.
724
        """
725
        old_root = TestCaseInTempDir.TEST_ROOT
726
        try:
727
            TestCaseInTempDir.TEST_ROOT = None
728
            return testrunner.run(test)
729
        finally:
730
            TestCaseInTempDir.TEST_ROOT = old_root
731
732
    def test_skipped_test(self):
733
        # run a test that is skipped, and check the suite as a whole still
734
        # succeeds.
735
        # skipping_test must be hidden in here so it's not run as a real test
736
        def skipping_test():
737
            raise TestSkipped('test intentionally skipped')
738
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
739
        test = unittest.FunctionTestCase(skipping_test)
740
        result = self.run_test_runner(runner, test)
741
        self.assertTrue(result.wasSuccessful())
742
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
743
    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.
744
        # tests that the running the benchmark produces a history file
745
        # containing a timestamp and the revision id of the bzrlib source which
746
        # was tested.
747
        workingtree = _get_bzr_source_tree()
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
748
        test = TestRunner('dummy_test')
749
        output = StringIO()
750
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
751
        result = self.run_test_runner(runner, test)
752
        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.
753
        self.assertContainsRe(output_string, "--date [0-9.]+")
754
        if workingtree is not None:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
755
            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.
756
            self.assertEndsWith(output_string.rstrip(), revision_id)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
757
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
758
    def test_success_log_deleted(self):
759
        """Successful tests have their log deleted"""
760
761
        class LogTester(TestCase):
762
763
            def test_success(self):
764
                self.log('this will be removed\n')
765
766
        sio = cStringIO.StringIO()
767
        runner = TextTestRunner(stream=sio)
768
        test = LogTester('test_success')
769
        result = self.run_test_runner(runner, test)
770
771
        log = test._get_log()
772
        self.assertEqual("DELETED log file to reduce memory footprint", log)
773
        self.assertEqual('', test._log_contents)
774
        self.assertIs(None, test._log_file_name)
775
776
    def test_fail_log_kept(self):
777
        """Failed tests have their log kept"""
778
779
        class LogTester(TestCase):
780
781
            def test_fail(self):
782
                self.log('this will be kept\n')
783
                self.fail('this test fails')
784
785
        sio = cStringIO.StringIO()
786
        runner = TextTestRunner(stream=sio)
787
        test = LogTester('test_fail')
788
        result = self.run_test_runner(runner, test)
789
790
        text = sio.getvalue()
791
        self.assertContainsRe(text, 'this will be kept')
792
        self.assertContainsRe(text, 'this test fails')
793
794
        log = test._get_log()
795
        self.assertContainsRe(log, 'this will be kept')
796
        self.assertEqual(log, test._log_contents)
797
798
    def test_error_log_kept(self):
799
        """Tests with errors have their log kept"""
800
801
        class LogTester(TestCase):
802
803
            def test_error(self):
804
                self.log('this will be kept\n')
805
                raise ValueError('random exception raised')
806
807
        sio = cStringIO.StringIO()
808
        runner = TextTestRunner(stream=sio)
809
        test = LogTester('test_error')
810
        result = self.run_test_runner(runner, test)
811
812
        text = sio.getvalue()
813
        self.assertContainsRe(text, 'this will be kept')
814
        self.assertContainsRe(text, 'random exception raised')
815
816
        log = test._get_log()
817
        self.assertContainsRe(log, 'this will be kept')
818
        self.assertEqual(log, test._log_contents)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
819
2036.1.2 by John Arbash Meinel
whitespace fix
820
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
821
class TestTestCase(TestCase):
822
    """Tests that test the core bzrlib TestCase."""
823
824
    def inner_test(self):
825
        # the inner child test
826
        note("inner_test")
827
828
    def outer_child(self):
829
        # the outer child test
830
        note("outer_start")
831
        self.inner_test = TestTestCase("inner_child")
2095.4.1 by Martin Pool
Better progress bars during tests
832
        result = bzrlib.tests.TextTestResult(self._log_file,
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
833
                                        descriptions=0,
834
                                        verbosity=1)
835
        self.inner_test.run(result)
836
        note("outer finish")
837
838
    def test_trace_nesting(self):
839
        # this tests that each test case nests its trace facility correctly.
840
        # we do this by running a test case manually. That test case (A)
841
        # should setup a new log, log content to it, setup a child case (B),
842
        # which should log independently, then case (A) should log a trailer
843
        # and return.
844
        # we do two nested children so that we can verify the state of the 
845
        # logs after the outer child finishes is correct, which a bad clean
846
        # up routine in tearDown might trigger a fault in our test with only
847
        # one child, we should instead see the bad result inside our test with
848
        # the two children.
849
        # the outer child test
850
        original_trace = bzrlib.trace._trace_file
851
        outer_test = TestTestCase("outer_child")
2095.4.1 by Martin Pool
Better progress bars during tests
852
        result = bzrlib.tests.TextTestResult(self._log_file,
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
853
                                        descriptions=0,
854
                                        verbosity=1)
855
        outer_test.run(result)
856
        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)
857
858
    def method_that_times_a_bit_twice(self):
859
        # 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.
860
        self.time(time.sleep, 0.007)
861
        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)
862
863
    def test_time_creates_benchmark_in_result(self):
864
        """Test that the TestCase.time() method accumulates a benchmark time."""
865
        sample_test = TestTestCase("method_that_times_a_bit_twice")
866
        output_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
867
        result = bzrlib.tests.VerboseTestResult(
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)
868
            unittest._WritelnDecorator(output_stream),
869
            descriptions=0,
2095.4.1 by Martin Pool
Better progress bars during tests
870
            verbosity=2,
871
            num_tests=sample_test.countTestCases())
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)
872
        sample_test.run(result)
873
        self.assertContainsRe(
874
            output_stream.getvalue(),
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
875
            r"\d+ms/ +\d+ms\n$")
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
876
877
    def test_hooks_sanitised(self):
878
        """The bzrlib hooks should be sanitised by setUp."""
2245.1.2 by Robert Collins
Remove the static DefaultHooks method from Branch, replacing it with a derived dict BranchHooks object, which is easier to use and provides a place to put the policy-checking add method discussed on list.
879
        self.assertEqual(bzrlib.branch.BranchHooks(),
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
880
            bzrlib.branch.Branch.hooks)
881
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
882
    def test__gather_lsprof_in_benchmarks(self):
883
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
884
        
885
        Each self.time() call is individually and separately profiled.
886
        """
887
        try:
888
            import bzrlib.lsprof
889
        except ImportError:
890
            raise TestSkipped("lsprof not installed.")
891
        # overrides the class member with an instance member so no cleanup 
892
        # needed.
893
        self._gather_lsprof_in_benchmarks = True
894
        self.time(time.sleep, 0.000)
895
        self.time(time.sleep, 0.003)
896
        self.assertEqual(2, len(self._benchcalls))
897
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
898
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
899
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
900
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
901
1534.11.4 by Robert Collins
Merge from mainline.
902
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
903
@symbol_versioning.deprecated_function(zero_eleven)
904
def sample_deprecated_function():
905
    """A deprecated function to test applyDeprecated with."""
906
    return 2
907
908
909
def sample_undeprecated_function(a_param):
910
    """A undeprecated function to test applyDeprecated with."""
911
912
913
class ApplyDeprecatedHelper(object):
914
    """A helper class for ApplyDeprecated tests."""
915
916
    @symbol_versioning.deprecated_method(zero_eleven)
917
    def sample_deprecated_method(self, param_one):
918
        """A deprecated method for testing with."""
919
        return param_one
920
921
    def sample_normal_method(self):
922
        """A undeprecated method."""
923
924
    @symbol_versioning.deprecated_method(zero_ten)
925
    def sample_nested_deprecation(self):
926
        return sample_deprecated_function()
927
928
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
929
class TestExtraAssertions(TestCase):
930
    """Tests for new test assertions in bzrlib test suite"""
931
932
    def test_assert_isinstance(self):
933
        self.assertIsInstance(2, int)
934
        self.assertIsInstance(u'', basestring)
935
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
936
        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
937
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
938
    def test_assertEndsWith(self):
939
        self.assertEndsWith('foo', 'oo')
940
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
941
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
942
    def test_applyDeprecated_not_deprecated(self):
943
        sample_object = ApplyDeprecatedHelper()
944
        # calling an undeprecated callable raises an assertion
945
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
946
            sample_object.sample_normal_method)
947
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
948
            sample_undeprecated_function, "a param value")
949
        # calling a deprecated callable (function or method) with the wrong
950
        # expected deprecation fails.
951
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
952
            sample_object.sample_deprecated_method, "a param value")
953
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
954
            sample_deprecated_function)
955
        # calling a deprecated callable (function or method) with the right
956
        # expected deprecation returns the functions result.
957
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
958
            sample_object.sample_deprecated_method, "a param value"))
959
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
960
            sample_deprecated_function))
961
        # calling a nested deprecation with the wrong deprecation version
962
        # fails even if a deeper nested function was deprecated with the 
963
        # supplied version.
964
        self.assertRaises(AssertionError, self.applyDeprecated,
965
            zero_eleven, sample_object.sample_nested_deprecation)
966
        # calling a nested deprecation with the right deprecation value
967
        # returns the calls result.
968
        self.assertEqual(2, self.applyDeprecated(zero_ten,
969
            sample_object.sample_nested_deprecation))
970
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
971
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
972
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
973
            if be_deprecated is True:
974
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
975
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
976
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
977
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
978
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
979
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
980
        self.assertEqual('result', result)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
981
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
982
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
983
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
984
985
class TestConvenienceMakers(TestCaseWithTransport):
986
    """Test for the make_* convenience functions."""
987
988
    def test_make_branch_and_tree_with_format(self):
989
        # we should be able to supply a format to make_branch_and_tree
990
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
991
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
992
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
993
                              bzrlib.bzrdir.BzrDirMetaFormat1)
994
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
995
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
996
1986.2.1 by Robert Collins
Bugfix - the name of the test for make_branch_and_memory_tree was wrong.
997
    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
998
        # we should be able to get a new branch and a mutable tree from
999
        # TestCaseWithTransport
1000
        tree = self.make_branch_and_memory_tree('a')
1001
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1002
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1003
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
1004
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1005
1006
    def test_make_tree_for_sftp_branch(self):
1007
        """Transports backed by local directories create local trees."""
1008
1009
        tree = self.make_branch_and_tree('t1')
1010
        base = tree.bzrdir.root_transport.base
1011
        self.failIf(base.startswith('sftp'),
1012
                'base %r is on sftp but should be local' % base)
1013
        self.assertEquals(tree.bzrdir.root_transport,
1014
                tree.branch.bzrdir.root_transport)
1015
        self.assertEquals(tree.bzrdir.root_transport,
1016
                tree.branch.repository.bzrdir.root_transport)
1017
1018
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1019
class TestSelftest(TestCase):
1020
    """Tests of bzrlib.tests.selftest."""
1021
1022
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1023
        factory_called = []
1024
        def factory():
1025
            factory_called.append(True)
1026
            return TestSuite()
1027
        out = StringIO()
1028
        err = StringIO()
1029
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
1030
            test_suite_factory=factory)
1031
        self.assertEqual([True], factory_called)
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
1032
1033
1034
class TestSelftestCleanOutput(TestCaseInTempDir):
1035
1036
    def test_clean_output(self):
1037
        # test functionality of clean_selftest_output()
1038
        from bzrlib.tests import clean_selftest_output
1039
1040
        dirs = ('test0000.tmp', 'test0001.tmp', 'bzrlib', 'tests')
1041
        files = ('bzr', 'setup.py', 'test9999.tmp')
1042
        for i in dirs:
1043
            os.mkdir(i)
1044
        for i in files:
1045
            f = file(i, 'wb')
1046
            f.write('content of ')
1047
            f.write(i)
1048
            f.close()
1049
1050
        root = os.getcwdu()
1051
        before = os.listdir(root)
2172.4.5 by Alexander Belchenko
Small fix: output of os.listdir() should be sorted manually
1052
        before.sort()
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
1053
        self.assertEquals(['bzr','bzrlib','setup.py',
1054
                           'test0000.tmp','test0001.tmp',
1055
                           'test9999.tmp','tests'],
1056
                           before)
1057
        clean_selftest_output(root, quiet=True)
1058
        after = os.listdir(root)
2172.4.5 by Alexander Belchenko
Small fix: output of os.listdir() should be sorted manually
1059
        after.sort()
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
1060
        self.assertEquals(['bzr','bzrlib','setup.py',
1061
                           'test9999.tmp','tests'],
1062
                           after)