/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
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
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
19
from cStringIO import StringIO
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
20
import os
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
21
import signal
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 (
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
29
    branchbuilder,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
30
    bzrdir,
4695.3.1 by Vincent Ladeuil
Fix test failures with no C extensions loaded.
31
    config,
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
32
    debug,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
33
    errors,
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
34
    lockdir,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
35
    memorytree,
36
    osutils,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
37
    progress,
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
38
    remote,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
39
    repository,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
40
    symbol_versioning,
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
41
    tests,
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
42
    transport,
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
43
    workingtree,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
44
    )
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
45
from bzrlib.repofmt import (
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
46
    groupcompress_repo,
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
47
    pack_repo,
48
    weaverepo,
49
    )
2696.1.1 by Martin Pool
Remove things deprecated in 0.11 and earlier
50
from bzrlib.symbol_versioning import (
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
51
    deprecated_function,
52
    deprecated_in,
53
    deprecated_method,
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
54
    )
1526.1.3 by Robert Collins
Merge from upstream.
55
from bzrlib.tests import (
4636.2.3 by Robert Collins
Layer tests for selftest --subunit better.
56
    SubUnitFeature,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
57
    test_lsprof,
58
    test_sftp_transport,
59
    TestUtil,
60
    )
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
61
from bzrlib.trace import note
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
62
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.
63
from bzrlib.version import _get_bzr_source_tree
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
64
65
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
66
def _test_ids(test_suite):
67
    """Get the ids for the tests in a test suite."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
68
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
69
70
71
class SelftestTests(tests.TestCase):
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
72
73
    def test_import_tests(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
74
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
75
        self.assertEqual(mod.SelftestTests, SelftestTests)
76
77
    def test_import_test_failure(self):
78
        self.assertRaises(ImportError,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
79
                          TestUtil._load_module_by_name,
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
80
                          'bzrlib.no-name-yet')
81
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
82
class MetaTestLog(tests.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.
83
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
84
    def test_logging(self):
85
        """Test logs are captured when a test fails."""
86
        self.log('a test message')
87
        self._log_file.flush()
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
88
        self.assertContainsRe(self._get_log(keep_log_file=True),
89
                              'a test message\n')
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
90
91
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
92
class TestUnicodeFilename(tests.TestCase):
3287.20.2 by John Arbash Meinel
Raise a clear error about the offending filename when there is a filename with bad characters.
93
94
    def test_probe_passes(self):
95
        """UnicodeFilename._probe passes."""
96
        # We can't test much more than that because the behaviour depends
97
        # on the platform.
98
        tests.UnicodeFilename._probe()
99
100
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
101
class TestTreeShape(tests.TestCaseInTempDir):
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.
102
103
    def test_unicode_paths(self):
3287.20.2 by John Arbash Meinel
Raise a clear error about the offending filename when there is a filename with bad characters.
104
        self.requireFeature(tests.UnicodeFilename)
105
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.
106
        filename = u'hell\u00d8'
3287.20.2 by John Arbash Meinel
Raise a clear error about the offending filename when there is a filename with bad characters.
107
        self.build_tree_contents([(filename, 'contents of hello')])
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.
108
        self.failUnlessExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
109
110
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
111
class TestTransportScenarios(tests.TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
112
    """A group of tests that test the transport implementation adaption core.
113
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
114
    This is a meta test that the tests are applied to all available
1551.1.1 by Martin Pool
[merge] branch-formats branch, and reconcile changes
115
    transports.
116
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
117
    This will be generalised in the future which is why it is in this
1530.1.21 by Robert Collins
Review feedback fixes.
118
    test file even though it is specific to transport tests at the moment.
119
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
120
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.
121
    def test_get_transport_permutations(self):
3455.1.1 by Vincent Ladeuil
Fix typos in comments.
122
        # this checks that get_test_permutations defined by the module is
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
123
        # called by the get_transport_test_permutations function.
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
124
        class MockModule(object):
125
            def get_test_permutations(self):
126
                return sample_permutation
127
        sample_permutation = [(1,2), (3,4)]
4523.1.5 by Vincent Ladeuil
Fixed as asked in review.
128
        from bzrlib.tests.per_transport import get_transport_test_permutations
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.
129
        self.assertEqual(sample_permutation,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
130
                         get_transport_test_permutations(MockModule()))
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.
131
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
132
    def test_scenarios_include_all_modules(self):
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
133
        # this checks that the scenario generator returns as many permutations
134
        # as there are in all the registered transport modules - we assume if
135
        # this matches its probably doing the right thing especially in
136
        # combination with the tests for setting the right classes below.
4523.1.5 by Vincent Ladeuil
Fixed as asked in review.
137
        from bzrlib.tests.per_transport import transport_test_permutations
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
138
        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.
139
        modules = _get_transport_modules()
140
        permutation_count = 0
141
        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.
142
            try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
143
                permutation_count += len(reduce(getattr,
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.
144
                    (module + ".get_test_permutations").split('.')[1:],
145
                     __import__(module))())
146
            except errors.DependencyNotPresent:
147
                pass
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
148
        scenarios = transport_test_permutations()
149
        self.assertEqual(permutation_count, len(scenarios))
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.
150
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
151
    def test_scenarios_include_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
152
        # This test used to know about all the possible transports and the
153
        # order they were returned but that seems overly brittle (mbp
154
        # 20060307)
4523.1.5 by Vincent Ladeuil
Fixed as asked in review.
155
        from bzrlib.tests.per_transport import transport_test_permutations
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
156
        scenarios = transport_test_permutations()
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
157
        # there are at least that many builtin transports
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
158
        self.assertTrue(len(scenarios) > 6)
159
        one_scenario = scenarios[0]
160
        self.assertIsInstance(one_scenario[0], str)
161
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
162
                                   bzrlib.transport.Transport))
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
163
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
164
                                   bzrlib.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
165
166
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
167
class TestBranchScenarios(tests.TestCase):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
168
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
169
    def test_scenarios(self):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
170
        # check that constructor parameters are passed through to the adapted
171
        # test.
4523.1.1 by Martin Pool
Rename tests.branch_implementations to per_branch
172
        from bzrlib.tests.per_branch import make_scenarios
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
173
        server1 = "a"
174
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
175
        formats = [("c", "C"), ("d", "D")]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
176
        scenarios = make_scenarios(server1, server2, formats)
177
        self.assertEqual(2, len(scenarios))
2553.2.6 by Robert Collins
And overhaul BranchTestProviderAdapter too.
178
        self.assertEqual([
179
            ('str',
180
             {'branch_format': 'c',
181
              'bzrdir_format': 'C',
182
              'transport_readonly_server': 'b',
183
              'transport_server': 'a'}),
184
            ('str',
185
             {'branch_format': 'd',
186
              'bzrdir_format': 'D',
187
              'transport_readonly_server': 'b',
188
              'transport_server': 'a'})],
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
189
            scenarios)
190
191
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
192
class TestBzrDirScenarios(tests.TestCase):
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
193
194
    def test_scenarios(self):
1534.4.39 by Robert Collins
Basic BzrDir support.
195
        # check that constructor parameters are passed through to the adapted
196
        # test.
4523.1.2 by Martin Pool
Rename bzrdir_implementations to per_bzrdir
197
        from bzrlib.tests.per_bzrdir import make_scenarios
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
198
        vfs_factory = "v"
1534.4.39 by Robert Collins
Basic BzrDir support.
199
        server1 = "a"
200
        server2 = "b"
201
        formats = ["c", "d"]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
202
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
2553.2.7 by Robert Collins
And overhaul BzrDirTestProviderAdapter too.
203
        self.assertEqual([
204
            ('str',
205
             {'bzrdir_format': 'c',
206
              'transport_readonly_server': 'b',
207
              'transport_server': 'a',
208
              'vfs_transport_factory': 'v'}),
209
            ('str',
210
             {'bzrdir_format': 'd',
211
              'transport_readonly_server': 'b',
212
              'transport_server': 'a',
213
              'vfs_transport_factory': 'v'})],
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
214
            scenarios)
215
216
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
217
class TestRepositoryScenarios(tests.TestCase):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
218
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
219
    def test_formats_to_scenarios(self):
3689.1.3 by John Arbash Meinel
Track down other tests that used repository_implementations.
220
        from bzrlib.tests.per_repository import formats_to_scenarios
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
221
        formats = [("(c)", remote.RemoteRepositoryFormat()),
222
                   ("(d)", repository.format_registry.get(
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
223
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
224
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
225
            None)
226
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
227
            vfs_transport_factory="vfs")
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
228
        # no_vfs generate scenarios without vfs_transport_factory
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
229
        expected = [
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
230
            ('RemoteRepositoryFormat(c)',
231
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
232
              'repository_format': remote.RemoteRepositoryFormat(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
233
              'transport_readonly_server': 'readonly',
234
              'transport_server': 'server'}),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
235
            ('RepositoryFormat2a(d)',
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
236
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
237
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
238
              'transport_readonly_server': 'readonly',
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
239
              'transport_server': 'server'})]
240
        self.assertEqual(expected, no_vfs_scenarios)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
241
        self.assertEqual([
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
242
            ('RemoteRepositoryFormat(c)',
243
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
244
              'repository_format': remote.RemoteRepositoryFormat(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
245
              'transport_readonly_server': 'readonly',
246
              'transport_server': 'server',
247
              'vfs_transport_factory': 'vfs'}),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
248
            ('RepositoryFormat2a(d)',
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
249
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
250
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
251
              'transport_readonly_server': 'readonly',
252
              'transport_server': 'server',
253
              'vfs_transport_factory': 'vfs'})],
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
254
            vfs_scenarios)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
255
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
256
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
257
class TestTestScenarioApplication(tests.TestCase):
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
258
    """Tests for the test adaption facilities."""
259
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
260
    def test_apply_scenario(self):
261
        from bzrlib.tests import apply_scenario
262
        input_test = TestTestScenarioApplication("test_apply_scenario")
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
263
        # setup two adapted tests
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
264
        adapted_test1 = apply_scenario(input_test,
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
265
            ("new id",
266
            {"bzrdir_format":"bzr_format",
267
             "repository_format":"repo_fmt",
268
             "transport_server":"transport_server",
269
             "transport_readonly_server":"readonly-server"}))
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
270
        adapted_test2 = apply_scenario(input_test,
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
271
            ("new id 2", {"bzrdir_format":None}))
272
        # input_test should have been altered.
273
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
274
        # the new tests are mutually incompatible, ensuring it has
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
275
        # made new ones, and unspecified elements in the scenario
276
        # should not have been altered.
277
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
278
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
279
        self.assertEqual("transport_server", adapted_test1.transport_server)
280
        self.assertEqual("readonly-server",
281
            adapted_test1.transport_readonly_server)
282
        self.assertEqual(
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
283
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
284
            "test_apply_scenario(new id)",
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
285
            adapted_test1.id())
286
        self.assertEqual(None, adapted_test2.bzrdir_format)
287
        self.assertEqual(
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
288
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
289
            "test_apply_scenario(new id 2)",
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
290
            adapted_test2.id())
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
291
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
292
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
293
class TestInterRepositoryScenarios(tests.TestCase):
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
294
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
295
    def test_scenarios(self):
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
296
        # check that constructor parameters are passed through to the adapted
297
        # test.
4523.1.5 by Vincent Ladeuil
Fixed as asked in review.
298
        from bzrlib.tests.per_interrepository import make_scenarios
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
299
        server1 = "a"
300
        server2 = "b"
4476.3.85 by Andrew Bennetts
Update TestInterRepositoryScenarios.test_scenarios for change to per_interrepo make_scenarios.
301
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
302
        scenarios = make_scenarios(server1, server2, formats)
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
303
        self.assertEqual([
4476.3.85 by Andrew Bennetts
Update TestInterRepositoryScenarios.test_scenarios for change to per_interrepo make_scenarios.
304
            ('C0,str,str',
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
305
             {'repository_format': 'C1',
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
306
              'repository_format_to': 'C2',
307
              'transport_readonly_server': 'b',
308
              'transport_server': 'a'}),
4476.3.85 by Andrew Bennetts
Update TestInterRepositoryScenarios.test_scenarios for change to per_interrepo make_scenarios.
309
            ('D0,str,str',
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
310
             {'repository_format': 'D1',
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
311
              'repository_format_to': 'D2',
312
              'transport_readonly_server': 'b',
313
              'transport_server': 'a'})],
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
314
            scenarios)
315
316
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
317
class TestWorkingTreeScenarios(tests.TestCase):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
318
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
319
    def test_scenarios(self):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
320
        # check that constructor parameters are passed through to the adapted
321
        # test.
4523.1.5 by Vincent Ladeuil
Fixed as asked in review.
322
        from bzrlib.tests.per_workingtree import make_scenarios
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
323
        server1 = "a"
324
        server2 = "b"
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
325
        formats = [workingtree.WorkingTreeFormat2(),
326
                   workingtree.WorkingTreeFormat3(),]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
327
        scenarios = make_scenarios(server1, server2, formats)
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
328
        self.assertEqual([
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
329
            ('WorkingTreeFormat2',
330
             {'bzrdir_format': formats[0]._matchingbzrdir,
331
              'transport_readonly_server': 'b',
332
              'transport_server': 'a',
333
              'workingtree_format': formats[0]}),
334
            ('WorkingTreeFormat3',
335
             {'bzrdir_format': formats[1]._matchingbzrdir,
336
              'transport_readonly_server': 'b',
337
              'transport_server': 'a',
338
              'workingtree_format': formats[1]})],
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
339
            scenarios)
340
341
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
342
class TestTreeScenarios(tests.TestCase):
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
343
344
    def test_scenarios(self):
345
        # the tree implementation scenario generator is meant to setup one
346
        # instance for each working tree format, and one additional instance
347
        # that will use the default wt format, but create a revision tree for
348
        # the tests.  this means that the wt ones should have the
349
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
350
        # revision one set to revision_tree_from_workingtree.
1852.6.1 by Robert Collins
Start tree implementation tests.
351
4523.1.4 by Martin Pool
Rename remaining *_implementations tests
352
        from bzrlib.tests.per_tree import (
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
353
            _dirstate_tree_from_workingtree,
354
            make_scenarios,
355
            preview_tree_pre,
356
            preview_tree_post,
1852.6.1 by Robert Collins
Start tree implementation tests.
357
            return_parameter,
358
            revision_tree_from_workingtree
359
            )
360
        server1 = "a"
361
        server2 = "b"
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
362
        formats = [workingtree.WorkingTreeFormat2(),
363
                   workingtree.WorkingTreeFormat3(),]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
364
        scenarios = make_scenarios(server1, server2, formats)
365
        self.assertEqual(7, len(scenarios))
366
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
367
        wt4_format = workingtree.WorkingTreeFormat4()
368
        wt5_format = workingtree.WorkingTreeFormat5()
369
        expected_scenarios = [
370
            ('WorkingTreeFormat2',
371
             {'bzrdir_format': formats[0]._matchingbzrdir,
372
              'transport_readonly_server': 'b',
373
              'transport_server': 'a',
374
              'workingtree_format': formats[0],
375
              '_workingtree_to_test_tree': return_parameter,
376
              }),
377
            ('WorkingTreeFormat3',
378
             {'bzrdir_format': formats[1]._matchingbzrdir,
379
              'transport_readonly_server': 'b',
380
              'transport_server': 'a',
381
              'workingtree_format': formats[1],
382
              '_workingtree_to_test_tree': return_parameter,
383
             }),
384
            ('RevisionTree',
385
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
386
              'bzrdir_format': default_wt_format._matchingbzrdir,
387
              'transport_readonly_server': 'b',
388
              'transport_server': 'a',
389
              'workingtree_format': default_wt_format,
390
             }),
