/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
2
#
3
# This program is free software; you can redistribute it and/or modify
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
17
"""Tests for the test framework."""
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
18
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
19
import cStringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
20
import os
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
21
from StringIO import StringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
22
import sys
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
23
import time
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
24
import unittest
1185.62.24 by John Arbash Meinel
Changing the exception that sftp.py throws when it can't find paramiko, so that the test suite can handle it.
25
import warnings
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
26
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
27
import bzrlib
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
28
from bzrlib import (
29
    bzrdir,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
30
    errors,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
31
    memorytree,
32
    osutils,
33
    repository,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
34
    symbol_versioning,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
35
    )
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
36
from bzrlib.progress import _BaseProgressBar
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
37
from bzrlib.repofmt import weaverepo
2696.1.1 by Martin Pool
Remove things deprecated in 0.11 and earlier
38
from bzrlib.symbol_versioning import (
39
        zero_ten,
40
        zero_eleven,
41
        )
1526.1.3 by Robert Collins
Merge from upstream.
42
from bzrlib.tests import (
1534.4.31 by Robert Collins
cleanedup test_outside_wt
43
                          ChrootedTestCase,
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
44
                          ExtendedTestResult,
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
45
                          Feature,
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
46
                          KnownFailure,
1526.1.3 by Robert Collins
Merge from upstream.
47
                          TestCase,
48
                          TestCaseInTempDir,
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
49
                          TestCaseWithMemoryTransport,
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
50
                          TestCaseWithTransport,
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
51
                          TestNotApplicable,
1526.1.3 by Robert Collins
Merge from upstream.
52
                          TestSkipped,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
53
                          TestSuite,
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
54
                          TestUtil,
1526.1.3 by Robert Collins
Merge from upstream.
55
                          TextTestRunner,
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
56
                          UnavailableFeature,
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
57
                          iter_suite_tests,
58
                          filter_suite_by_re,
59
                          sort_suite_by_re,
2493.2.8 by Aaron Bentley
Convert old lsprof tests to require new LSProf Feature instead of skipping
60
                          test_lsprof,
61
                          test_suite,
1526.1.3 by Robert Collins
Merge from upstream.
62
                          )
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
63
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
64
from bzrlib.tests.TestUtil import _load_module_by_name
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
65
from bzrlib.trace import note
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
66
from bzrlib.transport.memory import MemoryServer, MemoryTransport
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
67
from bzrlib.version import _get_bzr_source_tree
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
68
69
70
class SelftestTests(TestCase):
71
72
    def test_import_tests(self):
73
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
74
        self.assertEqual(mod.SelftestTests, SelftestTests)
75
76
    def test_import_test_failure(self):
77
        self.assertRaises(ImportError,
78
                          _load_module_by_name,
79
                          'bzrlib.no-name-yet')
80
81
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.
82
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
83
    def test_logging(self):
84
        """Test logs are captured when a test fails."""
85
        self.log('a test message')
86
        self._log_file.flush()
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
87
        self.assertContainsRe(self._get_log(keep_log_file=True),
88
                              'a test message\n')
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
89
90
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.
91
class TestTreeShape(TestCaseInTempDir):
92
93
    def test_unicode_paths(self):
94
        filename = u'hell\u00d8'
1526.1.4 by Robert Collins
forgot my self.
95
        try:
96
            self.build_tree_contents([(filename, 'contents of hello')])
97
        except UnicodeEncodeError:
