/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
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
398
class TestTestResult(TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
399
400
    def test_progress_bar_style_quiet(self):
401
        # test using a progress bar.
1728.1.2 by Robert Collins
Bugfix missing search-and-replace of TestResult.
402
        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.
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()
1740.2.5 by Aaron Bentley
Merge from bzr.dev
461
        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)
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()
1740.2.5 by Aaron Bentley
Merge from bzr.dev
467
        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)
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
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
471
    def _time_hello_world_encoding(self):
472
        """Profile two sleep calls
473
        
474
        This is used to exercise the test framework.
475
        """
476
        self.time(unicode, 'hello', errors='replace')
477
        self.time(unicode, 'world', errors='replace')
478
479
    def test_lsprofiling(self):
480
        """Verbose test result prints lsprof statistics from test cases."""
481
        try:
482
            import bzrlib.lsprof
483
        except ImportError:
484
            raise TestSkipped("lsprof not installed.")
485
        result_stream = StringIO()
486
        result = bzrlib.tests._MyResult(
487
            unittest._WritelnDecorator(result_stream),
488
            descriptions=0,
489
            verbosity=2,
490
            )
491
        # we want profile a call of some sort and check it is output by
492
        # addSuccess. We dont care about addError or addFailure as they
493
        # are not that interesting for performance tuning.
494
        # make a new test instance that when run will generate a profile
495
        example_test_case = TestTestResult("_time_hello_world_encoding")
496
        example_test_case._gather_lsprof_in_benchmarks = True
497
        # execute the test, which should succeed and record profiles
498
        example_test_case.run(result)
499
        # lsprofile_something()
500
        # if this worked we want 
501
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
502
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
503
        # (the lsprof header)
504
        # ... an arbitrary number of lines
505
        # and the function call which is time.sleep.
506
        #           1        0            ???         ???       ???(sleep) 
507
        # and then repeated but with 'world', rather than 'hello'.
508
        # this should appear in the output stream of our test result.
509
        self.assertContainsRe(result_stream.getvalue(), 
510
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)\n"
511
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n"
1551.6.28 by Aaron Bentley
Make lsprof test handle more lsprof variants
512
            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
513
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n"
514
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n"
1551.6.28 by Aaron Bentley
Make lsprof test handle more lsprof variants
515
            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
516
            )
517
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
518
519
class TestRunner(TestCase):
520
521
    def dummy_test(self):
522
        pass
523
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
524
    def run_test_runner(self, testrunner, test):
525
        """Run suite in testrunner, saving global state and restoring it.
526
527
        This current saves and restores:
528
        TestCaseInTempDir.TEST_ROOT
529
        
530
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
531
        without using this convenience method, because of our use of global state.
532
        """
533
        old_root = TestCaseInTempDir.TEST_ROOT
534
        try:
535
            TestCaseInTempDir.TEST_ROOT = None
536
            return testrunner.run(test)
537
        finally:
538
            TestCaseInTempDir.TEST_ROOT = old_root
539
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
540
    def test_accepts_and_uses_pb_parameter(self):
541
        test = TestRunner('dummy_test')
542
        mypb = MockProgress()
543
        self.assertEqual([], mypb.calls)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
544
        runner = TextTestRunner(stream=self._log_file, pb=mypb)
545
        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.
546
        self.assertEqual(1, result.testsRun)
547
        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.
548
        self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
549
        self.assertEqual(('update', 'OK           ', 1, None), mypb.calls[2])
550
        self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
551
        self.assertEqual(('clear',), mypb.calls[4])
552
        self.assertEqual(5, len(mypb.calls))
1534.11.4 by Robert Collins
Merge from mainline.
553
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
554
    def test_skipped_test(self):
555
        # run a test that is skipped, and check the suite as a whole still
556
        # succeeds.
557
        # skipping_test must be hidden in here so it's not run as a real test
558
        def skipping_test():
559
            raise TestSkipped('test intentionally skipped')
560
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
561
        test = unittest.FunctionTestCase(skipping_test)
562
        result = self.run_test_runner(runner, test)
563
        self.assertTrue(result.wasSuccessful())
564
565
566
class TestTestCase(TestCase):
567
    """Tests that test the core bzrlib TestCase."""
568
569
    def inner_test(self):
570
        # the inner child test
571
        note("inner_test")
572
573
    def outer_child(self):
574
        # the outer child test
575
        note("outer_start")
576
        self.inner_test = TestTestCase("inner_child")
