/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1
# Copyright (C) 2005, 2006 by Canonical Ltd
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License version 2 as published by
5
# the Free Software Foundation.
6
#
7
# This program is distributed in the hope that it will be useful,
8
# but WITHOUT ANY WARRANTY; without even the implied warranty of
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
# GNU General Public License for more details.
11
#
12
# You should have received a copy of the GNU General Public License
13
# along with this program; if not, write to the Free Software
14
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
16
"""Tests for the test framework."""
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
17
18
import os
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
19
from StringIO import StringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
20
import sys
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
21
import time
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
22
import unittest
1185.62.24 by John Arbash Meinel
Changing the exception that sftp.py throws when it can't find paramiko, so that the test suite can handle it.
23
import warnings
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
24
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.
25
import bzrlib
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
26
from bzrlib.progress import _BaseProgressBar
1526.1.3 by Robert Collins
Merge from upstream.
27
from bzrlib.tests import (
1534.4.31 by Robert Collins
cleanedup test_outside_wt
28
                          ChrootedTestCase,
1526.1.3 by Robert Collins
Merge from upstream.
29
                          TestCase,
30
                          TestCaseInTempDir,
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
31
                          TestCaseWithTransport,
1526.1.3 by Robert Collins
Merge from upstream.
32
                          TestSkipped,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
33
                          TestSuite,
1526.1.3 by Robert Collins
Merge from upstream.
34
                          TextTestRunner,
35
                          )
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
36
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.
37
import bzrlib.errors as errors
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
38
39
40
class SelftestTests(TestCase):
41
42
    def test_import_tests(self):
43
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
44
        self.assertEqual(mod.SelftestTests, SelftestTests)
45
46
    def test_import_test_failure(self):
47
        self.assertRaises(ImportError,
48
                          _load_module_by_name,
49
                          'bzrlib.no-name-yet')
50
51
52
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.
53
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
54
    def test_logging(self):
55
        """Test logs are captured when a test fails."""
56
        self.log('a test message')
57
        self._log_file.flush()
58
        self.assertContainsRe(self._get_log(), 'a test message\n')
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
59
60
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.
61
class TestTreeShape(TestCaseInTempDir):
62
63
    def test_unicode_paths(self):
64
        filename = u'hell\u00d8'
1526.1.4 by Robert Collins
forgot my self.
65
        try:
66
            self.build_tree_contents([(filename, 'contents of hello')])
67
        except UnicodeEncodeError:
