/brz/remove-bazaar

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