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