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