68
            raise TestSkipped("can't build unicode working tree in "
69
                "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.
70
        self.failUnlessExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
71
72
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
73
class TestTransportProviderAdapter(TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
74
    """A group of tests that test the transport implementation adaption core.
75
1551.1.1 by Martin Pool
[merge] branch-formats branch, and reconcile changes
76
    This is a meta test that the tests are applied to all available 
77
    transports.
78
1530.1.21 by Robert Collins
Review feedback fixes.
79
    This will be generalised in the future which is why it is in this 
80
    test file even though it is specific to transport tests at the moment.
81
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
82
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.
83
    def test_get_transport_permutations(self):
1530.1.21 by Robert Collins
Review feedback fixes.
84
        # this checks that we the module get_test_permutations call
85
        # 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.
86
        class MockModule(object):
87
            def get_test_permutations(self):
88
                return sample_permutation
89
        sample_permutation = [(1,2), (3,4)]
90
        from bzrlib.transport import TransportTestProviderAdapter
91
        adapter = TransportTestProviderAdapter()
92
        self.assertEqual(sample_permutation,
93
                         adapter.get_transport_test_permutations(MockModule()))
94
95
    def test_adapter_checks_all_modules(self):
1530.1.21 by Robert Collins
Review feedback fixes.
96
        # this checks that the adapter returns as many permurtations as
97
        # there are in all the registered# transport modules for there
98
        # - we assume if this matches its probably doing the right thing
99
        # especially in combination with the tests for setting the right
100
        # 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.
101
        from bzrlib.transport import (TransportTestProviderAdapter,
102
                                      _get_transport_modules
103
                                      )
104
        modules = _get_transport_modules()
105
        permutation_count = 0
106
        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.
107
            try:
108
                permutation_count += len(reduce(getattr, 
109
                    (module + ".get_test_permutations").split('.')[1:],
110
                     __import__(module))())
111
            except errors.DependencyNotPresent:
112
                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.
113
        input_test = TestTransportProviderAdapter(
114
            "test_adapter_sets_transport_class")
115
        adapter = TransportTestProviderAdapter()
116
        self.assertEqual(permutation_count,
117
                         len(list(iter(adapter.adapt(input_test)))))
118
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
119
    def test_adapter_sets_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
120
        # Check that the test adapter inserts a transport and server into the
121
        # generated test.
122
        #
123
        # This test used to know about all the possible transports and the
124
        # order they were returned but that seems overly brittle (mbp
125
        # 20060307)
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
126
        input_test = TestTransportProviderAdapter(
127
            "test_adapter_sets_transport_class")
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
128
        from bzrlib.transport import TransportTestProviderAdapter
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
129
        suite = TransportTestProviderAdapter().adapt(input_test)
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
130
        tests = list(iter(suite))
131
        self.assertTrue(len(tests) > 6)
132
        # there are at least that many builtin transports
133
        one_test = tests[0]
134
        self.assertTrue(issubclass(one_test.transport_class, 
135
                                   bzrlib.transport.Transport))
136
        self.assertTrue(issubclass(one_test.transport_server, 
137
                                   bzrlib.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
138
139
140
class TestBranchProviderAdapter(TestCase):
141
    """A group of tests that test the branch implementation test adapter."""
142
143
    def test_adapted_tests(self):
144
        # check that constructor parameters are passed through to the adapted
145
        # test.
146
        from bzrlib.branch import BranchTestProviderAdapter
147
        input_test = TestBranchProviderAdapter(
148
            "test_adapted_tests")
149
        server1 = "a"
150
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
151
        formats = [("c", "C"), ("d", "D")]
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
152
        adapter = BranchTestProviderAdapter(server1, server2, formats)
153
        suite = adapter.adapt(input_test)
154
        tests = list(iter(suite))
155
        self.assertEqual(2, len(tests))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
156
        self.assertEqual(tests[0].branch_format, formats[0][0])
157
        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.
158
        self.assertEqual(tests[0].transport_server, server1)
159
        self.assertEqual(tests[0].transport_readonly_server, server2)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
160
        self.assertEqual(tests[1].branch_format, formats[1][0])
161
        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.
162
        self.assertEqual(tests[1].transport_server, server1)
163
        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.
164
165
1534.4.39 by Robert Collins
Basic BzrDir support.
166
class TestBzrDirProviderAdapter(TestCase):
167
    """A group of tests that test the bzr dir implementation test adapter."""
168
169
    def test_adapted_tests(self):
170
        # check that constructor parameters are passed through to the adapted
171
        # test.
172
        from bzrlib.bzrdir import BzrDirTestProviderAdapter
173
        input_test = TestBzrDirProviderAdapter(
174
            "test_adapted_tests")
175
        server1 = "a"
176
        server2 = "b"
177
        formats = ["c", "d"]
178
        adapter = BzrDirTestProviderAdapter(server1, server2, formats)
179
        suite = adapter.adapt(input_test)
180
        tests = list(iter(suite))
181
        self.assertEqual(2, len(tests))
182
        self.assertEqual(tests[0].bzrdir_format, formats[0])
183
        self.assertEqual(tests[0].transport_server, server1)
184
        self.assertEqual(tests[0].transport_readonly_server, server2)
185
        self.assertEqual(tests[1].bzrdir_format, formats[1])
186
        self.assertEqual(tests[1].transport_server, server1)
187
        self.assertEqual(tests[1].transport_readonly_server, server2)
188
189
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
190
class TestRepositoryProviderAdapter(TestCase):
191
    """A group of tests that test the repository implementation test adapter."""
192
193
    def test_adapted_tests(self):
194
        # check that constructor parameters are passed through to the adapted
195
        # test.
196
        from bzrlib.repository import RepositoryTestProviderAdapter
197
        input_test = TestRepositoryProviderAdapter(
198
            "test_adapted_tests")
199
        server1 = "a"
200
        server2 = "b"
201
        formats = [("c", "C"), ("d", "D")]
202
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
203
        suite = adapter.adapt(input_test)
204
        tests = list(iter(suite))
205
        self.assertEqual(2, len(tests))
206
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
207
        self.assertEqual(tests[0].repository_format, formats[0][0])
208
        self.assertEqual(tests[0].transport_server, server1)
209
        self.assertEqual(tests[0].transport_readonly_server, server2)
210
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
211
        self.assertEqual(tests[1].repository_format, formats[1][0])
212
        self.assertEqual(tests[1].transport_server, server1)
213
        self.assertEqual(tests[1].transport_readonly_server, server2)
214
215
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
216
class TestInterRepositoryProviderAdapter(TestCase):
217
    """A group of tests that test the InterRepository test adapter."""
218
219
    def test_adapted_tests(self):
220
        # check that constructor parameters are passed through to the adapted
221
        # test.
222
        from bzrlib.repository import InterRepositoryTestProviderAdapter
223
        input_test = TestInterRepositoryProviderAdapter(
224
            "test_adapted_tests")
225
        server1 = "a"
226
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
227
        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.
228
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
229
        suite = adapter.adapt(input_test)
230
        tests = list(iter(suite))
231
        self.assertEqual(2, len(tests))
232
        self.assertEqual(tests[0].interrepo_class, formats[0][0])
233
        self.assertEqual(tests[0].repository_format, formats[0][1])
234
        self.assertEqual(tests[0].repository_format_to, formats[0][2])
235
        self.assertEqual(tests[0].transport_server, server1)
236
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
237
        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.
238
        self.assertEqual(tests[1].repository_format, formats[1][1])
239
        self.assertEqual(tests[1].repository_format_to, formats[1][2])
240
        self.assertEqual(tests[1].transport_server, server1)
241
        self.assertEqual(tests[1].transport_readonly_server, server2)
242
243
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.
244
class TestInterVersionedFileProviderAdapter(TestCase):
245
    """A group of tests that test the InterVersionedFile test adapter."""
246
247
    def test_adapted_tests(self):
248
        # check that constructor parameters are passed through to the adapted
249
        # test.
250
        from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
251
        input_test = TestInterRepositoryProviderAdapter(
252
            "test_adapted_tests")
253
        server1 = "a"
254
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
255
        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.
256
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
257
        suite = adapter.adapt(input_test)
258
        tests = list(iter(suite))
259
        self.assertEqual(2, len(tests))
260
        self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
261
        self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
262
        self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
263
        self.assertEqual(tests[0].transport_server, server1)
264
        self.assertEqual(tests[0].transport_readonly_server, server2)
1563.2.20 by Robert Collins
Add a revision store test adapter.
265
        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.
266
        self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
267
        self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
268
        self.assertEqual(tests[1].transport_server, server1)
269
        self.assertEqual(tests[1].transport_readonly_server, server2)
270
271
1563.2.20 by Robert Collins
Add a revision store test adapter.
272
class TestRevisionStoreProviderAdapter(TestCase):
273
    """A group of tests that test the RevisionStore test adapter."""
274
275
    def test_adapted_tests(self):
276
        # check that constructor parameters are passed through to the adapted
277
        # test.
278
        from bzrlib.store.revision import RevisionStoreTestProviderAdapter
279
        input_test = TestRevisionStoreProviderAdapter(
280
            "test_adapted_tests")
281
        # revision stores need a store factory - i.e. RevisionKnit
282
        #, a readonly and rw transport 
283
        # transport servers:
284
        server1 = "a"
285
        server2 = "b"
286
        store_factories = ["c", "d"]
287
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
288
        suite = adapter.adapt(input_test)
289
        tests = list(iter(suite))
290
        self.assertEqual(2, len(tests))
291
        self.assertEqual(tests[0].store_factory, store_factories[0][0])
292
        self.assertEqual(tests[0].transport_server, server1)
293
        self.assertEqual(tests[0].transport_readonly_server, server2)
294
        self.assertEqual(tests[1].store_factory, store_factories[1][0])
295
        self.assertEqual(tests[1].transport_server, server1)
296
        self.assertEqual(tests[1].transport_readonly_server, server2)
297
298
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
299
class TestWorkingTreeProviderAdapter(TestCase):
300
    """A group of tests that test the workingtree implementation test adapter."""
301
302
    def test_adapted_tests(self):
303
        # check that constructor parameters are passed through to the adapted
304
        # test.
305
        from bzrlib.workingtree import WorkingTreeTestProviderAdapter
306
        input_test = TestWorkingTreeProviderAdapter(
307
            "test_adapted_tests")
308
        server1 = "a"
309
        server2 = "b"
310
        formats = [("c", "C"), ("d", "D")]
311
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
312
        suite = adapter.adapt(input_test)
313
        tests = list(iter(suite))
314
        self.assertEqual(2, len(tests))
315
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
316
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
317
        self.assertEqual(tests[0].transport_server, server1)
318
        self.assertEqual(tests[0].transport_readonly_server, server2)
319
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
320
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
321
        self.assertEqual(tests[1].transport_server, server1)
322
        self.assertEqual(tests[1].transport_readonly_server, server2)
323
324
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
325
class TestTestCaseWithTransport(TestCaseWithTransport):
326
    """Tests for the convenience functions TestCaseWithTransport introduces."""
327
328
    def test_get_readonly_url_none(self):
329
        from bzrlib.transport import get_transport
330
        from bzrlib.transport.memory import MemoryServer
331
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
332
        self.transport_server = MemoryServer
333
        self.transport_readonly_server = None
334
        # calling get_readonly_transport() constructs a decorator on the url
335
        # for the server
336
        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.
337
        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.
338
        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.
339
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
340
        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.
341
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
342
        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.
343
344
    def test_get_readonly_url_http(self):
345
        from bzrlib.transport import get_transport
346
        from bzrlib.transport.local import LocalRelpathServer
1540.3.6 by Martin Pool
[merge] update from bzr.dev
347
        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.
348
        self.transport_server = LocalRelpathServer
349
        self.transport_readonly_server = HttpServer
350
        # calling get_readonly_transport() gives us a HTTP server instance.
351
        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.
352
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
353
        # 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.
354
        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.
355
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
356
        self.failUnless(isinstance(t, HttpTransportBase))
357
        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.
358
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
359
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
360
    def test_is_directory(self):
361
        """Test assertIsDirectory assertion"""
362
        t = self.get_transport()
363
        self.build_tree(['a_dir/', 'a_file'], transport=t)
364
        self.assertIsDirectory('a_dir', t)
365
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
366
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
367
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
368
1534.4.31 by Robert Collins
cleanedup test_outside_wt
369
class TestChrootedTest(ChrootedTestCase):
370
371
    def test_root_is_root(self):
372
        from bzrlib.transport import get_transport
373
        t = get_transport(self.get_readonly_url())
374
        url = t.base
375
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
376
377
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
378
class MockProgress(_BaseProgressBar):
379
    """Progress-bar standin that records calls.
380
381
    Useful for testing pb using code.
382
    """
383
384
    def __init__(self):
385
        _BaseProgressBar.__init__(self)
386
        self.calls = []
387
388
    def tick(self):
389
        self.calls.append(('tick',))
390
391
    def update(self, msg=None, current=None, total=None):
392
        self.calls.append(('update', msg, current, total))
393
394
    def clear(self):
395
        self.calls.append(('clear',))
396
397
398
class TestResult(TestCase):
399
400
    def test_progress_bar_style_quiet(self):
401
        # test using a progress bar.
402
        dummy_test = TestResult('test_progress_bar_style_quiet')
403
        dummy_error = (Exception, None, [])
404
        mypb = MockProgress()
405
        mypb.update('Running tests', 0, 4)
406
        last_calls = mypb.calls[:]
407
        result = bzrlib.tests._MyResult(self._log_file,
408
                                        descriptions=0,
409
                                        verbosity=1,
410
                                        pb=mypb)
411
        self.assertEqual(last_calls, mypb.calls)
412
413
        # an error 
414
        result.startTest(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
415
        # starting a test prints the test name
416
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 0, None)], mypb.calls)
417
        last_calls = mypb.calls[:]
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
418
        result.addError(dummy_test, dummy_error)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
419
        self.assertEqual(last_calls + [('update', 'ERROR        ', 1, None)], mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
420
        last_calls = mypb.calls[:]
421
422
        # a failure
423
        result.startTest(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
424
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 1, None)], mypb.calls)
425
        last_calls = mypb.calls[:]
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
426
        result.addFailure(dummy_test, dummy_error)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
427
        self.assertEqual(last_calls + [('update', 'FAIL         ', 2, None)], mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
428
        last_calls = mypb.calls[:]
429
430
        # a success
431
        result.startTest(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
432
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 2, None)], mypb.calls)
433
        last_calls = mypb.calls[:]
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
434
        result.addSuccess(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
435
        self.assertEqual(last_calls + [('update', 'OK           ', 3, None)], mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
436
        last_calls = mypb.calls[:]
437
438
        # a skip
439
        result.startTest(dummy_test)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
440
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 3, None)], mypb.calls)
441
        last_calls = mypb.calls[:]
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
442
        result.addSkipped(dummy_test, dummy_error)
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
443
        self.assertEqual(last_calls + [('update', 'SKIP         ', 4, None)], mypb.calls)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
444
        last_calls = mypb.calls[:]
445
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
446
    def test_elapsed_time_with_benchmarking(self):
447
        result = bzrlib.tests._MyResult(self._log_file,
448
                                        descriptions=0,
449
                                        verbosity=1,
450
                                        )
451
        result._recordTestStartTime()
452
        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)
453
        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).
454
        timed_string = result._testTimeString()
455
        # 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)
456
        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).
457
        # 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)
458
        self.time(time.sleep, 0.001)
459
        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).
460
        timed_string = result._testTimeString()
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)
461
        self.assertContainsRe(timed_string, "^    [0-9]ms/   [ 1-9][0-9]ms$")
462
        # 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).
463
        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)
464
        result.extractBenchmarkTime(
465
            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).
466
        timed_string = result._testTimeString()
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)
467
        self.assertContainsRe(timed_string, "^          [0-9]ms$")
468
        # cheat. Yes, wash thy mouth out with soap.
469
        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).
470
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
471
472
class TestRunner(TestCase):
473
474
    def dummy_test(self):
475
        pass
476
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
477
    def run_test_runner(self, testrunner, test):
478
        """Run suite in testrunner, saving global state and restoring it.
479
480
        This current saves and restores:
481
        TestCaseInTempDir.TEST_ROOT
482
        
483
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
484
        without using this convenience method, because of our use of global state.
485
        """
486
        old_root = TestCaseInTempDir.TEST_ROOT
487
        try:
488
            TestCaseInTempDir.TEST_ROOT = None
489
            return testrunner.run(test)
490
        finally:
491
            TestCaseInTempDir.TEST_ROOT = old_root
492
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
493
    def test_accepts_and_uses_pb_parameter(self):
494
        test = TestRunner('dummy_test')
495
        mypb = MockProgress()
496
        self.assertEqual([], mypb.calls)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
497
        runner = TextTestRunner(stream=self._log_file, pb=mypb)
498
        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.
499
        self.assertEqual(1, result.testsRun)
500
        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.
501
        self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
502
        self.assertEqual(('update', 'OK           ', 1, None), mypb.calls[2])
503
        self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
504
        self.assertEqual(('clear',), mypb.calls[4])
505
        self.assertEqual(5, len(mypb.calls))
1534.11.4 by Robert Collins
Merge from mainline.
506
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
507
    def test_skipped_test(self):
508
        # run a test that is skipped, and check the suite as a whole still
509
        # succeeds.
510
        # skipping_test must be hidden in here so it's not run as a real test
511
        def skipping_test():
512
            raise TestSkipped('test intentionally skipped')
513
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
514
        test = unittest.FunctionTestCase(skipping_test)
515
        result = self.run_test_runner(runner, test)
516
        self.assertTrue(result.wasSuccessful())
517
518
519
class TestTestCase(TestCase):
520
    """Tests that test the core bzrlib TestCase."""
521
522
    def inner_test(self):
523
        # the inner child test
524
        note("inner_test")
525
526
    def outer_child(self):
527
        # the outer child test
528
        note("outer_start")
529
        self.inner_test = TestTestCase("inner_child")
530
        result = bzrlib.tests._MyResult(self._log_file,
531
                                        descriptions=0,
532
                                        verbosity=1)
533
        self.inner_test.run(result)
534
        note("outer finish")
535
536
    def test_trace_nesting(self):
537
        # this tests that each test case nests its trace facility correctly.
538
        # we do this by running a test case manually. That test case (A)
539
        # should setup a new log, log content to it, setup a child case (B),
540
        # which should log independently, then case (A) should log a trailer
541
        # and return.
542
        # we do two nested children so that we can verify the state of the 
543
        # logs after the outer child finishes is correct, which a bad clean
544
        # up routine in tearDown might trigger a fault in our test with only
545
        # one child, we should instead see the bad result inside our test with
546
        # the two children.
547
        # the outer child test
548
        original_trace = bzrlib.trace._trace_file
549
        outer_test = TestTestCase("outer_child")
550
        result = bzrlib.tests._MyResult(self._log_file,
551
                                        descriptions=0,
552
                                        verbosity=1)
553
        outer_test.run(result)
554
        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)
555
556
    def method_that_times_a_bit_twice(self):
557
        # 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.
558
        self.time(time.sleep, 0.007)
559
        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)
560
561
    def test_time_creates_benchmark_in_result(self):
562
        """Test that the TestCase.time() method accumulates a benchmark time."""
563
        sample_test = TestTestCase("method_that_times_a_bit_twice")
564
        output_stream = StringIO()
565
        result = bzrlib.tests._MyResult(
566
            unittest._WritelnDecorator(output_stream),
567
            descriptions=0,
568
            verbosity=2)
569
        sample_test.run(result)
570
        self.assertContainsRe(
571
            output_stream.getvalue(),
572
            "[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.
573
        
1534.11.4 by Robert Collins
Merge from mainline.
574
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
575
class TestExtraAssertions(TestCase):
576
    """Tests for new test assertions in bzrlib test suite"""
577
578
    def test_assert_isinstance(self):
579
        self.assertIsInstance(2, int)
580
        self.assertIsInstance(u'', basestring)
581
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
582
        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
583
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
584
    def test_assertEndsWith(self):
585
        self.assertEndsWith('foo', 'oo')
586
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
587
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
588
589
class TestConvenienceMakers(TestCaseWithTransport):
590
    """Test for the make_* convenience functions."""
591
592
    def test_make_branch_and_tree_with_format(self):
593
        # we should be able to supply a format to make_branch_and_tree
594
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
595
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
596
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
597
                              bzrlib.bzrdir.BzrDirMetaFormat1)
598
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
599
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
600
601
602
class TestSelftest(TestCase):
603
    """Tests of bzrlib.tests.selftest."""
604
605
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
606
        factory_called = []
607
        def factory():
608
            factory_called.append(True)
609
            return TestSuite()
610
        out = StringIO()
611
        err = StringIO()
612
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
613
            test_suite_factory=factory)
614
        self.assertEqual([True], factory_called)