391
            ('DirStateRevisionTree,WT4',
392
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
393
              'bzrdir_format': wt4_format._matchingbzrdir,
394
              'transport_readonly_server': 'b',
395
              'transport_server': 'a',
396
              'workingtree_format': wt4_format,
397
             }),
398
            ('DirStateRevisionTree,WT5',
399
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
400
              'bzrdir_format': wt5_format._matchingbzrdir,
401
              'transport_readonly_server': 'b',
402
              'transport_server': 'a',
403
              'workingtree_format': wt5_format,
404
             }),
405
            ('PreviewTree',
406
             {'_workingtree_to_test_tree': preview_tree_pre,
407
              'bzrdir_format': default_wt_format._matchingbzrdir,
408
              'transport_readonly_server': 'b',
409
              'transport_server': 'a',
410
              'workingtree_format': default_wt_format}),
411
            ('PreviewTreePost',
412
             {'_workingtree_to_test_tree': preview_tree_post,
413
              'bzrdir_format': default_wt_format._matchingbzrdir,
414
              'transport_readonly_server': 'b',
415
              'transport_server': 'a',
416
              'workingtree_format': default_wt_format}),
417
             ]
418
        self.assertEqual(expected_scenarios, scenarios)
419
420
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
421
class TestInterTreeScenarios(tests.TestCase):
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
422
    """A group of tests that test the InterTreeTestAdapter."""
423
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
424
    def test_scenarios(self):
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
425
        # check that constructor parameters are passed through to the adapted
426
        # test.
427
        # for InterTree tests we want the machinery to bring up two trees in
428
        # each instance: the base one, and the one we are interacting with.
429
        # because each optimiser can be direction specific, we need to test
430
        # each optimiser in its chosen direction.
431
        # unlike the TestProviderAdapter we dont want to automatically add a
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
432
        # parameterized one for WorkingTree - the optimisers will tell us what
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
433
        # ones to add.
4523.1.4 by Martin Pool
Rename remaining *_implementations tests
434
        from bzrlib.tests.per_tree import (
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
435
            return_parameter,
436
            revision_tree_from_workingtree
437
            )
4523.1.4 by Martin Pool
Rename remaining *_implementations tests
438
        from bzrlib.tests.per_intertree import (
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
439
            make_scenarios,
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
440
            )
441
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
442
        input_test = TestInterTreeScenarios(
443
            "test_scenarios")
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
444
        server1 = "a"
445
        server2 = "b"
446
        format1 = WorkingTreeFormat2()
447
        format2 = WorkingTreeFormat3()
3696.4.19 by Robert Collins
Update missed test for InterTree test generation.
448
        formats = [("1", str, format1, format2, "converter1"),
449
            ("2", int, format2, format1, "converter2")]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
450
        scenarios = make_scenarios(server1, server2, formats)
451
        self.assertEqual(2, len(scenarios))
452
        expected_scenarios = [
453
            ("1", {
454
                "bzrdir_format": format1._matchingbzrdir,
455
                "intertree_class": formats[0][1],
456
                "workingtree_format": formats[0][2],
457
                "workingtree_format_to": formats[0][3],
458
                "mutable_trees_to_test_trees": formats[0][4],
459
                "_workingtree_to_test_tree": return_parameter,
460
                "transport_server": server1,
461
                "transport_readonly_server": server2,
462
                }),
463
            ("2", {
464
                "bzrdir_format": format2._matchingbzrdir,
465
                "intertree_class": formats[1][1],
466
                "workingtree_format": formats[1][2],
467
                "workingtree_format_to": formats[1][3],
468
                "mutable_trees_to_test_trees": formats[1][4],
469
                "_workingtree_to_test_tree": return_parameter,
470
                "transport_server": server1,
471
                "transport_readonly_server": server2,
472
                }),
473
            ]
474
        self.assertEqual(scenarios, expected_scenarios)
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
475
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
476
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
477
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
478
479
    def test_home_is_not_working(self):
480
        self.assertNotEqual(self.test_dir, self.test_home_dir)
481
        cwd = osutils.getcwd()
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
482
        self.assertIsSameRealPath(self.test_dir, cwd)
483
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
484
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
485
    def test_assertEqualStat_equal(self):
486
        from bzrlib.tests.test_dirstate import _FakeStat
487
        self.build_tree(["foo"])
488
        real = os.lstat("foo")
489
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
490
            real.st_dev, real.st_ino, real.st_mode)
491
        self.assertEqualStat(real, fake)
492
493
    def test_assertEqualStat_notequal(self):
494
        self.build_tree(["foo", "bar"])
495
        self.assertRaises(AssertionError, self.assertEqualStat,
496
            os.lstat("foo"), os.lstat("bar"))
497
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
498
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
499
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
500
501
    def test_home_is_non_existant_dir_under_root(self):
502
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
503
504
        This is because TestCaseWithMemoryTransport is for tests that do not
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
505
        need any disk resources: they should be hooked into bzrlib in such a
506
        way that no global settings are being changed by the test (only a
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
507
        few tests should need to do that), and having a missing dir as home is
508
        an effective way to ensure that this is the case.
509
        """
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
510
        self.assertIsSameRealPath(
511
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
512
            self.test_home_dir)
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
513
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
514
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
515
    def test_cwd_is_TEST_ROOT(self):
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
516
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
517
        cwd = osutils.getcwd()
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
518
        self.assertIsSameRealPath(self.test_dir, cwd)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
519
520
    def test_make_branch_and_memory_tree(self):
521
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
522
523
        This is hard to comprehensively robustly test, so we settle for making
524
        a branch and checking no directory was created at its relpath.
525
        """
526
        tree = self.make_branch_and_memory_tree('dir')
2227.2.2 by v.ladeuil+lp at free
Cleanup.
527
        # Guard against regression into MemoryTransport leaking
528
        # files to disk instead of keeping them in memory.
529
        self.failIf(osutils.lexists('dir'))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
530
        self.assertIsInstance(tree, memorytree.MemoryTree)
531
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
532
    def test_make_branch_and_memory_tree_with_format(self):
533
        """make_branch_and_memory_tree should accept a format option."""
534
        format = bzrdir.BzrDirMetaFormat1()
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
535
        format.repository_format = weaverepo.RepositoryFormat7()
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
536
        tree = self.make_branch_and_memory_tree('dir', format=format)
2227.2.2 by v.ladeuil+lp at free
Cleanup.
537
        # Guard against regression into MemoryTransport leaking
538
        # files to disk instead of keeping them in memory.
539
        self.failIf(osutils.lexists('dir'))
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
540
        self.assertIsInstance(tree, memorytree.MemoryTree)
541
        self.assertEqual(format.repository_format.__class__,
542
            tree.branch.repository._format.__class__)
543
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
544
    def test_make_branch_builder(self):
545
        builder = self.make_branch_builder('dir')
546
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
547
        # Guard against regression into MemoryTransport leaking
548
        # files to disk instead of keeping them in memory.
549
        self.failIf(osutils.lexists('dir'))
550
551
    def test_make_branch_builder_with_format(self):
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
552
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
553
        # that the format objects are used.
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
554
        format = bzrdir.BzrDirMetaFormat1()
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
555
        repo_format = weaverepo.RepositoryFormat7()
556
        format.repository_format = repo_format
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
557
        builder = self.make_branch_builder('dir', format=format)
558
        the_branch = builder.get_branch()
559
        # Guard against regression into MemoryTransport leaking
560
        # files to disk instead of keeping them in memory.
561
        self.failIf(osutils.lexists('dir'))
562
        self.assertEqual(format.repository_format.__class__,
563
                         the_branch.repository._format.__class__)
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
564
        self.assertEqual(repo_format.get_format_string(),
565
                         self.get_transport().get_bytes(
566
                            'dir/.bzr/repository/format'))
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
567
568
    def test_make_branch_builder_with_format_name(self):
569
        builder = self.make_branch_builder('dir', format='knit')
570
        the_branch = builder.get_branch()
571
        # Guard against regression into MemoryTransport leaking
572
        # files to disk instead of keeping them in memory.
573
        self.failIf(osutils.lexists('dir'))
574
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
575
        self.assertEqual(dir_format.repository_format.__class__,
576
                         the_branch.repository._format.__class__)
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
577
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
578
                         self.get_transport().get_bytes(
579
                            'dir/.bzr/repository/format'))
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
580
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
581
    def test_dangling_locks_cause_failures(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
582
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
583
            def test_function(self):
584
                t = self.get_transport('.')
585
                l = lockdir.LockDir(t, 'lock')
586
                l.create()
587
                l.attempt_lock()
588
        test = TestDanglingLock('test_function')
4314.2.1 by Robert Collins
Update lock debugging support patch.
589
        result = test.run()
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
590
        if self._lock_check_thorough:
591
            self.assertEqual(1, len(result.errors))
592
        else:
593
            # When _lock_check_thorough is disabled, then we don't trigger a
594
            # failure
595
            self.assertEqual(0, len(result.errors))
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
596
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
597
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
598
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
599
    """Tests for the convenience functions TestCaseWithTransport introduces."""
600
601
    def test_get_readonly_url_none(self):
602
        from bzrlib.transport import get_transport
603
        from bzrlib.transport.memory import MemoryServer
604
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
605
        self.vfs_transport_factory = MemoryServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
606
        self.transport_readonly_server = None
607
        # calling get_readonly_transport() constructs a decorator on the url
608
        # for the server
609
        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.
610
        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.
611
        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.
612
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
613
        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.
614
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
615
        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.
616
617
    def test_get_readonly_url_http(self):
2929.3.7 by Vincent Ladeuil
Rename bzrlib/test/HttpServer.py to bzrlib/tests/http_server.py and fix uses.
618
        from bzrlib.tests.http_server import HttpServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
619
        from bzrlib.transport import get_transport
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
620
        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 :)
621
        from bzrlib.transport.http import HttpTransportBase
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
622
        self.transport_server = LocalURLServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
623
        self.transport_readonly_server = HttpServer
624
        # calling get_readonly_transport() gives us a HTTP server instance.
625
        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.
626
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
627
        # 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.
628
        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.
629
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
630
        self.failUnless(isinstance(t, HttpTransportBase))
631
        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.
632
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
633
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
634
    def test_is_directory(self):
635
        """Test assertIsDirectory assertion"""
636
        t = self.get_transport()
637
        self.build_tree(['a_dir/', 'a_file'], transport=t)
638
        self.assertIsDirectory('a_dir', t)
639
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
640
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
641
3567.4.13 by John Arbash Meinel
Test that make_branch_builder works on a real filesystem.
642
    def test_make_branch_builder(self):
643
        builder = self.make_branch_builder('dir')
644
        rev_id = builder.build_commit()
645
        self.failUnlessExists('dir')
646
        a_dir = bzrdir.BzrDir.open('dir')
647
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
648
        a_branch = a_dir.open_branch()
649
        builder_branch = builder.get_branch()
650
        self.assertEqual(a_branch.base, builder_branch.base)
651
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
652
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
653
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
654
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
655
class TestTestCaseTransports(tests.TestCaseWithTransport):
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
656
657
    def setUp(self):
658
        super(TestTestCaseTransports, self).setUp()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
659
        self.vfs_transport_factory = MemoryServer
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
660
661
    def test_make_bzrdir_preserves_transport(self):
662
        t = self.get_transport()
663
        result_bzrdir = self.make_bzrdir('subdir')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
664
        self.assertIsInstance(result_bzrdir.transport,
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
665
                              MemoryTransport)
666
        # should not be on disk, should only be in memory
667
        self.failIfExists('subdir')
668
669
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
670
class TestChrootedTest(tests.ChrootedTestCase):
1534.4.31 by Robert Collins
cleanedup test_outside_wt
671
672
    def test_root_is_root(self):
673
        from bzrlib.transport import get_transport
674
        t = get_transport(self.get_readonly_url())
675
        url = t.base
676
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
677
678
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
679
class TestProfileResult(tests.TestCase):
680
681
    def test_profiles_tests(self):
4641.3.5 by Robert Collins
Properly guard LSProf using tests.
682
        self.requireFeature(test_lsprof.LSProfFeature)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
683
        terminal = unittest.TestResult()
684
        result = tests.ProfileResult(terminal)
685
        class Sample(tests.TestCase):
686
            def a(self):
687
                self.sample_function()
688
            def sample_function(self):
689
                pass
690
        test = Sample("a")
691
        test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
692
        test.run(result)
693
        self.assertLength(1, test._benchcalls)
694
        # We must be able to unpack it as the test reporting code wants
695
        (_, _, _), stats = test._benchcalls[0]
696
        self.assertTrue(callable(stats.pprint))