98
            raise TestSkipped("can't build unicode working tree in "
99
                "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.
100
        self.failUnlessExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
101
102
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
103
class TestTransportProviderAdapter(TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
104
    """A group of tests that test the transport implementation adaption core.
105
1551.1.1 by Martin Pool
[merge] branch-formats branch, and reconcile changes
106
    This is a meta test that the tests are applied to all available 
107
    transports.
108
1530.1.21 by Robert Collins
Review feedback fixes.
109
    This will be generalised in the future which is why it is in this 
110
    test file even though it is specific to transport tests at the moment.
111
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
112
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
    def test_get_transport_permutations(self):
1530.1.21 by Robert Collins
Review feedback fixes.
114
        # this checks that we the module get_test_permutations call
115
        # 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.
116
        class MockModule(object):
117
            def get_test_permutations(self):
118
                return sample_permutation
119
        sample_permutation = [(1,2), (3,4)]
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
120
        from bzrlib.tests.test_transport_implementations \
121
            import TransportTestProviderAdapter
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.
122
        adapter = TransportTestProviderAdapter()
123
        self.assertEqual(sample_permutation,
124
                         adapter.get_transport_test_permutations(MockModule()))
125
126
    def test_adapter_checks_all_modules(self):
1530.1.21 by Robert Collins
Review feedback fixes.
127
        # this checks that the adapter returns as many permurtations as
128
        # there are in all the registered# transport modules for there
129
        # - we assume if this matches its probably doing the right thing
130
        # especially in combination with the tests for setting the right
131
        # classes below.
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
132
        from bzrlib.tests.test_transport_implementations \
133
            import TransportTestProviderAdapter
134
        from bzrlib.transport import _get_transport_modules
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.
135
        modules = _get_transport_modules()
136
        permutation_count = 0
137
        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.
138
            try:
139
                permutation_count += len(reduce(getattr, 
140
                    (module + ".get_test_permutations").split('.')[1:],
141
                     __import__(module))())
142
            except errors.DependencyNotPresent:
143
                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.
144
        input_test = TestTransportProviderAdapter(
145
            "test_adapter_sets_transport_class")
146
        adapter = TransportTestProviderAdapter()
147
        self.assertEqual(permutation_count,
148
                         len(list(iter(adapter.adapt(input_test)))))
149
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
150
    def test_adapter_sets_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
151
        # Check that the test adapter inserts a transport and server into the
152
        # generated test.
153
        #
154
        # This test used to know about all the possible transports and the
155
        # order they were returned but that seems overly brittle (mbp
156
        # 20060307)
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
157
        from bzrlib.tests.test_transport_implementations \
158
            import TransportTestProviderAdapter
159
        scenarios = TransportTestProviderAdapter().scenarios
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
160
        # there are at least that many builtin transports
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
161
        self.assertTrue(len(scenarios) > 6)
162
        one_scenario = scenarios[0]
163
        self.assertIsInstance(one_scenario[0], str)
164
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
165
                                   bzrlib.transport.Transport))
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
166
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
167
                                   bzrlib.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
168
169
170
class TestBranchProviderAdapter(TestCase):
171
    """A group of tests that test the branch implementation test adapter."""
172
2553.2.6 by Robert Collins
And overhaul BranchTestProviderAdapter too.
173
    def test_constructor(self):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
174
        # check that constructor parameters are passed through to the adapted
175
        # test.
2553.2.6 by Robert Collins
And overhaul BranchTestProviderAdapter too.
176
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
177
        server1 = "a"
178
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
179
        formats = [("c", "C"), ("d", "D")]
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
180
        adapter = BranchTestProviderAdapter(server1, server2, formats)
2553.2.6 by Robert Collins
And overhaul BranchTestProviderAdapter too.
181
        self.assertEqual(2, len(adapter.scenarios))
182
        self.assertEqual([
183
            ('str',
184
             {'branch_format': 'c',
185
              'bzrdir_format': 'C',
186
              'transport_readonly_server': 'b',
187
              'transport_server': 'a'}),
188
            ('str',
189
             {'branch_format': 'd',
190
              'bzrdir_format': 'D',
191
              'transport_readonly_server': 'b',
192
              'transport_server': 'a'})],
193
            adapter.scenarios)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
194
195
1534.4.39 by Robert Collins
Basic BzrDir support.
196
class TestBzrDirProviderAdapter(TestCase):
197
    """A group of tests that test the bzr dir implementation test adapter."""
198
199
    def test_adapted_tests(self):
200
        # check that constructor parameters are passed through to the adapted
201
        # test.
2553.2.7 by Robert Collins
And overhaul BzrDirTestProviderAdapter too.
202
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
203
        vfs_factory = "v"
1534.4.39 by Robert Collins
Basic BzrDir support.
204
        server1 = "a"
205
        server2 = "b"
206
        formats = ["c", "d"]
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
207
        adapter = BzrDirTestProviderAdapter(vfs_factory,
208
            server1, server2, formats)
2553.2.7 by Robert Collins
And overhaul BzrDirTestProviderAdapter too.
209
        self.assertEqual([
210
            ('str',
211
             {'bzrdir_format': 'c',
212
              'transport_readonly_server': 'b',
213
              'transport_server': 'a',
214
              'vfs_transport_factory': 'v'}),
215
            ('str',
216
             {'bzrdir_format': 'd',
217
              'transport_readonly_server': 'b',
218
              'transport_server': 'a',
219
              'vfs_transport_factory': 'v'})],
220
            adapter.scenarios)
1534.4.39 by Robert Collins
Basic BzrDir support.
221
222
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
223
class TestRepositoryProviderAdapter(TestCase):
224
    """A group of tests that test the repository implementation test adapter."""
225
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
226
    def test_constructor(self):
227
        # check that constructor parameters are passed through to the
228
        # scenarios.
2553.2.2 by Robert Collins
Move RepositoryTestProviderAdapter into the tests part of the code base.
229
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
230
        server1 = "a"
231
        server2 = "b"
232
        formats = [("c", "C"), ("d", "D")]
233
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
234
        self.assertEqual([
235
            ('str',
236
             {'bzrdir_format': 'C',
237
              'repository_format': 'c',
238
              'transport_readonly_server': 'b',
239
              'transport_server': 'a'}),
240
            ('str',
241
             {'bzrdir_format': 'D',
242
              'repository_format': 'd',
243
              'transport_readonly_server': 'b',
244
              'transport_server': 'a'})],
245
            adapter.scenarios)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
246
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
247
    def test_setting_vfs_transport(self):
248
        """The vfs_transport_factory can be set optionally."""
2553.2.2 by Robert Collins
Move RepositoryTestProviderAdapter into the tests part of the code base.
249
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
250
        formats = [("a", "b"), ("c", "d")]
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
251
        adapter = RepositoryTestProviderAdapter(None, None, formats,
252
            vfs_transport_factory="vfs")
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
253
        self.assertEqual([
254
            ('str',
255
             {'bzrdir_format': 'b',
256
              'repository_format': 'a',
257
              'transport_readonly_server': None,
258
              'transport_server': None,
259
              'vfs_transport_factory': 'vfs'}),
260
            ('str',
261
             {'bzrdir_format': 'd',
262
              'repository_format': 'c',
263
              'transport_readonly_server': None,
264
              'transport_server': None,
265
              'vfs_transport_factory': 'vfs'})],
266
            adapter.scenarios)
267
268
    def test_formats_to_scenarios(self):
269
        """The adapter can generate all the scenarios needed."""
2553.2.2 by Robert Collins
Move RepositoryTestProviderAdapter into the tests part of the code base.
270
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
271
        no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
272
            [], None)
273
        vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
274
            [], vfs_transport_factory="vfs")
275
        # no_vfs generate scenarios without vfs_transport_factor
276
        formats = [("c", "C"), (1, "D")]
277
        self.assertEqual([
278
            ('str',
279
             {'bzrdir_format': 'C',
280
              'repository_format': 'c',
281
              'transport_readonly_server': 'readonly',
282
              'transport_server': 'server'}),
283
            ('int',
284
             {'bzrdir_format': 'D',
285
              'repository_format': 1,
286
              'transport_readonly_server': 'readonly',
287
              'transport_server': 'server'})],
288
            no_vfs_adapter.formats_to_scenarios(formats))
289
        self.assertEqual([
290
            ('str',
291
             {'bzrdir_format': 'C',
292
              'repository_format': 'c',
293
              'transport_readonly_server': 'readonly',
294
              'transport_server': 'server',
295
              'vfs_transport_factory': 'vfs'}),
296
            ('int',
297
             {'bzrdir_format': 'D',
298
              'repository_format': 1,
299
              'transport_readonly_server': 'readonly',
300
              'transport_server': 'server',
301
              'vfs_transport_factory': 'vfs'})],
302
            vfs_adapter.formats_to_scenarios(formats))
303
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
304
305
class TestTestScenarioApplier(TestCase):
306
    """Tests for the test adaption facilities."""
307
308
    def test_adapt_applies_scenarios(self):
309
        from bzrlib.tests.repository_implementations import TestScenarioApplier
310
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
311
        adapter = TestScenarioApplier()
312
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
313
        calls = []
314
        def capture_call(test, scenario):
315
            calls.append((test, scenario))
316
            return test
317
        adapter.adapt_test_to_scenario = capture_call
318
        adapter.adapt(input_test)
319
        self.assertEqual([(input_test, ("1", "dict")),
320
            (input_test, ("2", "settings"))], calls)
321
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
322
    def test_adapt_test_to_scenario(self):
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
323
        from bzrlib.tests.repository_implementations import TestScenarioApplier
324
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
325
        adapter = TestScenarioApplier()
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
326
        # setup two adapted tests
327
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
328
            ("new id",
329
            {"bzrdir_format":"bzr_format",
330
             "repository_format":"repo_fmt",
331
             "transport_server":"transport_server",
332
             "transport_readonly_server":"readonly-server"}))
333
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
334
            ("new id 2", {"bzrdir_format":None}))
335
        # input_test should have been altered.
336
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
337
        # the new tests are mutually incompatible, ensuring it has 
338
        # made new ones, and unspecified elements in the scenario
339
        # should not have been altered.
340
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
341
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
342
        self.assertEqual("transport_server", adapted_test1.transport_server)
343
        self.assertEqual("readonly-server",
344
            adapted_test1.transport_readonly_server)
345
        self.assertEqual(
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
346
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
347
            "test_adapt_test_to_scenario(new id)",
348
            adapted_test1.id())
349
        self.assertEqual(None, adapted_test2.bzrdir_format)
350
        self.assertEqual(
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
351
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
352
            "test_adapt_test_to_scenario(new id 2)",
353
            adapted_test2.id())
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
354
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
355
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
356
class TestInterRepositoryProviderAdapter(TestCase):
357
    """A group of tests that test the InterRepository test adapter."""
358
359
    def test_adapted_tests(self):
360
        # check that constructor parameters are passed through to the adapted
361
        # test.
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
362
        from bzrlib.tests.interrepository_implementations import \
363
            InterRepositoryTestProviderAdapter
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
364
        server1 = "a"
365
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
366
        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.
367
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
368
        self.assertEqual([
369
            ('str',
370
             {'interrepo_class': str,
371
              'repository_format': 'C1',
372
              'repository_format_to': 'C2',
373
              'transport_readonly_server': 'b',
374
              'transport_server': 'a'}),
375
            ('int',
376
             {'interrepo_class': int,
377
              'repository_format': 'D1',
378
              'repository_format_to': 'D2',
379
              'transport_readonly_server': 'b',
380
              'transport_server': 'a'})],
381
            adapter.formats_to_scenarios(formats))
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
382
383
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.
384
class TestInterVersionedFileProviderAdapter(TestCase):
385
    """A group of tests that test the InterVersionedFile test adapter."""
386
2553.2.9 by Robert Collins
And overhaul RevisionStoreTestProviderAdapter too.
387
    def test_scenarios(self):
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.
388
        # check that constructor parameters are passed through to the adapted
389
        # test.
2553.2.8 by Robert Collins
And overhaul InterVersionedFileTestProviderAdapter too.
390
        from bzrlib.tests.interversionedfile_implementations \
391
            import InterVersionedFileTestProviderAdapter
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.
392
        server1 = "a"
393
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
394
        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.
395
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
2553.2.8 by Robert Collins
And overhaul InterVersionedFileTestProviderAdapter too.
396
        self.assertEqual([
397
            ('str',
398
             {'interversionedfile_class':str,
399
              'transport_readonly_server': 'b',
400
              'transport_server': 'a',
401
              'versionedfile_factory': 'C1',
402
              'versionedfile_factory_to': 'C2'}),
403
            ('int',
404
             {'interversionedfile_class': int,
405
              'transport_readonly_server': 'b',
406
              'transport_server': 'a',
407
              'versionedfile_factory': 'D1',
408
              'versionedfile_factory_to': 'D2'})],
409
            adapter.scenarios)
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.
410
411
1563.2.20 by Robert Collins
Add a revision store test adapter.
412
class TestRevisionStoreProviderAdapter(TestCase):
413
    """A group of tests that test the RevisionStore test adapter."""
414
2553.2.9 by Robert Collins
And overhaul RevisionStoreTestProviderAdapter too.
415
    def test_scenarios(self):
1563.2.20 by Robert Collins
Add a revision store test adapter.
416
        # check that constructor parameters are passed through to the adapted
417
        # test.
2553.2.9 by Robert Collins
And overhaul RevisionStoreTestProviderAdapter too.
418
        from bzrlib.tests.revisionstore_implementations \
419
            import RevisionStoreTestProviderAdapter
1563.2.20 by Robert Collins
Add a revision store test adapter.
420
        # revision stores need a store factory - i.e. RevisionKnit
421
        #, a readonly and rw transport 
422
        # transport servers:
423
        server1 = "a"
424
        server2 = "b"
425
        store_factories = ["c", "d"]
426
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
2553.2.9 by Robert Collins
And overhaul RevisionStoreTestProviderAdapter too.
427
        self.assertEqual([
428
            ('c',
429
             {'store_factory': 'c',
430
              'transport_readonly_server': 'b',
431
              'transport_server': 'a'}),
432
            ('d',
433
             {'store_factory': 'd',
434
              'transport_readonly_server': 'b',
435
              'transport_server': 'a'})],
436
            adapter.scenarios)
1563.2.20 by Robert Collins
Add a revision store test adapter.
437
438
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
439
class TestWorkingTreeProviderAdapter(TestCase):
440
    """A group of tests that test the workingtree implementation test adapter."""
441
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
442
    def test_scenarios(self):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
443
        # check that constructor parameters are passed through to the adapted
444
        # test.
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
445
        from bzrlib.tests.workingtree_implementations \
446
            import WorkingTreeTestProviderAdapter
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
447
        server1 = "a"
448
        server2 = "b"
449
        formats = [("c", "C"), ("d", "D")]
450
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
451
        self.assertEqual([
452
            ('str',
453
             {'bzrdir_format': 'C',
454
              'transport_readonly_server': 'b',
455
              'transport_server': 'a',
456
              'workingtree_format': 'c'}),
457
            ('str',
458
             {'bzrdir_format': 'D',
459
              'transport_readonly_server': 'b',
460
              'transport_server': 'a',
461
              'workingtree_format': 'd'})],
462
            adapter.scenarios)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
463
464
1852.6.1 by Robert Collins
Start tree implementation tests.
465
class TestTreeProviderAdapter(TestCase):
466
    """Test the setup of tree_implementation tests."""
467
468
    def test_adapted_tests(self):
469
        # the tree implementation adapter is meant to setup one instance for
470
        # each working tree format, and one additional instance that will
471
        # use the default wt format, but create a revision tree for the tests.
472
        # this means that the wt ones should have the workingtree_to_test_tree
473
        # attribute set to 'return_parameter' and the revision one set to
474
        # revision_tree_from_workingtree.
475
476
        from bzrlib.tests.tree_implementations import (
477
            TreeTestProviderAdapter,
478
            return_parameter,
479
            revision_tree_from_workingtree
480
            )
2255.2.164 by Martin Pool
Change the default format for some tests from AB1 back to WorkingTreeFormat3
481
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
1852.6.1 by Robert Collins
Start tree implementation tests.
482
        input_test = TestTreeProviderAdapter(
483
            "test_adapted_tests")
484
        server1 = "a"
485
        server2 = "b"
486
        formats = [("c", "C"), ("d", "D")]
487
        adapter = TreeTestProviderAdapter(server1, server2, formats)
488
        suite = adapter.adapt(input_test)
489
        tests = list(iter(suite))
2255.6.3 by Aaron Bentley
tweak tests
490
        self.assertEqual(4, len(tests))
2255.2.164 by Martin Pool
Change the default format for some tests from AB1 back to WorkingTreeFormat3
491
        # this must match the default format setp up in
492
        # TreeTestProviderAdapter.adapt
493
        default_format = WorkingTreeFormat3
1852.6.1 by Robert Collins
Start tree implementation tests.
494
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
495
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
496
        self.assertEqual(tests[0].transport_server, server1)
497
        self.assertEqual(tests[0].transport_readonly_server, server2)
498
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
499
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
500
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
501
        self.assertEqual(tests[1].transport_server, server1)
502
        self.assertEqual(tests[1].transport_readonly_server, server2)
503
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
504
        self.assertIsInstance(tests[2].workingtree_format, default_format)
505
        #self.assertEqual(tests[2].bzrdir_format,
506
        #                 default_format._matchingbzrdir)
1852.6.1 by Robert Collins
Start tree implementation tests.
507
        self.assertEqual(tests[2].transport_server, server1)
508
        self.assertEqual(tests[2].transport_readonly_server, server2)
509
        self.assertEqual(tests[2].workingtree_to_test_tree,
510
            revision_tree_from_workingtree)
511
512
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
513
class TestInterTreeProviderAdapter(TestCase):
514
    """A group of tests that test the InterTreeTestAdapter."""
515
516
    def test_adapted_tests(self):
517
        # check that constructor parameters are passed through to the adapted
518
        # test.
519
        # for InterTree tests we want the machinery to bring up two trees in
520
        # each instance: the base one, and the one we are interacting with.
521
        # because each optimiser can be direction specific, we need to test
522
        # each optimiser in its chosen direction.
523
        # unlike the TestProviderAdapter we dont want to automatically add a
524
        # parameterised one for WorkingTree - the optimisers will tell us what
525
        # ones to add.
526
        from bzrlib.tests.tree_implementations import (
527
            return_parameter,
528
            revision_tree_from_workingtree
529
            )
530
        from bzrlib.tests.intertree_implementations import (
531
            InterTreeTestProviderAdapter,
532
            )
533
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
534
        input_test = TestInterTreeProviderAdapter(
535
            "test_adapted_tests")
536
        server1 = "a"
537
        server2 = "b"
538
        format1 = WorkingTreeFormat2()
539
        format2 = WorkingTreeFormat3()
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
540
        formats = [(str, format1, format2, "converter1"),
541
            (int, format2, format1, "converter2")]
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
542
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
543
        suite = adapter.adapt(input_test)
544
        tests = list(iter(suite))
545
        self.assertEqual(2, len(tests))
546
        self.assertEqual(tests[0].intertree_class, formats[0][0])
547
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
548
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
549
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
550
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
551
        self.assertEqual(tests[0].transport_server, server1)
552
        self.assertEqual(tests[0].transport_readonly_server, server2)
553
        self.assertEqual(tests[1].intertree_class, formats[1][0])
554
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
555
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
556
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
557
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
558
        self.assertEqual(tests[1].transport_server, server1)
559
        self.assertEqual(tests[1].transport_readonly_server, server2)
560
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
561
562
class TestTestCaseInTempDir(TestCaseInTempDir):
563
564
    def test_home_is_not_working(self):
565
        self.assertNotEqual(self.test_dir, self.test_home_dir)
566
        cwd = osutils.getcwd()
1987.1.4 by John Arbash Meinel
fix the home_is_not_working test
567
        self.assertEqual(self.test_dir, cwd)
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
568
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
569
570
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
571
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
572
573
    def test_home_is_non_existant_dir_under_root(self):
574
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
575
576
        This is because TestCaseWithMemoryTransport is for tests that do not
577
        need any disk resources: they should be hooked into bzrlib in such a 
578
        way that no global settings are being changed by the test (only a 
579
        few tests should need to do that), and having a missing dir as home is
580
        an effective way to ensure that this is the case.
581
        """
582
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
583
            self.test_home_dir)
584
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
585
        
586
    def test_cwd_is_TEST_ROOT(self):
587
        self.assertEqual(self.test_dir, self.TEST_ROOT)
588
        cwd = osutils.getcwd()
589
        self.assertEqual(self.test_dir, cwd)
590
591
    def test_make_branch_and_memory_tree(self):
592
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
593
594
        This is hard to comprehensively robustly test, so we settle for making
595
        a branch and checking no directory was created at its relpath.
596
        """
597
        tree = self.make_branch_and_memory_tree('dir')
2227.2.2 by v.ladeuil+lp at free
Cleanup.
598
        # Guard against regression into MemoryTransport leaking
599
        # files to disk instead of keeping them in memory.
600
        self.failIf(osutils.lexists('dir'))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
601
        self.assertIsInstance(tree, memorytree.MemoryTree)
602
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
603
    def test_make_branch_and_memory_tree_with_format(self):
604
        """make_branch_and_memory_tree should accept a format option."""
605
        format = bzrdir.BzrDirMetaFormat1()
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
606
        format.repository_format = weaverepo.RepositoryFormat7()
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
607
        tree = self.make_branch_and_memory_tree('dir', format=format)
2227.2.2 by v.ladeuil+lp at free
Cleanup.
608
        # Guard against regression into MemoryTransport leaking
609
        # files to disk instead of keeping them in memory.
610
        self.failIf(osutils.lexists('dir'))
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
611
        self.assertIsInstance(tree, memorytree.MemoryTree)
612
        self.assertEqual(format.repository_format.__class__,
613
            tree.branch.repository._format.__class__)
614
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
615
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
616
class TestTestCaseWithTransport(TestCaseWithTransport):
617
    """Tests for the convenience functions TestCaseWithTransport introduces."""
618
619
    def test_get_readonly_url_none(self):
620
        from bzrlib.transport import get_transport
621
        from bzrlib.transport.memory import MemoryServer
622
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
623
        self.vfs_transport_factory = MemoryServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
624
        self.transport_readonly_server = None
625
        # calling get_readonly_transport() constructs a decorator on the url
626
        # for the server
627
        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.
628
        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.
629
        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.
630
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
631
        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.
632
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
633
        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.
634
635
    def test_get_readonly_url_http(self):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
636
        from bzrlib.tests.HttpServer import HttpServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
637
        from bzrlib.transport import get_transport
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
638
        from bzrlib.transport.local import LocalURLServer
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
639
        from bzrlib.transport.http import HttpTransportBase
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
640
        self.transport_server = LocalURLServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
641
        self.transport_readonly_server = HttpServer
642
        # calling get_readonly_transport() gives us a HTTP server instance.
643
        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.
644
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
645
        # 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.
646
        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.
647
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
648
        self.failUnless(isinstance(t, HttpTransportBase))
649
        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.
650
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
651
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
652
    def test_is_directory(self):
653
        """Test assertIsDirectory assertion"""
654
        t = self.get_transport()
655
        self.build_tree(['a_dir/', 'a_file'], transport=t)
656
        self.assertIsDirectory('a_dir', t)
657
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
658
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
659
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
660
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
661
class TestTestCaseTransports(TestCaseWithTransport):
662
663
    def setUp(self):
664
        super(TestTestCaseTransports, self).setUp()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
665
        self.vfs_transport_factory = MemoryServer
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
666
667
    def test_make_bzrdir_preserves_transport(self):
668
        t = self.get_transport()
669
        result_bzrdir = self.make_bzrdir('subdir')
670
        self.assertIsInstance(result_bzrdir.transport, 
671
                              MemoryTransport)
672
        # should not be on disk, should only be in memory
673
        self.failIfExists('subdir')
674
675
1534.4.31 by Robert Collins
cleanedup test_outside_wt
676
class TestChrootedTest(ChrootedTestCase):
677
678
    def test_root_is_root(self):
679
        from bzrlib.transport import get_transport
680
        t = get_transport(self.get_readonly_url())
681
        url = t.base
682
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
683
684
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
685
class MockProgress(_BaseProgressBar):
686
    """Progress-bar standin that records calls.
687
688
    Useful for testing pb using code.
689
    """
690
691
    def __init__(self):
692
        _BaseProgressBar.__init__(self)
693
        self.calls = []
694
695
    def tick(self):
696
        self.calls.append(('tick',))
697
698
    def update(self, msg=None, current=None, total=None):
699
        self.calls.append(('update', msg, current, total))
700
701
    def clear(self):
702
        self.calls.append(('clear',))
703
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
704
    def note(self, msg, *args):
705
        self.calls.append(('note', msg, args))
706
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
707
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
708
class TestTestResult(TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
709
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
710
    def test_elapsed_time_with_benchmarking(self):
2095.4.1 by Martin Pool
Better progress bars during tests
711
        result = bzrlib.tests.TextTestResult(self._log_file,
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
712
                                        descriptions=0,
713
                                        verbosity=1,
714
                                        )
715
        result._recordTestStartTime()
716
        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)
717
        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).
718
        timed_string = result._testTimeString()
719
        # without explicit benchmarking, we should get a simple time.
2492.1.2 by John Arbash Meinel
Tweak the regex a bit more
720
        self.assertContainsRe(timed_string, "^ +[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).
721
        # 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)
722
        self.time(time.sleep, 0.001)
723
        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).
724
        timed_string = result._testTimeString()
2485.2.1 by Marien Zwart
Make test_elapsed_time_with_benchmarking pass on a slow cpu.
725
        self.assertContainsRe(
2492.1.2 by John Arbash Meinel
Tweak the regex a bit more
726
            timed_string, "^ +[0-9]+ms/ +[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)
727
        # 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).
728
        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)
729
        result.extractBenchmarkTime(
730
            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).
731
        timed_string = result._testTimeString()
2492.1.2 by John Arbash Meinel
Tweak the regex a bit more
732
        self.assertContainsRe(timed_string, "^ +[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)
733
        # cheat. Yes, wash thy mouth out with soap.
734
        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).
735
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
736
    def test_assigned_benchmark_file_stores_date(self):
737
        output = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
738
        result = bzrlib.tests.TextTestResult(self._log_file,
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
739
                                        descriptions=0,
740
                                        verbosity=1,
741
                                        bench_history=output
742
                                        )
743
        output_string = output.getvalue()
2095.4.1 by Martin Pool
Better progress bars during tests
744
        
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
745
        # if you are wondering about the regexp please read the comment in
746
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
1951.1.2 by Andrew Bennetts
Relax test_assigned_benchmark_file_stores_date's regexp the same way we relaxed test_bench_history's.
747
        # XXX: what comment?  -- Andrew Bennetts
748
        self.assertContainsRe(output_string, "--date [0-9.]+")
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
749
750
    def test_benchhistory_records_test_times(self):
751
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
752
        result = bzrlib.tests.TextTestResult(
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
753
            self._log_file,
754
            descriptions=0,
755
            verbosity=1,
756
            bench_history=result_stream
757
            )
758
759
        # we want profile a call and check that its test duration is recorded
760
        # make a new test instance that when run will generate a benchmark
761
        example_test_case = TestTestResult("_time_hello_world_encoding")
762
        # execute the test, which should succeed and record times
763
        example_test_case.run(result)
764
        lines = result_stream.getvalue().splitlines()
765
        self.assertEqual(2, len(lines))
766
        self.assertContainsRe(lines[1],
767
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
768
            "._time_hello_world_encoding")
769
 
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
770
    def _time_hello_world_encoding(self):
771
        """Profile two sleep calls
772
        
773
        This is used to exercise the test framework.
774
        """
775
        self.time(unicode, 'hello', errors='replace')
776
        self.time(unicode, 'world', errors='replace')
777
778
    def test_lsprofiling(self):
779
        """Verbose test result prints lsprof statistics from test cases."""
1551.15.28 by Aaron Bentley
Improve Feature usage style w/ lsprof
780
        self.requireFeature(test_lsprof.LSProfFeature)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
781
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
782
        result = bzrlib.tests.VerboseTestResult(
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
783
            unittest._WritelnDecorator(result_stream),
784
            descriptions=0,
785
            verbosity=2,
786
            )
787
        # we want profile a call of some sort and check it is output by
788
        # addSuccess. We dont care about addError or addFailure as they
789
        # are not that interesting for performance tuning.
790
        # make a new test instance that when run will generate a profile
791
        example_test_case = TestTestResult("_time_hello_world_encoding")
792
        example_test_case._gather_lsprof_in_benchmarks = True
793
        # execute the test, which should succeed and record profiles
794
        example_test_case.run(result)
795
        # lsprofile_something()
796
        # if this worked we want 
797
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
798
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
799
        # (the lsprof header)
800
        # ... an arbitrary number of lines
801
        # and the function call which is time.sleep.
802
        #           1        0            ???         ???       ???(sleep) 
803
        # and then repeated but with 'world', rather than 'hello'.
804
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
805
        output = result_stream.getvalue()
806
        self.assertContainsRe(output,
807
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
808
        self.assertContainsRe(output,
809
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
810
        self.assertContainsRe(output,
811
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
812
        self.assertContainsRe(output,
813
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
814
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
815
    def test_known_failure(self):
816
        """A KnownFailure being raised should trigger several result actions."""
817
        class InstrumentedTestResult(ExtendedTestResult):
818
819
            def report_test_start(self, test): pass
820
            def report_known_failure(self, test, err):
821
                self._call = test, err
822
        result = InstrumentedTestResult(None, None, None, None)
823
        def test_function():
824
            raise KnownFailure('failed!')
825
        test = unittest.FunctionTestCase(test_function)
826
        test.run(result)
827
        # it should invoke 'report_known_failure'.
828
        self.assertEqual(2, len(result._call))
829
        self.assertEqual(test, result._call[0])
830
        self.assertEqual(KnownFailure, result._call[1][0])
831
        self.assertIsInstance(result._call[1][1], KnownFailure)
832
        # we dont introspec the traceback, if the rest is ok, it would be
833
        # exceptional for it not to be.
834
        # it should update the known_failure_count on the object.
835
        self.assertEqual(1, result.known_failure_count)
836
        # the result should be successful.
837
        self.assertTrue(result.wasSuccessful())
838
839
    def test_verbose_report_known_failure(self):
840
        # verbose test output formatting
841
        result_stream = StringIO()
842
        result = bzrlib.tests.VerboseTestResult(
843
            unittest._WritelnDecorator(result_stream),
844
            descriptions=0,
845
            verbosity=2,
846
            )
847
        test = self.get_passing_test()
848
        result.startTest(test)
849
        result.extractBenchmarkTime(test)
850
        prefix = len(result_stream.getvalue())
851
        # the err parameter has the shape:
852
        # (class, exception object, traceback)
853
        # KnownFailures dont get their tracebacks shown though, so we
854
        # can skip that.
855
        err = (KnownFailure, KnownFailure('foo'), None)
856
        result.report_known_failure(test, err)
857
        output = result_stream.getvalue()[prefix:]
858
        lines = output.splitlines()
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
859
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
860
        self.assertEqual(lines[1], '    foo')
861
        self.assertEqual(2, len(lines))
862
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
863
    def test_text_report_known_failure(self):
864
        # text test output formatting
865
        pb = MockProgress()
866
        result = bzrlib.tests.TextTestResult(
867
            None,
868
            descriptions=0,
869
            verbosity=1,
870
            pb=pb,
871
            )
872
        test = self.get_passing_test()
873
        # this seeds the state to handle reporting the test.
874
        result.startTest(test)
875
        result.extractBenchmarkTime(test)
876
        # the err parameter has the shape:
877
        # (class, exception object, traceback)
878
        # KnownFailures dont get their tracebacks shown though, so we
879
        # can skip that.
880
        err = (KnownFailure, KnownFailure('foo'), None)
881
        result.report_known_failure(test, err)
882
        self.assertEqual(
883
            [
884
            ('update', '[1 in 0s] passing_test', None, None),
885
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
886
            ],
887
            pb.calls)
888
        # known_failures should be printed in the summary, so if we run a test
889
        # after there are some known failures, the update prefix should match
890
        # this.
891
        result.known_failure_count = 3
892
        test.run(result)
893
        self.assertEqual(
894
            [
895
            ('update', '[2 in 0s, 3 known failures] passing_test', None, None),
896
            ],
897
            pb.calls[2:])
898
899
    def get_passing_test(self):
900
        """Return a test object that can't be run usefully."""
901
        def passing_test():
902
            pass
903
        return unittest.FunctionTestCase(passing_test)
904
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
905
    def test_add_not_supported(self):
906
        """Test the behaviour of invoking addNotSupported."""
907
        class InstrumentedTestResult(ExtendedTestResult):
908
            def report_test_start(self, test): pass
909
            def report_unsupported(self, test, feature):
910
                self._call = test, feature
911
        result = InstrumentedTestResult(None, None, None, None)
912
        test = SampleTestCase('_test_pass')
913
        feature = Feature()
914
        result.startTest(test)
915
        result.addNotSupported(test, feature)
916
        # it should invoke 'report_unsupported'.
917
        self.assertEqual(2, len(result._call))
918
        self.assertEqual(test, result._call[0])
919
        self.assertEqual(feature, result._call[1])
920
        # the result should be successful.
921
        self.assertTrue(result.wasSuccessful())
922
        # it should record the test against a count of tests not run due to
923
        # this feature.
924
        self.assertEqual(1, result.unsupported['Feature'])
925
        # and invoking it again should increment that counter
926
        result.addNotSupported(test, feature)
927
        self.assertEqual(2, result.unsupported['Feature'])
928
929
    def test_verbose_report_unsupported(self):
930
        # verbose test output formatting
931
        result_stream = StringIO()
932
        result = bzrlib.tests.VerboseTestResult(
933
            unittest._WritelnDecorator(result_stream),
934
            descriptions=0,
935
            verbosity=2,
936
            )
937
        test = self.get_passing_test()
938
        feature = Feature()
939
        result.startTest(test)
940
        result.extractBenchmarkTime(test)
941
        prefix = len(result_stream.getvalue())
942
        result.report_unsupported(test, feature)
943
        output = result_stream.getvalue()[prefix:]
944
        lines = output.splitlines()
945
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
946
    
947
    def test_text_report_unsupported(self):
948
        # text test output formatting
949
        pb = MockProgress()
950
        result = bzrlib.tests.TextTestResult(
951
            None,
952
            descriptions=0,
953
            verbosity=1,
954
            pb=pb,
955
            )
956
        test = self.get_passing_test()
957
        feature = Feature()
958
        # this seeds the state to handle reporting the test.
959
        result.startTest(test)
960
        result.extractBenchmarkTime(test)
961
        result.report_unsupported(test, feature)
962
        # no output on unsupported features
963
        self.assertEqual(
964
            [('update', '[1 in 0s] passing_test', None, None)
965
            ],
966
            pb.calls)
967
        # the number of missing features should be printed in the progress
968
        # summary, so check for that.
969
        result.unsupported = {'foo':0, 'bar':0}
970
        test.run(result)
971
        self.assertEqual(
972
            [
973
            ('update', '[2 in 0s, 2 missing features] passing_test', None, None),
974
            ],
975
            pb.calls[1:])
976
    
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
977
    def test_unavailable_exception(self):
978
        """An UnavailableFeature being raised should invoke addNotSupported."""
979
        class InstrumentedTestResult(ExtendedTestResult):
980
981
            def report_test_start(self, test): pass
982
            def addNotSupported(self, test, feature):
983
                self._call = test, feature
984
        result = InstrumentedTestResult(None, None, None, None)
985
        feature = Feature()
986
        def test_function():
987
            raise UnavailableFeature(feature)
988
        test = unittest.FunctionTestCase(test_function)
989
        test.run(result)
990
        # it should invoke 'addNotSupported'.
991
        self.assertEqual(2, len(result._call))
992
        self.assertEqual(test, result._call[0])
993
        self.assertEqual(feature, result._call[1])
994
        # and not count as an error
995
        self.assertEqual(0, result.error_count)
996
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
997
    def test_strict_with_unsupported_feature(self):
998
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
999
                                                verbosity=1)
