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