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