1000
        test = self.get_passing_test()
1001
        feature = "Unsupported Feature"
1002
        result.addNotSupported(test, feature)
1003
        self.assertFalse(result.wasStrictlySuccessful())
1004
1005
    def test_strict_with_known_failure(self):
1006
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1007
                                                verbosity=1)
1008
        test = self.get_passing_test()
1009
        err = (KnownFailure, KnownFailure('foo'), None)
1010
        result.addKnownFailure(test, err)
1011
        self.assertFalse(result.wasStrictlySuccessful())
1012
1013
    def test_strict_with_success(self):
1014
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1015
                                                verbosity=1)
1016
        test = self.get_passing_test()
1017
        result.addSuccess(test)
1018
        self.assertTrue(result.wasStrictlySuccessful())
1019
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
1020
1021
class TestRunner(TestCase):
1022
1023
    def dummy_test(self):
1024
        pass
1025
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1026
    def run_test_runner(self, testrunner, test):
1027
        """Run suite in testrunner, saving global state and restoring it.
1028
1029
        This current saves and restores:
1030
        TestCaseInTempDir.TEST_ROOT
1031
        
1032
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
1033
        without using this convenience method, because of our use of global state.
1034
        """
1035
        old_root = TestCaseInTempDir.TEST_ROOT