697
698
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
699
class TestTestResult(tests.TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
700
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
701
    def check_timing(self, test_case, expected_re):
2095.4.1 by Martin Pool
Better progress bars during tests
702
        result = bzrlib.tests.TextTestResult(self._log_file,
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
703
                descriptions=0,
704
                verbosity=1,
705
                )
706
        test_case.run(result)
707
        timed_string = result._testTimeString(test_case)
708
        self.assertContainsRe(timed_string, expected_re)
709
710
    def test_test_reporting(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
711
        class ShortDelayTestCase(tests.TestCase):
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
712
            def test_short_delay(self):
713
                time.sleep(0.003)
714
            def test_short_benchmark(self):
715
                self.time(time.sleep, 0.003)
716
        self.check_timing(ShortDelayTestCase('test_short_delay'),
717
                          r"^ +[0-9]+ms$")
4536.5.3 by Martin Pool
Correction to selftest test for benchmark time display
718
        # if a benchmark time is given, we now show just that time followed by
719
        # a star
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
720
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
4536.5.3 by Martin Pool
Correction to selftest test for benchmark time display
721
                          r"^ +[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).
722
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
723
    def test_unittest_reporting_unittest_class(self):
724
        # getting the time from a non-bzrlib test works ok
725
        class ShortDelayTestCase(unittest.TestCase):
726
            def test_short_delay(self):
727
                time.sleep(0.003)
728
        self.check_timing(ShortDelayTestCase('test_short_delay'),
729
                          r"^ +[0-9]+ms$")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
730
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
731
    def _patch_get_bzr_source_tree(self):
732
        # Reading from the actual source tree breaks isolation, but we don't
733
        # want to assume that thats *all* that would happen.
734
        def _get_bzr_source_tree():
735
            return None
736
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
737
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
738
        def restore():
739
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
740
        self.addCleanup(restore)
741
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
742
    def test_assigned_benchmark_file_stores_date(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
743
        self._patch_get_bzr_source_tree()
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
744
        output = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
745
        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
746
                                        descriptions=0,
747
                                        verbosity=1,
748
                                        bench_history=output
749
                                        )
750
        output_string = output.getvalue()
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
751
        # if you are wondering about the regexp please read the comment in
752
        # 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.
753
        # XXX: what comment?  -- Andrew Bennetts
754
        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
755
756
    def test_benchhistory_records_test_times(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
757
        self._patch_get_bzr_source_tree()
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
758
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
759
        result = bzrlib.tests.TextTestResult(
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
760
            self._log_file,
761
            descriptions=0,
762
            verbosity=1,
763
            bench_history=result_stream
764
            )
765
766
        # we want profile a call and check that its test duration is recorded
767
        # make a new test instance that when run will generate a benchmark
768
        example_test_case = TestTestResult("_time_hello_world_encoding")
769
        # execute the test, which should succeed and record times
770
        example_test_case.run(result)
771
        lines = result_stream.getvalue().splitlines()
772
        self.assertEqual(2, len(lines))
773
        self.assertContainsRe(lines[1],
774
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
775
            "._time_hello_world_encoding")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
776
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
777
    def _time_hello_world_encoding(self):
778
        """Profile two sleep calls
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
779
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
780
        This is used to exercise the test framework.
781
        """
782
        self.time(unicode, 'hello', errors='replace')
783
        self.time(unicode, 'world', errors='replace')
784
785
    def test_lsprofiling(self):
786
        """Verbose test result prints lsprof statistics from test cases."""
1551.15.28 by Aaron Bentley
Improve Feature usage style w/ lsprof
787
        self.requireFeature(test_lsprof.LSProfFeature)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
788
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
789
        result = bzrlib.tests.VerboseTestResult(
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
790
            unittest._WritelnDecorator(result_stream),
791
            descriptions=0,
792
            verbosity=2,
793
            )
794
        # we want profile a call of some sort and check it is output by
795
        # addSuccess. We dont care about addError or addFailure as they
796
        # are not that interesting for performance tuning.
797
        # make a new test instance that when run will generate a profile
798
        example_test_case = TestTestResult("_time_hello_world_encoding")
799
        example_test_case._gather_lsprof_in_benchmarks = True
800
        # execute the test, which should succeed and record profiles
801
        example_test_case.run(result)
802
        # lsprofile_something()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
803
        # if this worked we want
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
804
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
805
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
806
        # (the lsprof header)
807
        # ... an arbitrary number of lines
808
        # and the function call which is time.sleep.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
809
        #           1        0            ???         ???       ???(sleep)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
810
        # and then repeated but with 'world', rather than 'hello'.
811
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
812
        output = result_stream.getvalue()
813
        self.assertContainsRe(output,
814
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
815
        self.assertContainsRe(output,
816
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
817
        self.assertContainsRe(output,
818
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
819
        self.assertContainsRe(output,
820
            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
821
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
822
    def test_known_failure(self):
823
        """A KnownFailure being raised should trigger several result actions."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
824
        class InstrumentedTestResult(tests.ExtendedTestResult):
4650.1.6 by Robert Collins
Fix interface skew between bzr selftest and python unittest - use stopTestRun not done to end test runs.
825
            def stopTestRun(self): pass
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
826
            def startTests(self): pass
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
827
            def report_test_start(self, test): pass
828
            def report_known_failure(self, test, err):
829
                self._call = test, err
830
        result = InstrumentedTestResult(None, None, None, None)
831
        def test_function():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
832
            raise tests.KnownFailure('failed!')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
833
        test = unittest.FunctionTestCase(test_function)
834
        test.run(result)
835
        # it should invoke 'report_known_failure'.
836
        self.assertEqual(2, len(result._call))
837
        self.assertEqual(test, result._call[0])
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
838
        self.assertEqual(tests.KnownFailure, result._call[1][0])
839
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
840
        # we dont introspec the traceback, if the rest is ok, it would be
841
        # exceptional for it not to be.
842
        # it should update the known_failure_count on the object.
843
        self.assertEqual(1, result.known_failure_count)
844
        # the result should be successful.
845
        self.assertTrue(result.wasSuccessful())
846
847
    def test_verbose_report_known_failure(self):
848
        # verbose test output formatting
849
        result_stream = StringIO()
850
        result = bzrlib.tests.VerboseTestResult(
851
            unittest._WritelnDecorator(result_stream),
852
            descriptions=0,
853
            verbosity=2,
854
            )
855
        test = self.get_passing_test()
856
        result.startTest(test)
857
        prefix = len(result_stream.getvalue())
858
        # the err parameter has the shape:
859
        # (class, exception object, traceback)
860
        # KnownFailures dont get their tracebacks shown though, so we
861
        # can skip that.
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
862
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
863
        result.report_known_failure(test, err)
864
        output = result_stream.getvalue()[prefix:]
865
        lines = output.splitlines()
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
866
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
867
        self.assertEqual(lines[1], '    foo')
868
        self.assertEqual(2, len(lines))
869
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
870
    def get_passing_test(self):
871
        """Return a test object that can't be run usefully."""
872
        def passing_test():
873
            pass
874
        return unittest.FunctionTestCase(passing_test)
875
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
876
    def test_add_not_supported(self):
877
        """Test the behaviour of invoking addNotSupported."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
878
        class InstrumentedTestResult(tests.ExtendedTestResult):
4650.1.6 by Robert Collins
Fix interface skew between bzr selftest and python unittest - use stopTestRun not done to end test runs.
879
            def stopTestRun(self): pass
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
880
            def startTests(self): pass
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
881
            def report_test_start(self, test): pass
882
            def report_unsupported(self, test, feature):
883
                self._call = test, feature
884
        result = InstrumentedTestResult(None, None, None, None)
885
        test = SampleTestCase('_test_pass')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
886
        feature = tests.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
887
        result.startTest(test)
888
        result.addNotSupported(test, feature)
889
        # it should invoke 'report_unsupported'.
890
        self.assertEqual(2, len(result._call))
891
        self.assertEqual(test, result._call[0])
892
        self.assertEqual(feature, result._call[1])
893
        # the result should be successful.
894
        self.assertTrue(result.wasSuccessful())
895
        # it should record the test against a count of tests not run due to
896
        # this feature.
897
        self.assertEqual(1, result.unsupported['Feature'])
898
        # and invoking it again should increment that counter
899
        result.addNotSupported(test, feature)
900
        self.assertEqual(2, result.unsupported['Feature'])
901
902
    def test_verbose_report_unsupported(self):
903
        # verbose test output formatting
904
        result_stream = StringIO()
905
        result = bzrlib.tests.VerboseTestResult(
906
            unittest._WritelnDecorator(result_stream),
907
            descriptions=0,
908
            verbosity=2,
909
            )
910
        test = self.get_passing_test()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
911
        feature = tests.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
912
        result.startTest(test)
913
        prefix = len(result_stream.getvalue())
914
        result.report_unsupported(test, feature)
915
        output = result_stream.getvalue()[prefix:]
916
        lines = output.splitlines()
4536.5.5 by Martin Pool
More selftest display test tweaks
917
        self.assertEqual(lines, ['NODEP        0ms',
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
918
                                 "    The feature 'Feature' is not available."])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
919
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
920
    def test_unavailable_exception(self):
921
        """An UnavailableFeature being raised should invoke addNotSupported."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
922
        class InstrumentedTestResult(tests.ExtendedTestResult):
4650.1.6 by Robert Collins
Fix interface skew between bzr selftest and python unittest - use stopTestRun not done to end test runs.
923
            def stopTestRun(self): pass
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
924
            def startTests(self): pass
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
925
            def report_test_start(self, test): pass
926
            def addNotSupported(self, test, feature):
927
                self._call = test, feature
928
        result = InstrumentedTestResult(None, None, None, None)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
929
        feature = tests.Feature()
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
930
        def test_function():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
931
            raise tests.UnavailableFeature(feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
932
        test = unittest.FunctionTestCase(test_function)
933
        test.run(result)
934
        # it should invoke 'addNotSupported'.
935
        self.assertEqual(2, len(result._call))
936
        self.assertEqual(test, result._call[0])
937
        self.assertEqual(feature, result._call[1])
938
        # and not count as an error
939
        self.assertEqual(0, result.error_count)
940
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
941
    def test_strict_with_unsupported_feature(self):
942
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
943
                                             verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
944
        test = self.get_passing_test()
945
        feature = "Unsupported Feature"
946
        result.addNotSupported(test, feature)
947
        self.assertFalse(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
948
        self.assertEqual(None, result._extractBenchmarkTime(test))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
949
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
950
    def test_strict_with_known_failure(self):
951
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
952
                                             verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
953
        test = self.get_passing_test()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
954
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
955
        result._addKnownFailure(test, err)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
956
        self.assertFalse(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
957
        self.assertEqual(None, result._extractBenchmarkTime(test))
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
958
959
    def test_strict_with_success(self):
960
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
961
                                             verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
962
        test = self.get_passing_test()
963
        result.addSuccess(test)
964
        self.assertTrue(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
965
        self.assertEqual(None, result._extractBenchmarkTime(test))
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
966
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
967
    def test_startTests(self):
968
        """Starting the first test should trigger startTests."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
969
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
970
            calls = 0
971
            def startTests(self): self.calls += 1
4271.2.4 by Vincent Ladeuil
Take subunit update into account.
972
            def report_test_start(self, test): pass
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
973
        result = InstrumentedTestResult(None, None, None, None)
974
        def test_function():
975
            pass
976
        test = unittest.FunctionTestCase(test_function)
977
        test.run(result)
978
        self.assertEquals(1, result.calls)
979
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
980
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
981
class TestUnicodeFilenameFeature(tests.TestCase):
3477.1.1 by John Arbash Meinel
Move UnicodeFeature into a core 'tests' feature, rather than living in test_diff.
982
983
    def test_probe_passes(self):
3477.1.2 by John Arbash Meinel
Rename UnicodeFilename => UnicodeFilenameFeature
984
        """UnicodeFilenameFeature._probe passes."""
3477.1.1 by John Arbash Meinel
Move UnicodeFeature into a core 'tests' feature, rather than living in test_diff.
985
        # We can't test much more than that because the behaviour depends
986
        # on the platform.
3477.1.2 by John Arbash Meinel
Rename UnicodeFilename => UnicodeFilenameFeature
987
        tests.UnicodeFilenameFeature._probe()
3477.1.1 by John Arbash Meinel
Move UnicodeFeature into a core 'tests' feature, rather than living in test_diff.
988
989
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
990
class TestRunner(tests.TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
991
992
    def dummy_test(self):
993
        pass
994
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
995
    def run_test_runner(self, testrunner, test):
996
        """Run suite in testrunner, saving global state and restoring it.
997
998
        This current saves and restores:
999
        TestCaseInTempDir.TEST_ROOT
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1000
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1001
        There should be no tests in this file that use
1002
        bzrlib.tests.TextTestRunner without using this convenience method,
1003
        because of our use of global state.
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1004
        """
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1005
        old_root = tests.TestCaseInTempDir.TEST_ROOT
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1006
        old_leak = tests.TestCase._first_thread_leaker_id
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1007
        try:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1008
            tests.TestCaseInTempDir.TEST_ROOT = None
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1009
            tests.TestCase._first_thread_leaker_id = None
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1010
            return testrunner.run(test)
1011
        finally:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1012
            tests.TestCaseInTempDir.TEST_ROOT = old_root
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1013
            tests.TestCase._first_thread_leaker_id = old_leak
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1014
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1015
    def test_known_failure_failed_run(self):
1016
        # run a test that generates a known failure which should be printed in
1017
        # the final output when real failures occur.
1018
        def known_failure_test():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1019
            raise tests.KnownFailure('failed')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1020
        test = unittest.TestSuite()
1021
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1022
        def failing_test():
1023
            raise AssertionError('foo')
1024
        test.addTest(unittest.FunctionTestCase(failing_test))
1025
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1026
        runner = tests.TextTestRunner(stream=stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1027
        result = self.run_test_runner(runner, test)
1028
        lines = stream.getvalue().splitlines()
4595.7.4 by Martin Pool
Change overly-tight selftest test to use a re
1029
        self.assertContainsRe(stream.getvalue(),
1030
            '(?sm)^testing.*$'
1031
            '.*'
1032
            '^======================================================================\n'
1033
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
1034
            '^----------------------------------------------------------------------\n'
1035
            'Traceback \\(most recent call last\\):\n'
1036
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1037
            '    raise AssertionError\\(\'foo\'\\)\n'
1038
            '.*'
1039
            '^----------------------------------------------------------------------\n'
1040
            '.*'
1041
            'FAILED \\(failures=1, known_failure_count=1\\)'
1042
            )
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1043
1044
    def test_known_failure_ok_run(self):
1045
        # run a test that generates a known failure which should be printed in the final output.
1046
        def known_failure_test():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1047
            raise tests.KnownFailure('failed')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1048
        test = unittest.FunctionTestCase(known_failure_test)
1049
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1050
        runner = tests.TextTestRunner(stream=stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1051
        result = self.run_test_runner(runner, test)
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
1052
        self.assertContainsRe(stream.getvalue(),
1053
            '\n'
1054
            '-*\n'
1055
            'Ran 1 test in .*\n'
1056
            '\n'
1057
            'OK \\(known_failures=1\\)\n')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1058
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1059
    def test_result_decorator(self):
1060
        # decorate results
1061
        calls = []
1062
        class LoggingDecorator(tests.ForwardingResult):
1063
            def startTest(self, test):
1064
                tests.ForwardingResult.startTest(self, test)
1065
                calls.append('start')
1066
        test = unittest.FunctionTestCase(lambda:None)
1067
        stream = StringIO()
1068
        runner = tests.TextTestRunner(stream=stream,
1069
            result_decorators=[LoggingDecorator])
1070
        result = self.run_test_runner(runner, test)
1071
        self.assertLength(1, calls)
1072
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1073
    def test_skipped_test(self):
1074
        # run a test that is skipped, and check the suite as a whole still
1075
        # succeeds.
1076
        # skipping_test must be hidden in here so it's not run as a real test
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1077
        class SkippingTest(tests.TestCase):
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1078
            def skipping_test(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1079
                raise tests.TestSkipped('test intentionally skipped')
1080
        runner = tests.TextTestRunner(stream=self._log_file)
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1081
        test = SkippingTest("skipping_test")
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1082
        result = self.run_test_runner(runner, test)
1083
        self.assertTrue(result.wasSuccessful())
1084
1085
    def test_skipped_from_setup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1086
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1087
        class SkippedSetupTest(tests.TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1088
1089
            def setUp(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1090
                calls.append('setUp')
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1091
                self.addCleanup(self.cleanup)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1092
                raise tests.TestSkipped('skipped setup')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1093
1094
            def test_skip(self):
1095
                self.fail('test reached')
1096
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1097
            def cleanup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1098
                calls.append('cleanup')
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1099
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1100
        runner = tests.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.
1101
        test = SkippedSetupTest('test_skip')
1102
        result = self.run_test_runner(runner, test)
1103
        self.assertTrue(result.wasSuccessful())
1104
        # Check if cleanup was called the right number of times.
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1105
        self.assertEqual(['setUp', 'cleanup'], calls)
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1106
1107
    def test_skipped_from_test(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1108
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1109
        class SkippedTest(tests.TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1110
1111
            def setUp(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1112
                tests.TestCase.setUp(self)
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1113
                calls.append('setUp')
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1114
                self.addCleanup(self.cleanup)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1115
1116
            def test_skip(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1117
                raise tests.TestSkipped('skipped test')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1118
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1119
            def cleanup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1120
                calls.append('cleanup')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1121
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1122
        runner = tests.TextTestRunner(stream=self._log_file)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1123
        test = SkippedTest('test_skip')
1124
        result = self.run_test_runner(runner, test)
1125
        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.
1126
        # Check if cleanup was called the right number of times.
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1127
        self.assertEqual(['setUp', 'cleanup'], calls)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1128
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1129
    def test_not_applicable(self):
1130
        # run a test that is skipped because it's not applicable
1131
        def not_applicable_test():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1132
            raise tests.TestNotApplicable('this test never runs')
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1133
        out = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1134
        runner = tests.TextTestRunner(stream=out, verbosity=2)
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1135
        test = unittest.FunctionTestCase(not_applicable_test)
1136
        result = self.run_test_runner(runner, test)
1137
        self._log_file.write(out.getvalue())
1138
        self.assertTrue(result.wasSuccessful())
1139
        self.assertTrue(result.wasStrictlySuccessful())
1140
        self.assertContainsRe(out.getvalue(),
1141
                r'(?m)not_applicable_test   * N/A')
1142
        self.assertContainsRe(out.getvalue(),
1143
                r'(?m)^    this test never runs')
1144
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1145
    def test_unsupported_features_listed(self):
1146
        """When unsupported features are encountered they are detailed."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1147
        class Feature1(tests.Feature):
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1148
            def _probe(self): return False
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1149
        class Feature2(tests.Feature):
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1150
            def _probe(self): return False
1151
        # create sample tests
1152
        test1 = SampleTestCase('_test_pass')
1153
        test1._test_needs_features = [Feature1()]
1154
        test2 = SampleTestCase('_test_pass')
1155
        test2._test_needs_features = [Feature2()]
1156
        test = unittest.TestSuite()
1157
        test.addTest(test1)
1158
        test.addTest(test2)
1159
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1160
        runner = tests.TextTestRunner(stream=stream)
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1161
        result = self.run_test_runner(runner, test)
1162
        lines = stream.getvalue().splitlines()
1163
        self.assertEqual([
1164
            'OK',
1165
            "Missing feature 'Feature1' skipped 1 tests.",
1166
            "Missing feature 'Feature2' skipped 1 tests.",
1167
            ],
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1168
            lines[-3:])
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1169
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
1170
    def _patch_get_bzr_source_tree(self):
1171
        # Reading from the actual source tree breaks isolation, but we don't
1172
        # want to assume that thats *all* that would happen.
1173
        self._get_source_tree_calls = []
1174
        def _get_bzr_source_tree():
1175
            self._get_source_tree_calls.append("called")
1176
            return None
1177
        orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
1178
        bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
1179
        def restore():
1180
            bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
1181
        self.addCleanup(restore)
1182
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1183
    def test_bench_history(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
1184
        # tests that the running the benchmark passes bench_history into
1185
        # the test result object. We can tell that happens if
1186
        # _get_bzr_source_tree is called.
1187
        self._patch_get_bzr_source_tree()
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1188
        test = TestRunner('dummy_test')
1189
        output = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1190
        runner = tests.TextTestRunner(stream=self._log_file,
1191
                                      bench_history=output)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
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.]+")
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
1195
        self.assertLength(1, self._get_source_tree_calls)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1196
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1197
    def assertLogDeleted(self, test):
1198
        log = test._get_log()
1199
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1200
        self.assertEqual('', test._log_contents)
1201
        self.assertIs(None, test._log_file_name)
1202
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1203
    def test_success_log_deleted(self):
1204
        """Successful tests have their log deleted"""
1205
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1206
        class LogTester(tests.TestCase):
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1207
1208
            def test_success(self):
1209
                self.log('this will be removed\n')
1210
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1211
        sio = StringIO()
1212
        runner = tests.TextTestRunner(stream=sio)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1213
        test = LogTester('test_success')
1214
        result = self.run_test_runner(runner, test)
1215
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1216
        self.assertLogDeleted(test)
1217
1218
    def test_skipped_log_deleted(self):
1219
        """Skipped tests have their log deleted"""
1220
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1221
        class LogTester(tests.TestCase):
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1222
1223
            def test_skipped(self):
1224
                self.log('this will be removed\n')
1225
                raise tests.TestSkipped()
1226
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1227
        sio = StringIO()
1228
        runner = tests.TextTestRunner(stream=sio)
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1229
        test = LogTester('test_skipped')
1230
        result = self.run_test_runner(runner, test)
1231
1232
        self.assertLogDeleted(test)
1233
1234
    def test_not_aplicable_log_deleted(self):
1235
        """Not applicable tests have their log deleted"""
1236
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1237
        class LogTester(tests.TestCase):
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1238
1239
            def test_not_applicable(self):
1240
                self.log('this will be removed\n')
1241
                raise tests.TestNotApplicable()
1242
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1243
        sio = StringIO()
1244
        runner = tests.TextTestRunner(stream=sio)
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1245
        test = LogTester('test_not_applicable')
1246
        result = self.run_test_runner(runner, test)
1247
1248
        self.assertLogDeleted(test)
1249
1250
    def test_known_failure_log_deleted(self):
1251
        """Know failure tests have their log deleted"""
1252
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1253
        class LogTester(tests.TestCase):
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1254
1255
            def test_known_failure(self):
1256
                self.log('this will be removed\n')
1257
                raise tests.KnownFailure()
1258
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1259
        sio = StringIO()
1260
        runner = tests.TextTestRunner(stream=sio)
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1261
        test = LogTester('test_known_failure')
1262
        result = self.run_test_runner(runner, test)
1263
1264
        self.assertLogDeleted(test)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1265
1266
    def test_fail_log_kept(self):
1267
        """Failed tests have their log kept"""
1268
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1269
        class LogTester(tests.TestCase):
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1270
1271
            def test_fail(self):
1272
                self.log('this will be kept\n')
1273
                self.fail('this test fails')
1274
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1275
        sio = StringIO()
1276
        runner = tests.TextTestRunner(stream=sio)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1277
        test = LogTester('test_fail')
1278
        result = self.run_test_runner(runner, test)
1279
1280
        text = sio.getvalue()
1281
        self.assertContainsRe(text, 'this will be kept')
1282
        self.assertContainsRe(text, 'this test fails')
1283
1284
        log = test._get_log()
1285
        self.assertContainsRe(log, 'this will be kept')
1286
        self.assertEqual(log, test._log_contents)
1287
1288
    def test_error_log_kept(self):
1289
        """Tests with errors have their log kept"""
1290
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1291
        class LogTester(tests.TestCase):
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1292
1293
            def test_error(self):
1294
                self.log('this will be kept\n')
1295
                raise ValueError('random exception raised')
1296
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1297
        sio = StringIO()
1298
        runner = tests.TextTestRunner(stream=sio)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1299
        test = LogTester('test_error')
1300
        result = self.run_test_runner(runner, test)
1301
1302
        text = sio.getvalue()
1303
        self.assertContainsRe(text, 'this will be kept')
1304
        self.assertContainsRe(text, 'random exception raised')
1305
1306
        log = test._get_log()
1307
        self.assertContainsRe(log, 'this will be kept')
1308
        self.assertEqual(log, test._log_contents)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1309
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
1310
    def test_startTestRun(self):
1311
        """run should call result.startTestRun()"""
1312
        calls = []
1313
        class LoggingDecorator(tests.ForwardingResult):
1314
            def startTestRun(self):
1315
                tests.ForwardingResult.startTestRun(self)
1316
                calls.append('startTestRun')
1317
        test = unittest.FunctionTestCase(lambda:None)
1318
        stream = StringIO()
1319
        runner = tests.TextTestRunner(stream=stream,
1320
            result_decorators=[LoggingDecorator])
1321
        result = self.run_test_runner(runner, test)
1322
        self.assertLength(1, calls)
1323
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1324
    def test_stopTestRun(self):
1325
        """run should call result.stopTestRun()"""
1326
        calls = []
1327
        class LoggingDecorator(tests.ForwardingResult):
1328
            def stopTestRun(self):
1329
                tests.ForwardingResult.stopTestRun(self)
1330
                calls.append('stopTestRun')
1331
        test = unittest.FunctionTestCase(lambda:None)
1332
        stream = StringIO()
1333
        runner = tests.TextTestRunner(stream=stream,
1334
            result_decorators=[LoggingDecorator])
1335
        result = self.run_test_runner(runner, test)
1336
        self.assertLength(1, calls)
1337
2036.1.2 by John Arbash Meinel
whitespace fix
1338
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1339
class SampleTestCase(tests.TestCase):
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1340
1341
    def _test_pass(self):
1342
        pass
1343
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1344
class _TestException(Exception):
1345
    pass
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1346
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1347
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1348
class TestTestCase(tests.TestCase):
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1349
    """Tests that test the core bzrlib TestCase."""
1350
4144.1.1 by Robert Collins
New assertLength method based on one Martin has squirreled away somewhere.
1351
    def test_assertLength_matches_empty(self):
1352
        a_list = []
1353
        self.assertLength(0, a_list)
1354
1355
    def test_assertLength_matches_nonempty(self):
1356
        a_list = [1, 2, 3]
1357
        self.assertLength(3, a_list)
1358
1359
    def test_assertLength_fails_different(self):
1360
        a_list = []
1361
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1362
1363
    def test_assertLength_shows_sequence_in_failure(self):
1364
        a_list = [1, 2, 3]
1365
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
1366
            a_list)
1367
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1368
            exception.args[0])
1369
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1370
    def test_base_setUp_not_called_causes_failure(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1371
        class TestCaseWithBrokenSetUp(tests.TestCase):
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1372
            def setUp(self):
1373
                pass # does not call TestCase.setUp
1374
            def test_foo(self):
1375
                pass
1376
        test = TestCaseWithBrokenSetUp('test_foo')
1377
        result = unittest.TestResult()
1378
        test.run(result)
1379
        self.assertFalse(result.wasSuccessful())
4153.1.5 by Andrew Bennetts
Tweak assertions based on Robert's review.
1380
        self.assertEqual(1, result.testsRun)
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1381
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1382
    def test_base_tearDown_not_called_causes_failure(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1383
        class TestCaseWithBrokenTearDown(tests.TestCase):
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1384
            def tearDown(self):
1385
                pass # does not call TestCase.tearDown
1386
            def test_foo(self):
1387
                pass
1388
        test = TestCaseWithBrokenTearDown('test_foo')
1389
        result = unittest.TestResult()
1390
        test.run(result)
1391
        self.assertFalse(result.wasSuccessful())
4153.1.5 by Andrew Bennetts
Tweak assertions based on Robert's review.
1392
        self.assertEqual(1, result.testsRun)
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1393
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1394
    def test_debug_flags_sanitised(self):
1395
        """The bzrlib debug flags should be sanitised by setUp."""
3731.3.1 by Andrew Bennetts
Make the test suite pass when -Eallow_debug is used.
1396
        if 'allow_debug' in tests.selftest_debug_flags:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1397
            raise tests.TestNotApplicable(
3731.3.2 by Andrew Bennetts
Fix typo.
1398
                '-Eallow_debug option prevents debug flag sanitisation')
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1399
        # we could set something and run a test that will check
1400
        # it gets santised, but this is probably sufficient for now:
1401
        # if someone runs the test with -Dsomething it will error.
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1402
        flags = set()
1403
        if self._lock_check_thorough:
1404
            flags.add('strict_locks')
1405
        self.assertEqual(flags, bzrlib.debug.debug_flags)
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1406
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1407
    def change_selftest_debug_flags(self, new_flags):
1408
        orig_selftest_flags = tests.selftest_debug_flags
1409
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1410
        tests.selftest_debug_flags = set(new_flags)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1411
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1412
    def _restore_selftest_debug_flags(self, flags):
1413
        tests.selftest_debug_flags = flags
1414
1415
    def test_allow_debug_flag(self):
1416
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1417
        sanitised (i.e. cleared) before running a test.
1418
        """
1419
        self.change_selftest_debug_flags(set(['allow_debug']))
1420
        bzrlib.debug.debug_flags = set(['a-flag'])
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1421
        class TestThatRecordsFlags(tests.TestCase):
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1422
            def test_foo(nested_self):
1423
                self.flags = set(bzrlib.debug.debug_flags)
1424
        test = TestThatRecordsFlags('test_foo')
1425
        test.run(self.make_test_result())
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1426
        flags = set(['a-flag'])
1427
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
1428
            flags.add('strict_locks')
1429
        self.assertEqual(flags, self.flags)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1430
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1431
    def test_disable_lock_checks(self):
1432
        """The -Edisable_lock_checks flag disables thorough checks."""
1433
        class TestThatRecordsFlags(tests.TestCase):
1434
            def test_foo(nested_self):
1435
                self.flags = set(bzrlib.debug.debug_flags)
1436
                self.test_lock_check_thorough = nested_self._lock_check_thorough
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1437
        self.change_selftest_debug_flags(set())
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1438
        test = TestThatRecordsFlags('test_foo')
1439
        test.run(self.make_test_result())
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1440
        # By default we do strict lock checking and thorough lock/unlock
1441
        # tracking.
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1442
        self.assertTrue(self.test_lock_check_thorough)
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1443
        self.assertEqual(set(['strict_locks']), self.flags)
1444
        # Now set the disable_lock_checks flag, and show that this changed.
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1445
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
1446
        test = TestThatRecordsFlags('test_foo')
1447
        test.run(self.make_test_result())
1448
        self.assertFalse(self.test_lock_check_thorough)
1449
        self.assertEqual(set(), self.flags)
1450
4523.4.13 by John Arbash Meinel
Add a test that thisFailsStrictLockCheck() does the right thing.
1451
    def test_this_fails_strict_lock_check(self):
1452
        class TestThatRecordsFlags(tests.TestCase):
1453
            def test_foo(nested_self):
1454
                self.flags1 = set(bzrlib.debug.debug_flags)
1455
                self.thisFailsStrictLockCheck()
1456
                self.flags2 = set(bzrlib.debug.debug_flags)
1457
        # Make sure lock checking is active
1458
        self.change_selftest_debug_flags(set())
1459
        test = TestThatRecordsFlags('test_foo')
1460
        test.run(self.make_test_result())
1461
        self.assertEqual(set(['strict_locks']), self.flags1)
1462
        self.assertEqual(set(), self.flags2)
1463
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1464
    def test_debug_flags_restored(self):
1465
        """The bzrlib debug flags should be restored to their original state
1466
        after the test was run, even if allow_debug is set.
1467
        """
1468
        self.change_selftest_debug_flags(set(['allow_debug']))
1469
        # Now run a test that modifies debug.debug_flags.
1470
        bzrlib.debug.debug_flags = set(['original-state'])
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1471
        class TestThatModifiesFlags(tests.TestCase):
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1472
            def test_foo(self):
1473
                bzrlib.debug.debug_flags = set(['modified'])
1474
        test = TestThatModifiesFlags('test_foo')
1475
        test.run(self.make_test_result())
1476
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1477
1478
    def make_test_result(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1479
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1480
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1481
    def inner_test(self):
1482
        # the inner child test
1483
        note("inner_test")
1484
1485
    def outer_child(self):
1486
        # the outer child test
1487
        note("outer_start")
1488
        self.inner_test = TestTestCase("inner_child")
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1489
        result = self.make_test_result()
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1490
        self.inner_test.run(result)
1491
        note("outer finish")
1492
1493
    def test_trace_nesting(self):
1494
        # this tests that each test case nests its trace facility correctly.
1495
        # we do this by running a test case manually. That test case (A)
1496
        # should setup a new log, log content to it, setup a child case (B),
1497
        # which should log independently, then case (A) should log a trailer
1498
        # and return.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1499
        # we do two nested children so that we can verify the state of the
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1500
        # logs after the outer child finishes is correct, which a bad clean
1501
        # up routine in tearDown might trigger a fault in our test with only
1502
        # one child, we should instead see the bad result inside our test with
1503
        # the two children.
1504
        # the outer child test
1505
        original_trace = bzrlib.trace._trace_file
1506
        outer_test = TestTestCase("outer_child")
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1507
        result = self.make_test_result()
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1508
        outer_test.run(result)
4659.2.5 by Vincent Ladeuil
Fixed as per Andrew's review.
1509
        self.addCleanup(osutils.delete_any, outer_test._log_file_name)
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1510
        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)
1511
1512
    def method_that_times_a_bit_twice(self):
1513
        # 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.
1514
        self.time(time.sleep, 0.007)
1515
        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)
1516
1517
    def test_time_creates_benchmark_in_result(self):
1518
        """Test that the TestCase.time() method accumulates a benchmark time."""
1519
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1520
        output_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
1521
        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)
1522
            unittest._WritelnDecorator(output_stream),
1523
            descriptions=0,
4573.2.2 by Robert Collins
Fix selftest for TestResult progress changes.
1524
            verbosity=2)
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)
1525
        sample_test.run(result)
1526
        self.assertContainsRe(
1527
            output_stream.getvalue(),
4536.5.5 by Martin Pool
More selftest display test tweaks
1528
            r"\d+ms\*\n$")
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1529
1530
    def test_hooks_sanitised(self):
1531
        """The bzrlib hooks should be sanitised by setUp."""
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
1532
        # Note this test won't fail with hooks that the core library doesn't
1533
        # use - but it trigger with a plugin that adds hooks, so its still a
1534
        # useful warning in that case.
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.
1535
        self.assertEqual(bzrlib.branch.BranchHooks(),
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1536
            bzrlib.branch.Branch.hooks)
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
1537
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1538
            bzrlib.smart.server.SmartTCPServer.hooks)
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
1539
        self.assertEqual(bzrlib.commands.CommandHooks(),
1540
            bzrlib.commands.Command.hooks)
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1541
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1542
    def test__gather_lsprof_in_benchmarks(self):
1543
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1544
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1545
        Each self.time() call is individually and separately profiled.
1546
        """
1551.15.28 by Aaron Bentley
Improve Feature usage style w/ lsprof
1547
        self.requireFeature(test_lsprof.LSProfFeature)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1548
        # overrides the class member with an instance member so no cleanup
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1549
        # needed.
1550
        self._gather_lsprof_in_benchmarks = True
1551
        self.time(time.sleep, 0.000)
1552
        self.time(time.sleep, 0.003)
1553
        self.assertEqual(2, len(self._benchcalls))
1554
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1555
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1556
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1557
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
4641.3.1 by Robert Collins
Squelch test noise on test__gather_lsprof_in_benchmarks verbose mode.
1558
        del self._benchcalls[:]
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1559
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1560
    def test_knownFailure(self):
1561
        """Self.knownFailure() should raise a KnownFailure exception."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1562
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1563
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
1564
    def test_open_bzrdir_safe_roots(self):
1565
        # even a memory transport should fail to open when its url isn't 
1566
        # permitted.
1567
        # Manually set one up (TestCase doesn't and shouldn't provide magic
1568
        # machinery)
1569
        transport_server = MemoryServer()
1570
        transport_server.setUp()
1571
        self.addCleanup(transport_server.tearDown)
1572
        t = transport.get_transport(transport_server.get_url())
1573
        bzrdir.BzrDir.create(t.base)
1574
        self.assertRaises(errors.BzrError,
1575
            bzrdir.BzrDir.open_from_transport, t)
1576
        # But if we declare this as safe, we can open the bzrdir.
1577
        self.permit_url(t.base)
1578
        self._bzr_selftest_roots.append(t.base)
1579
        bzrdir.BzrDir.open_from_transport(t)
1580
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1581
    def test_requireFeature_available(self):
1582
        """self.requireFeature(available) is a no-op."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1583
        class Available(tests.Feature):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1584
            def _probe(self):return True
1585
        feature = Available()
1586
        self.requireFeature(feature)
1587
1588
    def test_requireFeature_unavailable(self):
1589
        """self.requireFeature(unavailable) raises UnavailableFeature."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1590
        class Unavailable(tests.Feature):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1591
            def _probe(self):return False
1592
        feature = Unavailable()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1593
        self.assertRaises(tests.UnavailableFeature,
1594
                          self.requireFeature, feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1595
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1596
    def test_run_no_parameters(self):
1597
        test = SampleTestCase('_test_pass')
1598
        test.run()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1599
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1600
    def test_run_enabled_unittest_result(self):
1601
        """Test we revert to regular behaviour when the test is enabled."""
1602
        test = SampleTestCase('_test_pass')
1603
        class EnabledFeature(object):
1604
            def available(self):
1605
                return True
1606
        test._test_needs_features = [EnabledFeature()]
1607
        result = unittest.TestResult()
1608
        test.run(result)
1609
        self.assertEqual(1, result.testsRun)
1610
        self.assertEqual([], result.errors)
1611
        self.assertEqual([], result.failures)
1612
1613
    def test_run_disabled_unittest_result(self):
1614
        """Test our compatability for disabled tests with unittest results."""
1615
        test = SampleTestCase('_test_pass')
1616
        class DisabledFeature(object):
1617
            def available(self):
1618
                return False
1619
        test._test_needs_features = [DisabledFeature()]
1620
        result = unittest.TestResult()
1621
        test.run(result)
1622
        self.assertEqual(1, result.testsRun)
1623
        self.assertEqual([], result.errors)
1624
        self.assertEqual([], result.failures)
1625
1626
    def test_run_disabled_supporting_result(self):
1627
        """Test disabled tests behaviour with support aware results."""
1628
        test = SampleTestCase('_test_pass')
1629
        class DisabledFeature(object):
1630
            def available(self):
1631
                return False
1632
        the_feature = DisabledFeature()
1633
        test._test_needs_features = [the_feature]
1634
        class InstrumentedTestResult(unittest.TestResult):
1635
            def __init__(self):
1636
                unittest.TestResult.__init__(self)
1637
                self.calls = []
1638
            def startTest(self, test):
1639
                self.calls.append(('startTest', test))
1640
            def stopTest(self, test):
1641
                self.calls.append(('stopTest', test))
1642
            def addNotSupported(self, test, feature):
1643
                self.calls.append(('addNotSupported', test, feature))
1644
        result = InstrumentedTestResult()
1645
        test.run(result)
1646
        self.assertEqual([
1647
            ('startTest', test),
1648
            ('addNotSupported', test, the_feature),
1649
            ('stopTest', test),
1650
            ],
1651
            result.calls)
1652
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
1653
    def test_start_server_registers_url(self):
1654
        transport_server = MemoryServer()
1655
        # A little strict, but unlikely to be changed soon.
1656
        self.assertEqual([], self._bzr_selftest_roots)
1657
        self.start_server(transport_server)
1658
        self.assertSubset([transport_server.get_url()],
1659
            self._bzr_selftest_roots)
1660
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1661
    def test_assert_list_raises_on_generator(self):
1662
        def generator_which_will_raise():
1663
            # This will not raise until after the first yield
1664
            yield 1
1665
            raise _TestException()
1666
1667
        e = self.assertListRaises(_TestException, generator_which_will_raise)
1668
        self.assertIsInstance(e, _TestException)
1669
1670
        e = self.assertListRaises(Exception, generator_which_will_raise)
1671
        self.assertIsInstance(e, _TestException)
1672
1673
    def test_assert_list_raises_on_plain(self):
1674
        def plain_exception():
1675
            raise _TestException()
1676
            return []
1677
1678
        e = self.assertListRaises(_TestException, plain_exception)
1679
        self.assertIsInstance(e, _TestException)
1680
1681
        e = self.assertListRaises(Exception, plain_exception)
1682
        self.assertIsInstance(e, _TestException)
1683
1684
    def test_assert_list_raises_assert_wrong_exception(self):
1685
        class _NotTestException(Exception):
1686
            pass
1687
1688
        def wrong_exception():
1689
            raise _NotTestException()
1690
1691
        def wrong_exception_generator():
1692
            yield 1
1693
            yield 2
1694
            raise _NotTestException()
1695
1696
        # Wrong exceptions are not intercepted
1697
        self.assertRaises(_NotTestException,
1698
            self.assertListRaises, _TestException, wrong_exception)
1699
        self.assertRaises(_NotTestException,
1700
            self.assertListRaises, _TestException, wrong_exception_generator)
1701
1702
    def test_assert_list_raises_no_exception(self):
1703
        def success():
1704
            return []
1705
1706
        def success_generator():
1707
            yield 1
1708
            yield 2
1709
1710
        self.assertRaises(AssertionError,
1711
            self.assertListRaises, _TestException, success)
1712
1713
        self.assertRaises(AssertionError,
1714
            self.assertListRaises, _TestException, success_generator)
1715
1534.11.4 by Robert Collins
Merge from mainline.
1716
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1717
# NB: Don't delete this; it's not actually from 0.11!
1718
@deprecated_function(deprecated_in((0, 11, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1719
def sample_deprecated_function():
1720
    """A deprecated function to test applyDeprecated with."""
1721
    return 2
1722
1723
1724
def sample_undeprecated_function(a_param):
1725
    """A undeprecated function to test applyDeprecated with."""
1726
1727
1728
class ApplyDeprecatedHelper(object):
1729
    """A helper class for ApplyDeprecated tests."""
1730
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1731
    @deprecated_method(deprecated_in((0, 11, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1732
    def sample_deprecated_method(self, param_one):
1733
        """A deprecated method for testing with."""
1734
        return param_one
1735
1736
    def sample_normal_method(self):
1737
        """A undeprecated method."""
1738
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1739
    @deprecated_method(deprecated_in((0, 10, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1740
    def sample_nested_deprecation(self):
1741
        return sample_deprecated_function()
1742
1743
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1744
class TestExtraAssertions(tests.TestCase):
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1745
    """Tests for new test assertions in bzrlib test suite"""
1746
1747
    def test_assert_isinstance(self):
1748
        self.assertIsInstance(2, int)
1749
        self.assertIsInstance(u'', basestring)
4449.3.43 by Martin Pool
More tests for assertIsInstance
1750
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1751
        self.assertEquals(str(e),
1752
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1753
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
4449.3.43 by Martin Pool
More tests for assertIsInstance
1754
        e = self.assertRaises(AssertionError,
1755
            self.assertIsInstance, None, int, "it's just not")
1756
        self.assertEquals(str(e),
1757
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
1758
            ": it's just not")
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1759
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
1760
    def test_assertEndsWith(self):
1761
        self.assertEndsWith('foo', 'oo')
1762
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1763
4680.1.1 by Vincent Ladeuil
Surprisingly, assertEqualDiff was wrong.
1764
    def test_assertEqualDiff(self):
1765
        e = self.assertRaises(AssertionError,
1766
                              self.assertEqualDiff, '', '\n')
1767
        self.assertEquals(str(e),
1768
                          # Don't blink ! The '+' applies to the second string
1769
                          'first string is missing a final newline.\n+ \n')
1770
        e = self.assertRaises(AssertionError,
1771
                              self.assertEqualDiff, '\n', '')
1772
        self.assertEquals(str(e),
1773
                          # Don't blink ! The '-' applies to the second string
1774
                          'second string is missing a final newline.\n- \n')
1775
1776
1777
class TestDeprecations(tests.TestCase):
1778
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1779
    def test_applyDeprecated_not_deprecated(self):
1780
        sample_object = ApplyDeprecatedHelper()
1781
        # calling an undeprecated callable raises an assertion
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1782
        self.assertRaises(AssertionError, self.applyDeprecated,
1783
            deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1784
            sample_object.sample_normal_method)
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1785
        self.assertRaises(AssertionError, self.applyDeprecated,
1786
            deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1787
            sample_undeprecated_function, "a param value")
1788
        # calling a deprecated callable (function or method) with the wrong
1789
        # expected deprecation fails.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1790
        self.assertRaises(AssertionError, self.applyDeprecated,
1791
            deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1792
            sample_object.sample_deprecated_method, "a param value")
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1793
        self.assertRaises(AssertionError, self.applyDeprecated,
1794
            deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1795
            sample_deprecated_function)
1796
        # calling a deprecated callable (function or method) with the right
1797
        # expected deprecation returns the functions result.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1798
        self.assertEqual("a param value",
1799
            self.applyDeprecated(deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1800
            sample_object.sample_deprecated_method, "a param value"))
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1801
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1802
            sample_deprecated_function))
1803
        # calling a nested deprecation with the wrong deprecation version
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1804
        # fails even if a deeper nested function was deprecated with the
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1805
        # supplied version.
1806
        self.assertRaises(AssertionError, self.applyDeprecated,
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1807
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1808
        # calling a nested deprecation with the right deprecation value
1809
        # returns the calls result.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1810
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1811
            sample_object.sample_nested_deprecation))
1812
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1813
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1814
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1815
            if be_deprecated is True:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1816
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1817
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1818
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1819
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1820
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1821
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1822
        self.assertEqual('result', result)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1823
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1824
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1825
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1826
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1827
class TestWarningTests(tests.TestCase):
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1828
    """Tests for calling methods that raise warnings."""
1829
1830
    def test_callCatchWarnings(self):
1831
        def meth(a, b):
1832
            warnings.warn("this is your last warning")
1833
            return a + b
1834
        wlist, result = self.callCatchWarnings(meth, 1, 2)
1835
        self.assertEquals(3, result)
1836
        # would like just to compare them, but UserWarning doesn't implement
1837
        # eq well
1838
        w0, = wlist
1839
        self.assertIsInstance(w0, UserWarning)
2592.3.247 by Andrew Bennetts
Fix test_callCatchWarnings to pass when run with Python 2.4.
1840
        self.assertEquals("this is your last warning", str(w0))
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1841
1842
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1843
class TestConvenienceMakers(tests.TestCaseWithTransport):
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1844
    """Test for the make_* convenience functions."""
1845
1846
    def test_make_branch_and_tree_with_format(self):
1847
        # we should be able to supply a format to make_branch_and_tree
1848
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1849
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1850
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1851
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1852
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1853
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1854
1986.2.1 by Robert Collins
Bugfix - the name of the test for make_branch_and_memory_tree was wrong.
1855
    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
1856
        # we should be able to get a new branch and a mutable tree from
1857
        # TestCaseWithTransport
1858
        tree = self.make_branch_and_memory_tree('a')
1859
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1860
4650.1.2 by Robert Collins
Remove unnecessary use of an SFTP server connection to test the behaviour of TestCase.make_branch_and_tree.
1861
    def test_make_tree_for_local_vfs_backed_transport(self):
1862
        # make_branch_and_tree has to use local branch and repositories
1863
        # when the vfs transport and local disk are colocated, even if
1864
        # a different transport is in use for url generation.
1865
        from bzrlib.transport.fakevfat import FakeVFATServer
1866
        self.transport_server = FakeVFATServer
1867
        self.assertFalse(self.get_url('t1').startswith('file://'))
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
1868
        tree = self.make_branch_and_tree('t1')
1869
        base = tree.bzrdir.root_transport.base
4650.1.2 by Robert Collins
Remove unnecessary use of an SFTP server connection to test the behaviour of TestCase.make_branch_and_tree.
1870
        self.assertStartsWith(base, 'file://')
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
1871
        self.assertEquals(tree.bzrdir.root_transport,
1872
                tree.branch.bzrdir.root_transport)
1873
        self.assertEquals(tree.bzrdir.root_transport,
1874
                tree.branch.repository.bzrdir.root_transport)
1875
1876
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
1877
class SelfTestHelper:
1878
1879
    def run_selftest(self, **kwargs):
1880
        """Run selftest returning its output."""
1881
        output = StringIO()
1882
        old_transport = bzrlib.tests.default_transport
1883
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1884
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1885
        try:
1886
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1887
        finally:
1888
            bzrlib.tests.default_transport = old_transport
1889
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1890
        output.seek(0)
1891
        return output
1892
1893
1894
class TestSelftest(tests.TestCase, SelfTestHelper):
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1895
    """Tests of bzrlib.tests.selftest."""
1896
1897
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1898
        factory_called = []
1899
        def factory():
1900
            factory_called.append(True)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1901
            return TestUtil.TestSuite()
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1902
        out = StringIO()
1903
        err = StringIO()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1904
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1905
            test_suite_factory=factory)
1906
        self.assertEqual([True], factory_called)
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
1907
4636.2.1 by Robert Collins
Test selftest --list-only and --randomize options using more precisely layers.
1908
    def factory(self):
1909
        """A test suite factory."""
1910
        class Test(tests.TestCase):
1911
            def a(self):
1912
                pass
1913
            def b(self):
1914
                pass
1915
            def c(self):
1916
                pass
1917
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1918
1919
    def test_list_only(self):
1920
        output = self.run_selftest(test_suite_factory=self.factory,
1921
            list_only=True)
1922
        self.assertEqual(3, len(output.readlines()))
1923
1924
    def test_list_only_filtered(self):
1925
        output = self.run_selftest(test_suite_factory=self.factory,
1926
            list_only=True, pattern="Test.b")
1927
        self.assertEndsWith(output.getvalue(), "Test.b\n")
1928
        self.assertLength(1, output.readlines())
1929
1930
    def test_list_only_excludes(self):
1931
        output = self.run_selftest(test_suite_factory=self.factory,
1932
            list_only=True, exclude_pattern="Test.b")
1933
        self.assertNotContainsRe("Test.b", output.getvalue())
1934
        self.assertLength(2, output.readlines())
1935
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1936
    def test_lsprof_tests(self):
4641.3.5 by Robert Collins
Properly guard LSProf using tests.
1937
        self.requireFeature(test_lsprof.LSProfFeature)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1938
        calls = []
1939
        class Test(object):
1940
            def __call__(test, result):
1941
                test.run(result)
1942
            def run(test, result):
1943
                self.assertIsInstance(result, tests.ForwardingResult)
1944
                calls.append("called")
1945
            def countTestCases(self):
1946
                return 1
1947
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1948
        self.assertLength(1, calls)
1949
4636.2.1 by Robert Collins
Test selftest --list-only and --randomize options using more precisely layers.
1950
    def test_random(self):
1951
        # test randomising by listing a number of tests.
1952
        output_123 = self.run_selftest(test_suite_factory=self.factory,
1953
            list_only=True, random_seed="123")
1954
        output_234 = self.run_selftest(test_suite_factory=self.factory,
1955
            list_only=True, random_seed="234")
1956
        self.assertNotEqual(output_123, output_234)
1957
        # "Randominzing test order..\n\n
1958
        self.assertLength(5, output_123.readlines())
1959
        self.assertLength(5, output_234.readlines())
1960
1961
    def test_random_reuse_is_same_order(self):
1962
        # test randomising by listing a number of tests.
1963
        expected = self.run_selftest(test_suite_factory=self.factory,
1964
            list_only=True, random_seed="123")
1965
        repeated = self.run_selftest(test_suite_factory=self.factory,
1966
            list_only=True, random_seed="123")
1967
        self.assertEqual(expected.getvalue(), repeated.getvalue())
1968
4636.2.3 by Robert Collins
Layer tests for selftest --subunit better.
1969
    def test_runner_class(self):
1970
        self.requireFeature(SubUnitFeature)
1971
        from subunit import ProtocolTestCase
1972
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1973
            test_suite_factory=self.factory)
1974
        test = ProtocolTestCase(stream)
1975
        result = unittest.TestResult()
1976
        test.run(result)
1977
        self.assertEqual(3, result.testsRun)
1978
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
1979
    def test_starting_with_single_argument(self):
1980
        output = self.run_selftest(test_suite_factory=self.factory,
1981
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
1982
            list_only=True)
1983
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1984
            output.getvalue())
1985
1986
    def test_starting_with_multiple_argument(self):
1987
        output = self.run_selftest(test_suite_factory=self.factory,
1988
            starting_with=['bzrlib.tests.test_selftest.Test.a',
1989
                'bzrlib.tests.test_selftest.Test.b'],
1990
            list_only=True)
1991
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1992
            'bzrlib.tests.test_selftest.Test.b\n',
1993
            output.getvalue())
1994
4636.2.2 by Robert Collins
Fix selftest tests for --transport to test each layer precisely.
1995
    def check_transport_set(self, transport_server):
1996
        captured_transport = []
1997
        def seen_transport(a_transport):
1998
            captured_transport.append(a_transport)
1999
        class Capture(tests.TestCase):
2000
            def a(self):
2001
                seen_transport(bzrlib.tests.default_transport)
2002
        def factory():
2003
            return TestUtil.TestSuite([Capture("a")])
2004
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
2005
        self.assertEqual(transport_server, captured_transport[0])
2006
2007
    def test_transport_sftp(self):
2008
        try:
2009
            import bzrlib.transport.sftp
4645.2.1 by Vincent Ladeuil
Fix typo left after refactoring.
2010
        except errors.ParamikoNotPresent:
4645.2.2 by Vincent Ladeuil
One more import typo
2011
            raise tests.TestSkipped("Paramiko not present")
4636.2.2 by Robert Collins
Fix selftest tests for --transport to test each layer precisely.
2012
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
2013
2014
    def test_transport_memory(self):
2015
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
2016
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
2017
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2018
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2019
    # Does IO: reads test.list
2020
2021
    def test_load_list(self):
2022
        # Provide a list with one test - this test.
2023
        test_id_line = '%s\n' % self.id()
2024
        self.build_tree_contents([('test.list', test_id_line)])
2025
        # And generate a list of the tests in  the suite.
2026
        stream = self.run_selftest(load_list='test.list', list_only=True)
2027
        self.assertEqual(test_id_line, stream.getvalue())
2028
2029
    def test_load_unknown(self):
2030
        # Provide a list with one test - this test.
2031
        # And generate a list of the tests in  the suite.
2032
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
2033
            load_list='missing file name', list_only=True)
2034
2035
2036
class TestRunBzr(tests.TestCase):
2037
2038
    out = ''
2039
    err = ''
2040
2041
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2042
                         working_dir=None):
2043
        """Override _run_bzr_core to test how it is invoked by run_bzr.
2044
2045
        Attempts to run bzr from inside this class don't actually run it.
2046
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2047
        We test how run_bzr actually invokes bzr in another location.  Here we
2048
        only need to test that it passes the right parameters to run_bzr.
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2049
        """
2050
        self.argv = list(argv)
2051
        self.retcode = retcode
2052
        self.encoding = encoding
2053
        self.stdin = stdin
2054
        self.working_dir = working_dir
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2055
        return self.retcode, self.out, self.err
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2056
2057
    def test_run_bzr_error(self):
2058
        self.out = "It sure does!\n"
2059
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2060
        self.assertEqual(['rocks'], self.argv)
2061
        self.assertEqual(34, self.retcode)
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2062
        self.assertEqual('It sure does!\n', out)
2063
        self.assertEquals(out, self.out)
2064
        self.assertEqual('', err)
2065
        self.assertEquals(err, self.err)
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2066
2067
    def test_run_bzr_error_regexes(self):
2068
        self.out = ''
2069
        self.err = "bzr: ERROR: foobarbaz is not versioned"
2070
        out, err = self.run_bzr_error(
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2071
            ["bzr: ERROR: foobarbaz is not versioned"],
2072
            ['file-id', 'foobarbaz'])
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2073
2074
    def test_encoding(self):
2075
        """Test that run_bzr passes encoding to _run_bzr_core"""
2076
        self.run_bzr('foo bar')
2077
        self.assertEqual(None, self.encoding)
2078
        self.assertEqual(['foo', 'bar'], self.argv)
2079
2080
        self.run_bzr('foo bar', encoding='baz')
2081
        self.assertEqual('baz', self.encoding)
2082
        self.assertEqual(['foo', 'bar'], self.argv)
2083
2084
    def test_retcode(self):
2085
        """Test that run_bzr passes retcode to _run_bzr_core"""
2086
        # Default is retcode == 0
2087
        self.run_bzr('foo bar')
2088
        self.assertEqual(0, self.retcode)
2089
        self.assertEqual(['foo', 'bar'], self.argv)
2090
2091
        self.run_bzr('foo bar', retcode=1)
2092
        self.assertEqual(1, self.retcode)
2093
        self.assertEqual(['foo', 'bar'], self.argv)
2094
2095
        self.run_bzr('foo bar', retcode=None)
2096
        self.assertEqual(None, self.retcode)
2097
        self.assertEqual(['foo', 'bar'], self.argv)
2098
2099
        self.run_bzr(['foo', 'bar'], retcode=3)
2100
        self.assertEqual(3, self.retcode)
2101
        self.assertEqual(['foo', 'bar'], self.argv)
2102
2103
    def test_stdin(self):
2104
        # test that the stdin keyword to run_bzr is passed through to
2105
        # _run_bzr_core as-is. We do this by overriding
2106
        # _run_bzr_core in this class, and then calling run_bzr,
2107
        # which is a convenience function for _run_bzr_core, so
2108
        # should invoke it.
2109
        self.run_bzr('foo bar', stdin='gam')
2110
        self.assertEqual('gam', self.stdin)
2111
        self.assertEqual(['foo', 'bar'], self.argv)
2112
2113
        self.run_bzr('foo bar', stdin='zippy')
2114
        self.assertEqual('zippy', self.stdin)
2115
        self.assertEqual(['foo', 'bar'], self.argv)
2116
2117
    def test_working_dir(self):
2118
        """Test that run_bzr passes working_dir to _run_bzr_core"""
2119
        self.run_bzr('foo bar')
2120
        self.assertEqual(None, self.working_dir)
2121
        self.assertEqual(['foo', 'bar'], self.argv)
2122
2123
        self.run_bzr('foo bar', working_dir='baz')
2124
        self.assertEqual('baz', self.working_dir)
2125
        self.assertEqual(['foo', 'bar'], self.argv)
2126
2127
    def test_reject_extra_keyword_arguments(self):
2128
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
2129
                          error_regex=['error message'])
2130
2131
2132
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2133
    # Does IO when testing the working_dir parameter.
2134
2135
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2136
                         a_callable=None, *args, **kwargs):
2137
        self.stdin = stdin
2138
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2139
        self.factory = bzrlib.ui.ui_factory
2140
        self.working_dir = osutils.getcwd()
2141
        stdout.write('foo\n')
2142
        stderr.write('bar\n')
2143
        return 0
2144
2145
    def test_stdin(self):
2146
        # test that the stdin keyword to _run_bzr_core is passed through to
2147
        # apply_redirected as a StringIO. We do this by overriding
2148
        # apply_redirected in this class, and then calling _run_bzr_core,
2149
        # which calls apply_redirected.
2150
        self.run_bzr(['foo', 'bar'], stdin='gam')
2151
        self.assertEqual('gam', self.stdin.read())
2152
        self.assertTrue(self.stdin is self.factory_stdin)
2153
        self.run_bzr(['foo', 'bar'], stdin='zippy')
2154
        self.assertEqual('zippy', self.stdin.read())
2155
        self.assertTrue(self.stdin is self.factory_stdin)
2156
2157
    def test_ui_factory(self):
2158
        # each invocation of self.run_bzr should get its
2159
        # own UI factory, which is an instance of TestUIFactory,
2160
        # with stdin, stdout and stderr attached to the stdin,
2161
        # stdout and stderr of the invoked run_bzr
2162
        current_factory = bzrlib.ui.ui_factory
2163
        self.run_bzr(['foo'])
2164
        self.failIf(current_factory is self.factory)
2165
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2166
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2167
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2168
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
2169
        self.assertIsInstance(self.factory, tests.TestUIFactory)
2170
2171
    def test_working_dir(self):
2172
        self.build_tree(['one/', 'two/'])
2173
        cwd = osutils.getcwd()
2174
2175
        # Default is to work in the current directory
2176
        self.run_bzr(['foo', 'bar'])
2177
        self.assertEqual(cwd, self.working_dir)
2178
2179
        self.run_bzr(['foo', 'bar'], working_dir=None)
2180
        self.assertEqual(cwd, self.working_dir)
2181
2182
        # The function should be run in the alternative directory
2183
        # but afterwards the current working dir shouldn't be changed
2184
        self.run_bzr(['foo', 'bar'], working_dir='one')
2185
        self.assertNotEqual(cwd, self.working_dir)
2186
        self.assertEndsWith(self.working_dir, 'one')
2187
        self.assertEqual(cwd, osutils.getcwd())
2188
2189
        self.run_bzr(['foo', 'bar'], working_dir='two')
2190
        self.assertNotEqual(cwd, self.working_dir)
2191
        self.assertEndsWith(self.working_dir, 'two')
2192
        self.assertEqual(cwd, osutils.getcwd())
2193
2194
2195
class StubProcess(object):
2196
    """A stub process for testing run_bzr_subprocess."""
2197
    
2198
    def __init__(self, out="", err="", retcode=0):
2199
        self.out = out
2200
        self.err = err
2201
        self.returncode = retcode
2202
2203
    def communicate(self):
2204
        return self.out, self.err
2205
2206
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2207
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2208
    """Base class for tests testing how we might run bzr."""
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2209
2210
    def setUp(self):
2211
        tests.TestCaseWithTransport.setUp(self)
2212
        self.subprocess_calls = []
2213
2214
    def start_bzr_subprocess(self, process_args, env_changes=None,
2215
                             skip_if_plan_to_signal=False,
2216
                             working_dir=None,
2217
                             allow_plugins=False):
2218
        """capture what run_bzr_subprocess tries to do."""
2219
        self.subprocess_calls.append({'process_args':process_args,
2220
            'env_changes':env_changes,
2221
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
2222
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
2223
        return self.next_subprocess
2224
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2225
2226
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2227
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2228
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2229
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
2230
2231
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2232
        that will return static results. This assertion method populates those
2233
        results and also checks the arguments run_bzr_subprocess generates.
2234
        """
2235
        self.next_subprocess = process
2236
        try:
2237
            result = self.run_bzr_subprocess(*args, **kwargs)
2238
        except:
2239
            self.next_subprocess = None
2240
            for key, expected in expected_args.iteritems():
2241
                self.assertEqual(expected, self.subprocess_calls[-1][key])
2242
            raise
2243
        else:
2244
            self.next_subprocess = None
2245
            for key, expected in expected_args.iteritems():
2246
                self.assertEqual(expected, self.subprocess_calls[-1][key])
2247
            return result
2248
2249
    def test_run_bzr_subprocess(self):
2250
        """The run_bzr_helper_external command behaves nicely."""
2251
        self.assertRunBzrSubprocess({'process_args':['--version']},
2252
            StubProcess(), '--version')
2253
        self.assertRunBzrSubprocess({'process_args':['--version']},
2254
            StubProcess(), ['--version'])
2255
        # retcode=None disables retcode checking
2256
        result = self.assertRunBzrSubprocess({},
2257
            StubProcess(retcode=3), '--version', retcode=None)
2258
        result = self.assertRunBzrSubprocess({},
2259
            StubProcess(out="is free software"), '--version')
2260
        self.assertContainsRe(result[0], 'is free software')
2261
        # Running a subcommand that is missing errors
2262
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2263
            {'process_args':['--versionn']}, StubProcess(retcode=3),
2264
            '--versionn')
2265
        # Unless it is told to expect the error from the subprocess
2266
        result = self.assertRunBzrSubprocess({},
2267
            StubProcess(retcode=3), '--versionn', retcode=3)
2268
        # Or to ignore retcode checking
2269
        result = self.assertRunBzrSubprocess({},
2270
            StubProcess(err="unknown command", retcode=3), '--versionn',
2271
            retcode=None)
2272
        self.assertContainsRe(result[1], 'unknown command')
2273
2274
    def test_env_change_passes_through(self):
2275
        self.assertRunBzrSubprocess(
2276
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2277
            StubProcess(), '',
2278
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2279
2280
    def test_no_working_dir_passed_as_None(self):
2281
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2282
2283
    def test_no_working_dir_passed_through(self):
2284
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2285
            working_dir='dir')
2286
2287
    def test_run_bzr_subprocess_no_plugins(self):
2288
        self.assertRunBzrSubprocess({'allow_plugins': False},
2289
            StubProcess(), '')
2290
2291
    def test_allow_plugins(self):
2292
        self.assertRunBzrSubprocess({'allow_plugins': True},
2293
            StubProcess(), '', allow_plugins=True)
2294
2295
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2296
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2297
2298
    def test_finish_bzr_subprocess_with_error(self):
2299
        """finish_bzr_subprocess allows specification of the desired exit code.
2300
        """
2301
        process = StubProcess(err="unknown command", retcode=3)
2302
        result = self.finish_bzr_subprocess(process, retcode=3)
2303
        self.assertEqual('', result[0])
2304
        self.assertContainsRe(result[1], 'unknown command')
2305
2306
    def test_finish_bzr_subprocess_ignoring_retcode(self):
2307
        """finish_bzr_subprocess allows the exit code to be ignored."""
2308
        process = StubProcess(err="unknown command", retcode=3)
2309
        result = self.finish_bzr_subprocess(process, retcode=None)
2310
        self.assertEqual('', result[0])
2311
        self.assertContainsRe(result[1], 'unknown command')
2312
2313
    def test_finish_subprocess_with_unexpected_retcode(self):
2314
        """finish_bzr_subprocess raises self.failureException if the retcode is
2315
        not the expected one.
2316
        """
2317
        process = StubProcess(err="unknown command", retcode=3)
2318
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2319
                          process)
2320
2321
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2322
class _DontSpawnProcess(Exception):
2323
    """A simple exception which just allows us to skip unnecessary steps"""
2324
2325
2326
class TestStartBzrSubProcess(tests.TestCase):
2327
2328
    def check_popen_state(self):
2329
        """Replace to make assertions when popen is called."""
2330
2331
    def _popen(self, *args, **kwargs):
2332
        """Record the command that is run, so that we can ensure it is correct"""
2333
        self.check_popen_state()
2334
        self._popen_args = args
2335
        self._popen_kwargs = kwargs
2336
        raise _DontSpawnProcess()
2337
2338
    def test_run_bzr_subprocess_no_plugins(self):
2339
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2340
        command = self._popen_args[0]
2341
        self.assertEqual(sys.executable, command[0])
2342
        self.assertEqual(self.get_bzr_path(), command[1])
2343
        self.assertEqual(['--no-plugins'], command[2:])
2344
2345
    def test_allow_plugins(self):
2346
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2347
            allow_plugins=True)
2348
        command = self._popen_args[0]
2349
        self.assertEqual([], command[2:])
2350
2351
    def test_set_env(self):
2352
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2353
        # set in the child
2354
        def check_environment():
2355
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2356
        self.check_popen_state = check_environment
2357
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2358
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
2359
        # not set in theparent
2360
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2361
2362
    def test_run_bzr_subprocess_env_del(self):
2363
        """run_bzr_subprocess can remove environment variables too."""
2364
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
2365
        def check_environment():
2366
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2367
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2368
        self.check_popen_state = check_environment
2369
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2370
            env_changes={'EXISTANT_ENV_VAR':None})
2371
        # Still set in parent
2372
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2373
        del os.environ['EXISTANT_ENV_VAR']
2374
2375
    def test_env_del_missing(self):
2376
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2377
        def check_environment():
2378
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2379
        self.check_popen_state = check_environment
2380
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2381
            env_changes={'NON_EXISTANT_ENV_VAR':None})
2382
2383
    def test_working_dir(self):
2384
        """Test that we can specify the working dir for the child"""
2385
        orig_getcwd = osutils.getcwd
2386
        orig_chdir = os.chdir
2387
        chdirs = []
2388
        def chdir(path):
2389
            chdirs.append(path)
2390
        os.chdir = chdir
2391
        try:
2392
            def getcwd():
2393
                return 'current'
2394
            osutils.getcwd = getcwd
2395
            try:
2396
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2397
                    working_dir='foo')
2398
            finally:
2399
                osutils.getcwd = orig_getcwd
2400
        finally:
2401
            os.chdir = orig_chdir
2402
        self.assertEqual(['foo', 'current'], chdirs)
2403
2404
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2405
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2406
    """Tests that really need to do things with an external bzr."""
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2407
2408
    def test_start_and_stop_bzr_subprocess_send_signal(self):
2409
        """finish_bzr_subprocess raises self.failureException if the retcode is
2410
        not the expected one.
2411
        """
4695.3.2 by Vincent Ladeuil
Simplified and claried as per Robert's review.
2412
        self.disable_missing_extensions_warning()
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2413
        process = self.start_bzr_subprocess(['wait-until-signalled'],
2414
                                            skip_if_plan_to_signal=True)
2415
        self.assertEqual('running\n', process.stdout.readline())
2416
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2417
                                            retcode=3)
2418
        self.assertEqual('', result[0])
2419
        self.assertEqual('bzr: interrupted\n', result[1])
2420
2421
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2422
class TestKnownFailure(tests.TestCase):
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
2423
2424
    def test_known_failure(self):
2425
        """Check that KnownFailure is defined appropriately."""
2426
        # a KnownFailure is an assertion error for compatability with unaware
2427
        # runners.
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2428
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2429
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
2430
    def test_expect_failure(self):
2431
        try:
2432
            self.expectFailure("Doomed to failure", self.assertTrue, False)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2433
        except tests.KnownFailure, e:
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
2434
            self.assertEqual('Doomed to failure', e.args[0])
2435
        try:
2436
            self.expectFailure("Doomed to failure", self.assertTrue, True)
2437
        except AssertionError, e:
2438
            self.assertEqual('Unexpected success.  Should have failed:'
2439
                             ' Doomed to failure', e.args[0])
2440
        else:
2441
            self.fail('Assertion not raised')
2442
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2443
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2444
class TestFeature(tests.TestCase):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2445
2446
    def test_caching(self):
2447
        """Feature._probe is called by the feature at most once."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2448
        class InstrumentedFeature(tests.Feature):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2449
            def __init__(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2450
                super(InstrumentedFeature, self).__init__()
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2451
                self.calls = []
2452
            def _probe(self):
2453
                self.calls.append('_probe')
2454
                return False
2455
        feature = InstrumentedFeature()
2456
        feature.available()
2457
        self.assertEqual(['_probe'], feature.calls)
2458
        feature.available()
2459
        self.assertEqual(['_probe'], feature.calls)
2460
2461
    def test_named_str(self):
2462
        """Feature.__str__ should thunk to feature_name()."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2463
        class NamedFeature(tests.Feature):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2464
            def feature_name(self):
2465
                return 'symlinks'
2466
        feature = NamedFeature()
2467
        self.assertEqual('symlinks', str(feature))
2468
2469
    def test_default_str(self):
2470
        """Feature.__str__ should default to __class__.__name__."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2471
        class NamedFeature(tests.Feature):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2472
            pass
2473
        feature = NamedFeature()
2474
        self.assertEqual('NamedFeature', str(feature))
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
2475
2476
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2477
class TestUnavailableFeature(tests.TestCase):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
2478
2479
    def test_access_feature(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2480
        feature = tests.Feature()
2481
        exception = tests.UnavailableFeature(feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
2482
        self.assertIs(feature, exception.args[0])
2394.2.5 by Ian Clatworthy
list-only working, include test not
2483
2484
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2485
class TestSelftestFiltering(tests.TestCase):
2394.2.5 by Ian Clatworthy
list-only working, include test not
2486
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2487
    def setUp(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2488
        tests.TestCase.setUp(self)
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2489
        self.suite = TestUtil.TestSuite()
2490
        self.loader = TestUtil.TestLoader()
4636.2.5 by Robert Collins
Minor tweaks to clarity in slower selftest tests.
2491
        self.suite.addTest(self.loader.loadTestsFromModule(
2492
            sys.modules['bzrlib.tests.test_selftest']))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2493
        self.all_names = _test_ids(self.suite)
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2494
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2495
    def test_condition_id_re(self):
2496
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2497
            'test_condition_id_re')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2498
        filtered_suite = tests.filter_suite_by_condition(
2499
            self.suite, tests.condition_id_re('test_condition_id_re'))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2500
        self.assertEqual([test_name], _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2501
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2502
    def test_condition_id_in_list(self):
2503
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
2504
                      'test_condition_id_in_list']
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2505
        id_list = tests.TestIdList(test_names)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2506
        filtered_suite = tests.filter_suite_by_condition(
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2507
            self.suite, tests.condition_id_in_list(id_list))
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2508
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2509
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2510
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2511
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2512
    def test_condition_id_startswith(self):
2513
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2514
        start1 = klass + 'test_condition_id_starts'
2515
        start2 = klass + 'test_condition_id_in'
2516
        test_names = [ klass + 'test_condition_id_in_list',
2517
                      klass + 'test_condition_id_startswith',
2518
                     ]
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2519
        filtered_suite = tests.filter_suite_by_condition(
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2520
            self.suite, tests.condition_id_startswith([start1, start2]))
2521
        self.assertEqual(test_names, _test_ids(filtered_suite))
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2522
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
2523
    def test_condition_isinstance(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2524
        filtered_suite = tests.filter_suite_by_condition(
2525
            self.suite, tests.condition_isinstance(self.__class__))
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
2526
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2527
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2528
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
2529
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2530
    def test_exclude_tests_by_condition(self):
2531
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2532
            'test_exclude_tests_by_condition')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2533
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2534
            lambda x:x.id() == excluded_name)
2535
        self.assertEqual(len(self.all_names) - 1,
2536
            filtered_suite.countTestCases())
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2537
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2538
        remaining_names = list(self.all_names)
2539
        remaining_names.remove(excluded_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2540
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2541
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2542
    def test_exclude_tests_by_re(self):
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2543
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2544
        filtered_suite = tests.exclude_tests_by_re(self.suite,
2545
                                                   'exclude_tests_by_re')
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2546
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2547
            'test_exclude_tests_by_re')
2548
        self.assertEqual(len(self.all_names) - 1,
2549
            filtered_suite.countTestCases())
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2550
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2551
        remaining_names = list(self.all_names)
2552
        remaining_names.remove(excluded_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2553
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2554
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2555
    def test_filter_suite_by_condition(self):
2556
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2557
            'test_filter_suite_by_condition')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2558
        filtered_suite = tests.filter_suite_by_condition(self.suite,
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2559
            lambda x:x.id() == test_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2560
        self.assertEqual([test_name], _test_ids(filtered_suite))
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2561
2394.2.5 by Ian Clatworthy
list-only working, include test not
2562
    def test_filter_suite_by_re(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2563
        filtered_suite = tests.filter_suite_by_re(self.suite,
2564
                                                  'test_filter_suite_by_r')
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2565
        filtered_names = _test_ids(filtered_suite)
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2566
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
2567
            'TestSelftestFiltering.test_filter_suite_by_re'])
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2568
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2569
    def test_filter_suite_by_id_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2570
        test_list = ['bzrlib.tests.test_selftest.'
2571
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2572
        filtered_suite = tests.filter_suite_by_id_list(
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2573
            self.suite, tests.TestIdList(test_list))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2574
        filtered_names = _test_ids(filtered_suite)
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2575
        self.assertEqual(
2576
            filtered_names,
2577
            ['bzrlib.tests.test_selftest.'
2578
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
2579
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2580
    def test_filter_suite_by_id_startswith(self):
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
2581
        # By design this test may fail if another test is added whose name also
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2582
        # begins with one of the start value used.
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2583
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2584
        start1 = klass + 'test_filter_suite_by_id_starts'
2585
        start2 = klass + 'test_filter_suite_by_id_li'
2586
        test_list = [klass + 'test_filter_suite_by_id_list',
2587
                     klass + 'test_filter_suite_by_id_startswith',
2588
                     ]
2589
        filtered_suite = tests.filter_suite_by_id_startswith(
2590
            self.suite, [start1, start2])
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2591
        self.assertEqual(
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2592
            test_list,
2593
            _test_ids(filtered_suite),
2594
            )
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2595
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2596
    def test_preserve_input(self):
2597
        # NB: Surely this is something in the stdlib to do this?
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2598
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
2599
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2600
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
2601
    def test_randomize_suite(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2602
        randomized_suite = tests.randomize_suite(self.suite)
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
2603
        # randomizing should not add or remove test names.
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2604
        self.assertEqual(set(_test_ids(self.suite)),
2605
                         set(_test_ids(randomized_suite)))
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
2606
        # Technically, this *can* fail, because random.shuffle(list) can be
2607
        # equal to list. Trying multiple times just pushes the frequency back.
2608
        # As its len(self.all_names)!:1, the failure frequency should be low
2609
        # enough to ignore. RBC 20071021.
2610
        # It should change the order.
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2611
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
2612
        # But not the length. (Possibly redundant with the set test, but not
2613
        # necessarily.)
3302.7.4 by Vincent Ladeuil
Cosmetic change.
2614
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
2615
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
2616
    def test_split_suit_by_condition(self):
2617
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2618
        condition = tests.condition_id_re('test_filter_suite_by_r')
2619
        split_suite = tests.split_suite_by_condition(self.suite, condition)
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
2620
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2621
            'test_filter_suite_by_re')
2622
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2623
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2624
        remaining_names = list(self.all_names)
2625
        remaining_names.remove(filtered_name)
2626
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2627
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2628
    def test_split_suit_by_re(self):
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2629
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2630
        split_suite = tests.split_suite_by_re(self.suite,
2631
                                              'test_filter_suite_by_r')
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2632
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2633
            'test_filter_suite_by_re')
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2634
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2635
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2636
        remaining_names = list(self.all_names)
2637
        remaining_names.remove(filtered_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2638
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2639
2545.3.2 by James Westby
Add a test for check_inventory_shape.
2640
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2641
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2545.3.2 by James Westby
Add a test for check_inventory_shape.
2642
2643
    def test_check_inventory_shape(self):
2561.1.2 by Aaron Bentley
Fix indenting in TestCheckInventoryShape
2644
        files = ['a', 'b/', 'b/c']
2645
        tree = self.make_branch_and_tree('.')
2646
        self.build_tree(files)
2647
        tree.add(files)
2648
        tree.lock_read()
2649
        try:
2650
            self.check_inventory_shape(tree.inventory, files)
2651
        finally:
2652
            tree.unlock()
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
2653
2654
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2655
class TestBlackboxSupport(tests.TestCase):
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
2656
    """Tests for testsuite blackbox features."""
2657
2658
    def test_run_bzr_failure_not_caught(self):
2659
        # When we run bzr in blackbox mode, we want any unexpected errors to
2660
        # propagate up to the test suite so that it can show the error in the
2661
        # usual way, and we won't get a double traceback.
2662
        e = self.assertRaises(
2663
            AssertionError,
2664
            self.run_bzr, ['assert-fail'])
2665
        # make sure we got the real thing, not an error from somewhere else in
2666
        # the test framework
2667
        self.assertEquals('always fails', str(e))
2668
        # check that there's no traceback in the test log
2669
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
2670
            r'Traceback')
2671
2672
    def test_run_bzr_user_error_caught(self):
2673
        # Running bzr in blackbox mode, normal/expected/user errors should be
2674
        # caught in the regular way and turned into an error message plus exit
2675
        # code.
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
2676
        transport_server = MemoryServer()
2677
        transport_server.setUp()
2678
        self.addCleanup(transport_server.tearDown)
2679
        url = transport_server.get_url()
2680
        self.permit_url(url)
2681
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
2682
        self.assertEqual(out, '')
3146.4.7 by Aaron Bentley
Remove UNIX path assumption
2683
        self.assertContainsRe(err,
2684
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2685
2686
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2687
class TestTestLoader(tests.TestCase):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2688
    """Tests for the test loader."""
2689
2690
    def _get_loader_and_module(self):
2691
        """Gets a TestLoader and a module with one test in it."""
2692
        loader = TestUtil.TestLoader()
2693
        module = {}
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2694
        class Stub(tests.TestCase):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2695
            def test_foo(self):
2696
                pass
2697
        class MyModule(object):
2698
            pass
2699
        MyModule.a_class = Stub
2700
        module = MyModule()
2701
        return loader, module
2702
2703
    def test_module_no_load_tests_attribute_loads_classes(self):
2704
        loader, module = self._get_loader_and_module()
2705
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2706
2707
    def test_module_load_tests_attribute_gets_called(self):
2708
        loader, module = self._get_loader_and_module()
2709
        # 'self' is here because we're faking the module with a class. Regular
2710
        # load_tests do not need that :)
2711
        def load_tests(self, standard_tests, module, loader):
2712
            result = loader.suiteClass()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2713
            for test in tests.iter_suite_tests(standard_tests):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2714
                result.addTests([test, test])
2715
            return result
2716
        # add a load_tests() method which multiplies the tests from the module.
2717
        module.__class__.load_tests = load_tests
2718
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2719
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2720
    def test_load_tests_from_module_name_smoke_test(self):
2721
        loader = TestUtil.TestLoader()
2722
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2723
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2724
                          _test_ids(suite))
2725
3302.7.8 by Vincent Ladeuil
Fix typos.
2726
    def test_load_tests_from_module_name_with_bogus_module_name(self):
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2727
        loader = TestUtil.TestLoader()
2728
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2729
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2730
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2731
class TestTestIdList(tests.TestCase):
2732
2733
    def _create_id_list(self, test_list):
2734
        return tests.TestIdList(test_list)
2735
2736
    def _create_suite(self, test_id_list):
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
2737
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2738
        class Stub(tests.TestCase):
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
2739
            def test_foo(self):
2740
                pass
2741
2742
        def _create_test_id(id):
2743
            return lambda: id
2744
2745
        suite = TestUtil.TestSuite()
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2746
        for id in test_id_list:
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
2747
            t  = Stub('test_foo')
2748
            t.id = _create_test_id(id)
2749
            suite.addTest(t)
2750
        return suite
2751
2752
    def _test_ids(self, test_suite):
2753
        """Get the ids for the tests in a test suite."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2754
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
2755
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2756
    def test_empty_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2757
        id_list = self._create_id_list([])
2758
        self.assertEquals({}, id_list.tests)
2759
        self.assertEquals({}, id_list.modules)
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2760
2761
    def test_valid_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2762
        id_list = self._create_id_list(
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
2763
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2764
             'mod1.func1', 'mod1.cl2.meth2',
2765
             'mod1.submod1',
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
2766
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2767
             ])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2768
        self.assertTrue(id_list.refers_to('mod1'))
2769
        self.assertTrue(id_list.refers_to('mod1.submod1'))
2770
        self.assertTrue(id_list.refers_to('mod1.submod2'))
2771
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2772
        self.assertTrue(id_list.includes('mod1.submod1'))
2773
        self.assertTrue(id_list.includes('mod1.func1'))
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2774
2775
    def test_bad_chars_in_params(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2776
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2777
        self.assertTrue(id_list.refers_to('mod1'))
2778
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
2779
2780
    def test_module_used(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2781
        id_list = self._create_id_list(['mod.class.meth'])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2782
        self.assertTrue(id_list.refers_to('mod'))
2783
        self.assertTrue(id_list.refers_to('mod.class'))
2784
        self.assertTrue(id_list.refers_to('mod.class.meth'))
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2785
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2786
    def test_test_suite_matches_id_list_with_unknown(self):
2787
        loader = TestUtil.TestLoader()
3302.7.6 by Vincent Ladeuil
Catch up with loadTestsFromModuleName use.
2788
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2789
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2790
                     'bogus']
2791
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2792
        self.assertEquals(['bogus'], not_found)
2793
        self.assertEquals([], duplicates)
2794
2795
    def test_suite_matches_id_list_with_duplicates(self):
2796
        loader = TestUtil.TestLoader()
3302.7.6 by Vincent Ladeuil
Catch up with loadTestsFromModuleName use.
2797
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2798
        dupes = loader.suiteClass()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2799
        for test in tests.iter_suite_tests(suite):
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2800
            dupes.addTest(test)
2801
            dupes.addTest(test) # Add it again
2802
2803
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2804
        not_found, duplicates = tests.suite_matches_id_list(
2805
            dupes, test_list)
2806
        self.assertEquals([], not_found)
2807
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2808
                          duplicates)
2809
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2810
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2811
class TestTestSuite(tests.TestCase):
2812
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
2813
    def test__test_suite_testmod_names(self):
2814
        # Test that a plausible list of test module names are returned
2815
        # by _test_suite_testmod_names.
2816
        test_list = tests._test_suite_testmod_names()
2817
        self.assertSubset([
2818
            'bzrlib.tests.blackbox',
2819
            'bzrlib.tests.per_transport',
2820
            'bzrlib.tests.test_selftest',
2821
            ],
2822
            test_list)
2823
2824
    def test__test_suite_modules_to_doctest(self):
2825
        # Test that a plausible list of modules to doctest is returned
2826
        # by _test_suite_modules_to_doctest.
2827
        test_list = tests._test_suite_modules_to_doctest()
2828
        self.assertSubset([
2829
            'bzrlib.timestamp',
2830
            ],
2831
            test_list)
2832
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2833
    def test_test_suite(self):
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
2834
        # test_suite() loads the entire test suite to operate. To avoid this
2835
        # overhead, and yet still be confident that things are happening,
2836
        # we temporarily replace two functions used by test_suite with 
2837
        # test doubles that supply a few sample tests to load, and check they
2838
        # are loaded.
2839
        calls = []
2840
        def _test_suite_testmod_names():
2841
            calls.append("testmod_names")
2842
            return [
2843
                'bzrlib.tests.blackbox.test_branch',
2844
                'bzrlib.tests.per_transport',
2845
                'bzrlib.tests.test_selftest',
2846
                ]
2847
        original_testmod_names = tests._test_suite_testmod_names
2848
        def _test_suite_modules_to_doctest():
2849
            calls.append("modules_to_doctest")
2850
            return ['bzrlib.timestamp']
2851
        orig_modules_to_doctest = tests._test_suite_modules_to_doctest
2852
        def restore_names():
2853
            tests._test_suite_testmod_names = original_testmod_names
2854
            tests._test_suite_modules_to_doctest = orig_modules_to_doctest
2855
        self.addCleanup(restore_names)
2856
        tests._test_suite_testmod_names = _test_suite_testmod_names
2857
        tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
2858
        expected_test_list = [
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2859
            # testmod_names
2860
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
4523.1.5 by Vincent Ladeuil
Fixed as asked in review.
2861
            ('bzrlib.tests.per_transport.TransportTests'
2862
             '.test_abspath(LocalURLServer)'),
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2863
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2864
            # modules_to_doctest
2865
            'bzrlib.timestamp.format_highres_date',
2866
            # plugins can't be tested that way since selftest may be run with
2867
            # --no-plugins
2868
            ]
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
2869
        suite = tests.test_suite()
2870
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2871
            set(calls))
2872
        self.assertSubset(expected_test_list, _test_ids(suite))
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2873
2874
    def test_test_suite_list_and_start(self):
4636.2.5 by Robert Collins
Minor tweaks to clarity in slower selftest tests.
2875
        # We cannot test this at the same time as the main load, because we want
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
2876
        # to know that starting_with == None works. So a second load is
2877
        # incurred - note that the starting_with parameter causes a partial load
2878
        # rather than a full load so this test should be pretty quick.
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2879
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2880
        suite = tests.test_suite(test_list,
2881
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
2882
        # test_test_suite_list_and_start is not included 
2883
        self.assertEquals(test_list, _test_ids(suite))
2884
2885
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2886
class TestLoadTestIdList(tests.TestCaseInTempDir):
2887
2888
    def _create_test_list_file(self, file_name, content):
2889
        fl = open(file_name, 'wt')
2890
        fl.write(content)
2891
        fl.close()
2892
2893
    def test_load_unknown(self):
2894
        self.assertRaises(errors.NoSuchFile,
2895
                          tests.load_test_id_list, 'i_do_not_exist')
2896
2897
    def test_load_test_list(self):
2898
        test_list_fname = 'test.list'
2899
        self._create_test_list_file(test_list_fname,
2900
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2901
        tlist = tests.load_test_id_list(test_list_fname)
2902
        self.assertEquals(2, len(tlist))
2903
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2904
        self.assertEquals('mod2.cl2.meth2', tlist[1])
2905
2906
    def test_load_dirty_file(self):
2907
        test_list_fname = 'test.list'
2908
        self._create_test_list_file(test_list_fname,
2909
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
2910
                                    'bar baz\n')
2911
        tlist = tests.load_test_id_list(test_list_fname)
2912
        self.assertEquals(4, len(tlist))
2913
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2914
        self.assertEquals('', tlist[1])
2915
        self.assertEquals('mod2.cl2.meth2', tlist[2])
2916
        self.assertEquals('bar baz', tlist[3])
2917
2918
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
2919
class TestFilteredByModuleTestLoader(tests.TestCase):
2920
2921
    def _create_loader(self, test_list):
2922
        id_filter = tests.TestIdList(test_list)
3302.8.4 by Vincent Ladeuil
Cosmetic changes.
2923
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
2924
        return loader
2925
2926
    def test_load_tests(self):
2927
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2928
        loader = self._create_loader(test_list)
2929
2930
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2931
        self.assertEquals(test_list, _test_ids(suite))
2932
2933
    def test_exclude_tests(self):
2934
        test_list = ['bogus']
2935
        loader = self._create_loader(test_list)
2936
2937
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2938
        self.assertEquals([], _test_ids(suite))
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2939
2940
2941
class TestFilteredByNameStartTestLoader(tests.TestCase):
2942
2943
    def _create_loader(self, name_start):
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
2944
        def needs_module(name):
2945
            return name.startswith(name_start) or name_start.startswith(name)
2946
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2947
        return loader
2948
2949
    def test_load_tests(self):
2950
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
2951
        loader = self._create_loader('bzrlib.tests.test_samp')
2952
2953
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2954
        self.assertEquals(test_list, _test_ids(suite))
2955
2956
    def test_load_tests_inside_module(self):
2957
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2958
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2959
2960
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2961
        self.assertEquals(test_list, _test_ids(suite))
2962
2963
    def test_exclude_tests(self):
2964
        test_list = ['bogus']
2965
        loader = self._create_loader('bogus')
2966
2967
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2968
        self.assertEquals([], _test_ids(suite))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
2969
2970
2971
class TestTestPrefixRegistry(tests.TestCase):
2972
2973
    def _get_registry(self):
2974
        tp_registry = tests.TestPrefixAliasRegistry()
2975
        return tp_registry
2976
2977
    def test_register_new_prefix(self):
2978
        tpr = self._get_registry()
2979
        tpr.register('foo', 'fff.ooo.ooo')
2980
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2981
2982
    def test_register_existing_prefix(self):
2983
        tpr = self._get_registry()
2984
        tpr.register('bar', 'bbb.aaa.rrr')
2985
        tpr.register('bar', 'bBB.aAA.rRR')
2986
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2987
        self.assertContainsRe(self._get_log(keep_log_file=True),
2988
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2989
2990
    def test_get_unknown_prefix(self):
2991
        tpr = self._get_registry()
2992
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2993
2994
    def test_resolve_prefix(self):
2995
        tpr = self._get_registry()
2996
        tpr.register('bar', 'bb.aa.rr')
2997
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2998
2999
    def test_resolve_unknown_alias(self):
3000
        tpr = self._get_registry()
3001
        self.assertRaises(errors.BzrCommandError,
3002
                          tpr.resolve_alias, 'I am not a prefix')
3003
3004
    def test_predefined_prefixes(self):
3005
        tpr = tests.test_prefix_alias_registry
3006
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
3007
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
3008
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
3009
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
3010
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
3011
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3012
3013
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3014
class TestRunSuite(tests.TestCase):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3015
3016
    def test_runner_class(self):
3017
        """run_suite accepts and uses a runner_class keyword argument."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3018
        class Stub(tests.TestCase):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3019
            def test_foo(self):
3020
                pass
3021
        suite = Stub("test_foo")
3022
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3023
        class MyRunner(tests.TextTestRunner):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3024
            def run(self, test):
3025
                calls.append(test)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3026
                return tests.ExtendedTestResult(self.stream, self.descriptions,
3027
                                                self.verbosity)
3028
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
4573.2.2 by Robert Collins
Fix selftest for TestResult progress changes.
3029
        self.assertLength(1, calls)