577
        result = bzrlib.tests._MyResult(self._log_file,
578
                                        descriptions=0,
579
                                        verbosity=1)
580
        self.inner_test.run(result)
581
        note("outer finish")
582
583
    def test_trace_nesting(self):
584
        # this tests that each test case nests its trace facility correctly.
585
        # we do this by running a test case manually. That test case (A)
586
        # should setup a new log, log content to it, setup a child case (B),
587
        # which should log independently, then case (A) should log a trailer
588
        # and return.
589
        # we do two nested children so that we can verify the state of the 
590
        # logs after the outer child finishes is correct, which a bad clean
591
        # up routine in tearDown might trigger a fault in our test with only
592
        # one child, we should instead see the bad result inside our test with
593
        # the two children.
594
        # the outer child test
595
        original_trace = bzrlib.trace._trace_file
596
        outer_test = TestTestCase("outer_child")
597
        result = bzrlib.tests._MyResult(self._log_file,
598
                                        descriptions=0,
599
                                        verbosity=1)
600
        outer_test.run(result)
601
        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)
602
603
    def method_that_times_a_bit_twice(self):
604
        # 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.
605
        self.time(time.sleep, 0.007)
606
        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)
607
608
    def test_time_creates_benchmark_in_result(self):
609
        """Test that the TestCase.time() method accumulates a benchmark time."""
610
        sample_test = TestTestCase("method_that_times_a_bit_twice")
611
        output_stream = StringIO()
612
        result = bzrlib.tests._MyResult(
613
            unittest._WritelnDecorator(output_stream),
614
            descriptions=0,
615
            verbosity=2)
616
        sample_test.run(result)
617
        self.assertContainsRe(
618
            output_stream.getvalue(),
619
            "[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.
620
        
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
621
    def test__gather_lsprof_in_benchmarks(self):
622
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
623
        
624
        Each self.time() call is individually and separately profiled.
625
        """
626
        try:
627
            import bzrlib.lsprof
628
        except ImportError:
629
            raise TestSkipped("lsprof not installed.")
630
        # overrides the class member with an instance member so no cleanup 
631
        # needed.
632
        self._gather_lsprof_in_benchmarks = True
633
        self.time(time.sleep, 0.000)
634
        self.time(time.sleep, 0.003)
635
        self.assertEqual(2, len(self._benchcalls))
636
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
637
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
638
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
639
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
640
1534.11.4 by Robert Collins
Merge from mainline.
641
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
642
class TestExtraAssertions(TestCase):
643
    """Tests for new test assertions in bzrlib test suite"""
644
645
    def test_assert_isinstance(self):
646
        self.assertIsInstance(2, int)
647
        self.assertIsInstance(u'', basestring)
648
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
649
        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
650
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
651
    def test_assertEndsWith(self):
652
        self.assertEndsWith('foo', 'oo')
653
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
654
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
655
656
class TestConvenienceMakers(TestCaseWithTransport):
657
    """Test for the make_* convenience functions."""
658
659
    def test_make_branch_and_tree_with_format(self):
660
        # we should be able to supply a format to make_branch_and_tree
661
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
662
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
663
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
664
                              bzrlib.bzrdir.BzrDirMetaFormat1)
665
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
666
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
667
668
669
class TestSelftest(TestCase):
670
    """Tests of bzrlib.tests.selftest."""
671
672
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
673
        factory_called = []
674
        def factory():
675
            factory_called.append(True)
676
            return TestSuite()
677
        out = StringIO()
678
        err = StringIO()
679
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
680
            test_suite_factory=factory)
681
        self.assertEqual([True], factory_called)
1752.1.1 by Aaron Bentley
Add run_bzr_external
682
683
    def test_run_bzr_external(self):
684
        """The run_bzr_helper_external comand behaves nicely."""
685
        result = self.run_bzr_external('--version')
686
        self.assertContainsRe(result[0], 'is free software')
687
        self.assertRaises(AssertionError, self.run_bzr_external, '--versionn')
688
        result = self.run_bzr_external('--versionn', retcode=3)
689
        self.assertContainsRe(result[1], 'unknown command')
690
        err = self.run_bzr_external('merge --merge-type "magic merge"', 
691
                                    retcode=3)[1]
692
        self.assertContainsRe(err, 'No known merge type magic merge')
693
        err = self.run_bzr_external('merge', '--merge-type', 'magic merge', 
694
                                    retcode=3)[1]
695
        self.assertContainsRe(err, 'No known merge type magic merge')