1036
        try:
1037
            TestCaseInTempDir.TEST_ROOT = None
1038
            return testrunner.run(test)
1039
        finally:
1040
            TestCaseInTempDir.TEST_ROOT = old_root
1041
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1042
    def test_known_failure_failed_run(self):
1043
        # run a test that generates a known failure which should be printed in
1044
        # the final output when real failures occur.
1045
        def known_failure_test():
1046
            raise KnownFailure('failed')
1047
        test = unittest.TestSuite()
1048
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1049
        def failing_test():
1050
            raise AssertionError('foo')
1051
        test.addTest(unittest.FunctionTestCase(failing_test))
1052
        stream = StringIO()
1053
        runner = TextTestRunner(stream=stream)
1054
        result = self.run_test_runner(runner, test)
1055
        lines = stream.getvalue().splitlines()
1056
        self.assertEqual([
1057
            '',
1058
            '======================================================================',
1059
            'FAIL: unittest.FunctionTestCase (failing_test)',
1060
            '----------------------------------------------------------------------',
1061
            'Traceback (most recent call last):',
1062
            '    raise AssertionError(\'foo\')',
1063
            'AssertionError: foo',
1064
            '',
1065
            '----------------------------------------------------------------------',
1066
            '',
1067
            'FAILED (failures=1, known_failure_count=1)'],
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1068
            lines[0:5] + lines[6:10] + lines[11:])
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1069
1070
    def test_known_failure_ok_run(self):
1071
        # run a test that generates a known failure which should be printed in the final output.
1072
        def known_failure_test():
1073
            raise KnownFailure('failed')
1074
        test = unittest.FunctionTestCase(known_failure_test)
1075
        stream = StringIO()
1076
        runner = TextTestRunner(stream=stream)
1077
        result = self.run_test_runner(runner, test)
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
1078
        self.assertContainsRe(stream.getvalue(),
1079
            '\n'
1080
            '-*\n'
1081
            'Ran 1 test in .*\n'
1082
            '\n'
1083
            'OK \\(known_failures=1\\)\n')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1084
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1085
    def test_skipped_test(self):
1086
        # run a test that is skipped, and check the suite as a whole still
1087
        # succeeds.
1088
        # skipping_test must be hidden in here so it's not run as a real test
1089
        def skipping_test():
1090
            raise TestSkipped('test intentionally skipped')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1091
2485.6.5 by Martin Pool
Remove keep_output option
1092
        runner = TextTestRunner(stream=self._log_file)
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1093
        test = unittest.FunctionTestCase(skipping_test)
1094
        result = self.run_test_runner(runner, test)
1095
        self.assertTrue(result.wasSuccessful())
1096
1097
    def test_skipped_from_setup(self):
1098
        class SkippedSetupTest(TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1099
1100
            def setUp(self):
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1101
                self.counter = 1
1102
                self.addCleanup(self.cleanup)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1103
                raise TestSkipped('skipped setup')
1104
1105
            def test_skip(self):
1106
                self.fail('test reached')
1107
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1108
            def cleanup(self):
1109
                self.counter -= 1
1110
2485.6.5 by Martin Pool
Remove keep_output option
1111
        runner = TextTestRunner(stream=self._log_file)
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1112
        test = SkippedSetupTest('test_skip')
1113
        result = self.run_test_runner(runner, test)
1114
        self.assertTrue(result.wasSuccessful())
1115
        # Check if cleanup was called the right number of times.
1116
        self.assertEqual(0, test.counter)
1117
1118
    def test_skipped_from_test(self):
1119
        class SkippedTest(TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1120
1121
            def setUp(self):
1122
                self.counter = 1
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1123
                self.addCleanup(self.cleanup)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1124
1125
            def test_skip(self):
1126
                raise TestSkipped('skipped test')
1127
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1128
            def cleanup(self):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1129
                self.counter -= 1
1130
2485.6.5 by Martin Pool
Remove keep_output option
1131
        runner = TextTestRunner(stream=self._log_file)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1132
        test = SkippedTest('test_skip')
1133
        result = self.run_test_runner(runner, test)
1134
        self.assertTrue(result.wasSuccessful())
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1135
        # Check if cleanup was called the right number of times.
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1136
        self.assertEqual(0, test.counter)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1137
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1138
    def test_not_applicable(self):
1139
        # run a test that is skipped because it's not applicable
1140
        def not_applicable_test():
1141
            from bzrlib.tests import TestNotApplicable
1142
            raise TestNotApplicable('this test never runs')
1143
        out = StringIO()
1144
        runner = TextTestRunner(stream=out, verbosity=2)
1145
        test = unittest.FunctionTestCase(not_applicable_test)
1146
        result = self.run_test_runner(runner, test)
1147
        self._log_file.write(out.getvalue())
1148
        self.assertTrue(result.wasSuccessful())
1149
        self.assertTrue(result.wasStrictlySuccessful())
1150
        self.assertContainsRe(out.getvalue(),
1151
                r'(?m)not_applicable_test   * N/A')
1152
        self.assertContainsRe(out.getvalue(),
1153
                r'(?m)^    this test never runs')
1154
1155
    def test_not_applicable_demo(self):
1156
        # just so you can see it in the test output
1157
        raise TestNotApplicable('this test is just a demonstation')
1158
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1159
    def test_unsupported_features_listed(self):
1160
        """When unsupported features are encountered they are detailed."""
1161
        class Feature1(Feature):
1162
            def _probe(self): return False
1163
        class Feature2(Feature):
1164
            def _probe(self): return False
1165
        # create sample tests
1166
        test1 = SampleTestCase('_test_pass')
1167
        test1._test_needs_features = [Feature1()]
1168
        test2 = SampleTestCase('_test_pass')
1169
        test2._test_needs_features = [Feature2()]
1170
        test = unittest.TestSuite()
1171
        test.addTest(test1)
1172
        test.addTest(test2)
1173
        stream = StringIO()
1174
        runner = TextTestRunner(stream=stream)
1175
        result = self.run_test_runner(runner, test)
1176
        lines = stream.getvalue().splitlines()
1177
        self.assertEqual([
1178
            'OK',
1179
            "Missing feature 'Feature1' skipped 1 tests.",
1180
            "Missing feature 'Feature2' skipped 1 tests.",
1181
            ],
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1182
            lines[-3:])
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1183
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1184
    def test_bench_history(self):
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
1185
        # tests that the running the benchmark produces a history file
1186
        # containing a timestamp and the revision id of the bzrlib source which
1187
        # was tested.
1188
        workingtree = _get_bzr_source_tree()
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1189
        test = TestRunner('dummy_test')
1190
        output = StringIO()
1191
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
1192
        result = self.run_test_runner(runner, test)
1193
        output_string = output.getvalue()
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
1194
        self.assertContainsRe(output_string, "--date [0-9.]+")
1195
        if workingtree is not None:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1196
            revision_id = workingtree.get_parent_ids()[0]
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
1197
            self.assertEndsWith(output_string.rstrip(), revision_id)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1198
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1199
    def test_success_log_deleted(self):
1200
        """Successful tests have their log deleted"""
1201
1202
        class LogTester(TestCase):
1203
1204
            def test_success(self):
1205
                self.log('this will be removed\n')
1206
1207
        sio = cStringIO.StringIO()
1208
        runner = TextTestRunner(stream=sio)
1209
        test = LogTester('test_success')
1210
        result = self.run_test_runner(runner, test)
1211
1212
        log = test._get_log()
1213
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1214
        self.assertEqual('', test._log_contents)
1215
        self.assertIs(None, test._log_file_name)
1216
1217
    def test_fail_log_kept(self):
1218
        """Failed tests have their log kept"""
1219
1220
        class LogTester(TestCase):
1221
1222
            def test_fail(self):
1223
                self.log('this will be kept\n')
1224
                self.fail('this test fails')
1225
1226
        sio = cStringIO.StringIO()
1227
        runner = TextTestRunner(stream=sio)
1228
        test = LogTester('test_fail')
1229
        result = self.run_test_runner(runner, test)
1230
1231
        text = sio.getvalue()
1232
        self.assertContainsRe(text, 'this will be kept')
1233
        self.assertContainsRe(text, 'this test fails')
1234
1235
        log = test._get_log()
1236
        self.assertContainsRe(log, 'this will be kept')
1237
        self.assertEqual(log, test._log_contents)
1238
1239
    def test_error_log_kept(self):
1240
        """Tests with errors have their log kept"""
1241
1242
        class LogTester(TestCase):
1243
1244
            def test_error(self):
1245
                self.log('this will be kept\n')
1246
                raise ValueError('random exception raised')
1247
1248
        sio = cStringIO.StringIO()
1249
        runner = TextTestRunner(stream=sio)
1250
        test = LogTester('test_error')
1251
        result = self.run_test_runner(runner, test)
1252
1253
        text = sio.getvalue()
1254
        self.assertContainsRe(text, 'this will be kept')
1255
        self.assertContainsRe(text, 'random exception raised')
1256
1257
        log = test._get_log()
1258
        self.assertContainsRe(log, 'this will be kept')
1259
        self.assertEqual(log, test._log_contents)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1260
2036.1.2 by John Arbash Meinel
whitespace fix
1261
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1262
class SampleTestCase(TestCase):
1263
1264
    def _test_pass(self):
1265
        pass
1266
1267
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1268
class TestTestCase(TestCase):
1269
    """Tests that test the core bzrlib TestCase."""
1270
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1271
    def test_debug_flags_sanitised(self):
1272
        """The bzrlib debug flags should be sanitised by setUp."""
1273
        # we could set something and run a test that will check
1274
        # it gets santised, but this is probably sufficient for now:
1275
        # if someone runs the test with -Dsomething it will error.
1276
        self.assertEqual(set(), bzrlib.debug.debug_flags)
1277
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1278
    def inner_test(self):
1279
        # the inner child test
1280
        note("inner_test")
1281
1282
    def outer_child(self):
1283
        # the outer child test
1284
        note("outer_start")
1285
        self.inner_test = TestTestCase("inner_child")
2095.4.1 by Martin Pool
Better progress bars during tests
1286
        result = bzrlib.tests.TextTestResult(self._log_file,
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1287
                                        descriptions=0,
1288
                                        verbosity=1)
1289
        self.inner_test.run(result)
1290
        note("outer finish")
1291
1292
    def test_trace_nesting(self):
1293
        # this tests that each test case nests its trace facility correctly.
1294
        # we do this by running a test case manually. That test case (A)
1295
        # should setup a new log, log content to it, setup a child case (B),
1296
        # which should log independently, then case (A) should log a trailer
1297
        # and return.
1298
        # we do two nested children so that we can verify the state of the 
1299
        # logs after the outer child finishes is correct, which a bad clean
1300
        # up routine in tearDown might trigger a fault in our test with only
1301
        # one child, we should instead see the bad result inside our test with
1302
        # the two children.
1303
        # the outer child test
1304
        original_trace = bzrlib.trace._trace_file
1305
        outer_test = TestTestCase("outer_child")
2095.4.1 by Martin Pool
Better progress bars during tests
1306
        result = bzrlib.tests.TextTestResult(self._log_file,
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1307
                                        descriptions=0,
1308
                                        verbosity=1)
1309
        outer_test.run(result)
1310
        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)
1311
1312
    def method_that_times_a_bit_twice(self):
1313
        # 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.
1314
        self.time(time.sleep, 0.007)
1315
        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)
1316
1317
    def test_time_creates_benchmark_in_result(self):
1318
        """Test that the TestCase.time() method accumulates a benchmark time."""
1319
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1320
        output_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
1321
        result = bzrlib.tests.VerboseTestResult(
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
1322
            unittest._WritelnDecorator(output_stream),
1323
            descriptions=0,
2095.4.1 by Martin Pool
Better progress bars during tests
1324
            verbosity=2,
1325
            num_tests=sample_test.countTestCases())
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
1326
        sample_test.run(result)
1327
        self.assertContainsRe(
1328
            output_stream.getvalue(),
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1329
            r"\d+ms/ +\d+ms\n$")
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1330
1331
    def test_hooks_sanitised(self):
1332
        """The bzrlib hooks should be sanitised by setUp."""
2245.1.2 by Robert Collins
Remove the static DefaultHooks method from Branch, replacing it with a derived dict BranchHooks object, which is easier to use and provides a place to put the policy-checking add method discussed on list.
1333
        self.assertEqual(bzrlib.branch.BranchHooks(),
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1334
            bzrlib.branch.Branch.hooks)
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
1335
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1336
            bzrlib.smart.server.SmartTCPServer.hooks)
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1337
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1338
    def test__gather_lsprof_in_benchmarks(self):
1339
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1340
        
1341
        Each self.time() call is individually and separately profiled.
1342
        """
1551.15.28 by Aaron Bentley
Improve Feature usage style w/ lsprof
1343
        self.requireFeature(test_lsprof.LSProfFeature)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1344
        # overrides the class member with an instance member so no cleanup 
1345
        # needed.
1346
        self._gather_lsprof_in_benchmarks = True
1347
        self.time(time.sleep, 0.000)
1348
        self.time(time.sleep, 0.003)
1349
        self.assertEqual(2, len(self._benchcalls))
1350
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1351
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1352
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1353
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1354
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1355
    def test_knownFailure(self):
1356
        """Self.knownFailure() should raise a KnownFailure exception."""
1357
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1358
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1359
    def test_requireFeature_available(self):
1360
        """self.requireFeature(available) is a no-op."""
1361
        class Available(Feature):
1362
            def _probe(self):return True
1363
        feature = Available()
1364
        self.requireFeature(feature)
1365
1366
    def test_requireFeature_unavailable(self):
1367
        """self.requireFeature(unavailable) raises UnavailableFeature."""
1368
        class Unavailable(Feature):
1369
            def _probe(self):return False
1370
        feature = Unavailable()
1371
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1372
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1373
    def test_run_no_parameters(self):
1374
        test = SampleTestCase('_test_pass')
1375
        test.run()
1376
    
1377
    def test_run_enabled_unittest_result(self):
1378
        """Test we revert to regular behaviour when the test is enabled."""
1379
        test = SampleTestCase('_test_pass')
1380
        class EnabledFeature(object):
1381
            def available(self):
1382
                return True
1383
        test._test_needs_features = [EnabledFeature()]
1384
        result = unittest.TestResult()
1385
        test.run(result)
1386
        self.assertEqual(1, result.testsRun)
1387
        self.assertEqual([], result.errors)
1388
        self.assertEqual([], result.failures)
1389
1390
    def test_run_disabled_unittest_result(self):
1391
        """Test our compatability for disabled tests with unittest results."""
1392
        test = SampleTestCase('_test_pass')
1393
        class DisabledFeature(object):
1394
            def available(self):
1395
                return False
1396
        test._test_needs_features = [DisabledFeature()]
1397
        result = unittest.TestResult()
1398
        test.run(result)
1399
        self.assertEqual(1, result.testsRun)
1400
        self.assertEqual([], result.errors)
1401
        self.assertEqual([], result.failures)
1402
1403
    def test_run_disabled_supporting_result(self):
1404
        """Test disabled tests behaviour with support aware results."""
1405
        test = SampleTestCase('_test_pass')
1406
        class DisabledFeature(object):
1407
            def available(self):
1408
                return False
1409
        the_feature = DisabledFeature()
1410
        test._test_needs_features = [the_feature]
1411
        class InstrumentedTestResult(unittest.TestResult):
1412
            def __init__(self):
1413
                unittest.TestResult.__init__(self)
1414
                self.calls = []
1415
            def startTest(self, test):
1416
                self.calls.append(('startTest', test))
1417
            def stopTest(self, test):
1418
                self.calls.append(('stopTest', test))
1419
            def addNotSupported(self, test, feature):
1420
                self.calls.append(('addNotSupported', test, feature))
1421
        result = InstrumentedTestResult()
1422
        test.run(result)
1423
        self.assertEqual([
1424
            ('startTest', test),
1425
            ('addNotSupported', test, the_feature),
1426
            ('stopTest', test),
1427
            ],
1428
            result.calls)
1429
1534.11.4 by Robert Collins
Merge from mainline.
1430
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1431
@symbol_versioning.deprecated_function(zero_eleven)
1432
def sample_deprecated_function():
1433
    """A deprecated function to test applyDeprecated with."""
1434
    return 2
1435
1436
1437
def sample_undeprecated_function(a_param):
1438
    """A undeprecated function to test applyDeprecated with."""
1439
1440
1441
class ApplyDeprecatedHelper(object):
1442
    """A helper class for ApplyDeprecated tests."""
1443
1444
    @symbol_versioning.deprecated_method(zero_eleven)
1445
    def sample_deprecated_method(self, param_one):
1446
        """A deprecated method for testing with."""
1447
        return param_one
1448
1449
    def sample_normal_method(self):
1450
        """A undeprecated method."""
1451
1452
    @symbol_versioning.deprecated_method(zero_ten)
1453
    def sample_nested_deprecation(self):
1454
        return sample_deprecated_function()
1455
1456
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1457
class TestExtraAssertions(TestCase):
1458
    """Tests for new test assertions in bzrlib test suite"""
1459
1460
    def test_assert_isinstance(self):
1461
        self.assertIsInstance(2, int)
1462
        self.assertIsInstance(u'', basestring)
1463
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1464
        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
1465
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
1466
    def test_assertEndsWith(self):
1467
        self.assertEndsWith('foo', 'oo')
1468
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1469
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1470
    def test_applyDeprecated_not_deprecated(self):
1471
        sample_object = ApplyDeprecatedHelper()
1472
        # calling an undeprecated callable raises an assertion
1473
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1474
            sample_object.sample_normal_method)
1475
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1476
            sample_undeprecated_function, "a param value")
1477
        # calling a deprecated callable (function or method) with the wrong
1478
        # expected deprecation fails.
1479
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1480
            sample_object.sample_deprecated_method, "a param value")
1481
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1482
            sample_deprecated_function)
1483
        # calling a deprecated callable (function or method) with the right
1484
        # expected deprecation returns the functions result.
1485
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1486
            sample_object.sample_deprecated_method, "a param value"))
1487
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
1488
            sample_deprecated_function))
1489
        # calling a nested deprecation with the wrong deprecation version
1490
        # fails even if a deeper nested function was deprecated with the 
1491
        # supplied version.
1492
        self.assertRaises(AssertionError, self.applyDeprecated,
1493
            zero_eleven, sample_object.sample_nested_deprecation)
1494
        # calling a nested deprecation with the right deprecation value
1495
        # returns the calls result.
1496
        self.assertEqual(2, self.applyDeprecated(zero_ten,
1497
            sample_object.sample_nested_deprecation))
1498
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1499
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1500
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1501
            if be_deprecated is True:
1502
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
1503
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1504
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1505
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1506
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1507
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1508
        self.assertEqual('result', result)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1509
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1510
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1511
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1512
1513
class TestConvenienceMakers(TestCaseWithTransport):
1514
    """Test for the make_* convenience functions."""
1515
1516
    def test_make_branch_and_tree_with_format(self):
1517
        # we should be able to supply a format to make_branch_and_tree
1518
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1519
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1520
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1521
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1522
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1523
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1524
1986.2.1 by Robert Collins
Bugfix - the name of the test for make_branch_and_memory_tree was wrong.
1525
    def test_make_branch_and_memory_tree(self):
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
1526
        # we should be able to get a new branch and a mutable tree from
1527
        # TestCaseWithTransport
1528
        tree = self.make_branch_and_memory_tree('a')
1529
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1530
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1531
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
1532
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1533
1534
    def test_make_tree_for_sftp_branch(self):
1535
        """Transports backed by local directories create local trees."""
1536
1537
        tree = self.make_branch_and_tree('t1')
1538
        base = tree.bzrdir.root_transport.base
1539
        self.failIf(base.startswith('sftp'),
1540
                'base %r is on sftp but should be local' % base)
1541
        self.assertEquals(tree.bzrdir.root_transport,
1542
                tree.branch.bzrdir.root_transport)
1543
        self.assertEquals(tree.bzrdir.root_transport,
1544
                tree.branch.repository.bzrdir.root_transport)
1545
1546
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1547
class TestSelftest(TestCase):
1548
    """Tests of bzrlib.tests.selftest."""
1549
1550
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1551
        factory_called = []
1552
        def factory():
1553
            factory_called.append(True)
1554
            return TestSuite()
1555
        out = StringIO()
1556
        err = StringIO()
1557
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
1558
            test_suite_factory=factory)
1559
        self.assertEqual([True], factory_called)
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
1560
1561
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1562
class TestKnownFailure(TestCase):
1563
1564
    def test_known_failure(self):
1565
        """Check that KnownFailure is defined appropriately."""
1566
        # a KnownFailure is an assertion error for compatability with unaware
1567
        # runners.
1568
        self.assertIsInstance(KnownFailure(""), AssertionError)
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1569
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1570
    def test_expect_failure(self):
1571
        try:
1572
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1573
        except KnownFailure, e:
1574
            self.assertEqual('Doomed to failure', e.args[0])
1575
        try:
1576
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1577
        except AssertionError, e:
1578
            self.assertEqual('Unexpected success.  Should have failed:'
1579
                             ' Doomed to failure', e.args[0])
1580
        else:
1581
            self.fail('Assertion not raised')
1582
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1583
1584
class TestFeature(TestCase):
1585
1586
    def test_caching(self):
1587
        """Feature._probe is called by the feature at most once."""
1588
        class InstrumentedFeature(Feature):
1589
            def __init__(self):
1590
                Feature.__init__(self)
1591
                self.calls = []
1592
            def _probe(self):
1593
                self.calls.append('_probe')
1594
                return False
1595
        feature = InstrumentedFeature()
1596
        feature.available()
1597
        self.assertEqual(['_probe'], feature.calls)
1598
        feature.available()
1599
        self.assertEqual(['_probe'], feature.calls)
1600
1601
    def test_named_str(self):
1602
        """Feature.__str__ should thunk to feature_name()."""
1603
        class NamedFeature(Feature):
1604
            def feature_name(self):
1605
                return 'symlinks'
1606
        feature = NamedFeature()
1607
        self.assertEqual('symlinks', str(feature))
1608
1609
    def test_default_str(self):
1610
        """Feature.__str__ should default to __class__.__name__."""
1611
        class NamedFeature(Feature):
1612
            pass
1613
        feature = NamedFeature()
1614
        self.assertEqual('NamedFeature', str(feature))
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1615
1616
1617
class TestUnavailableFeature(TestCase):
1618
1619
    def test_access_feature(self):
1620
        feature = Feature()
1621
        exception = UnavailableFeature(feature)
1622
        self.assertIs(feature, exception.args[0])
2394.2.5 by Ian Clatworthy
list-only working, include test not
1623
1624
1625
class TestSelftestFiltering(TestCase):
1626
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
1627
    def setUp(self):
1628
        self.suite = TestUtil.TestSuite()
1629
        self.loader = TestUtil.TestLoader()
1630
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1631
            'bzrlib.tests.test_selftest']))
1632
        self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
1633
2394.2.5 by Ian Clatworthy
list-only working, include test not
1634
    def test_filter_suite_by_re(self):
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
1635
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
1636
        filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
1637
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1638
            'TestSelftestFiltering.test_filter_suite_by_re'])
1639
            
1640
    def test_sort_suite_by_re(self):
1641
        sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
1642
        sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
1643
        self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1644
            'TestSelftestFiltering.test_filter_suite_by_re')
1645
        self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1646
2545.3.2 by James Westby
Add a test for check_inventory_shape.
1647
1648
class TestCheckInventoryShape(TestCaseWithTransport):
1649
1650
    def test_check_inventory_shape(self):
2561.1.2 by Aaron Bentley
Fix indenting in TestCheckInventoryShape
1651
        files = ['a', 'b/', 'b/c']
1652
        tree = self.make_branch_and_tree('.')
1653
        self.build_tree(files)
1654
        tree.add(files)
1655
        tree.lock_read()
1656
        try:
1657
            self.check_inventory_shape(tree.inventory, files)
1658
        finally:
1659
            tree.unlock()