/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
21
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).
22
import time
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
23
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.
24
import warnings
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
25
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.
26
import bzrlib
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
27
from bzrlib import (
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
28
    branchbuilder,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
29
    bzrdir,
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
30
    debug,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
31
    errors,
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
32
    lockdir,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
33
    memorytree,
34
    osutils,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
35
    progress,
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
36
    remote,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
37
    repository,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
38
    symbol_versioning,
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
39
    tests,
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
40
    workingtree,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
41
    )
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
42
from bzrlib.repofmt import (
43
    pack_repo,
44
    weaverepo,
45
    )
2696.1.1 by Martin Pool
Remove things deprecated in 0.11 and earlier
46
from bzrlib.symbol_versioning import (
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
47
    deprecated_function,
48
    deprecated_in,
49
    deprecated_method,
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
50
    )
1526.1.3 by Robert Collins
Merge from upstream.
51
from bzrlib.tests import (
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
52
    test_lsprof,
53
    test_sftp_transport,
54
    TestUtil,
55
    )
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
56
from bzrlib.trace import note
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
57
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.
58
from bzrlib.version import _get_bzr_source_tree
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
59
60
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
61
def _test_ids(test_suite):
62
    """Get the ids for the tests in a test suite."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
63
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
64
65
66
class SelftestTests(tests.TestCase):
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
67
68
    def test_import_tests(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
69
        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.
70
        self.assertEqual(mod.SelftestTests, SelftestTests)
71
72
    def test_import_test_failure(self):
73
        self.assertRaises(ImportError,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
74
                          TestUtil._load_module_by_name,
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
75
                          'bzrlib.no-name-yet')
76
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
77
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.
78
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
79
    def test_logging(self):
80
        """Test logs are captured when a test fails."""
81
        self.log('a test message')
82
        self._log_file.flush()
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
83
        self.assertContainsRe(self._get_log(keep_log_file=True),
84
                              'a test message\n')
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
85
86
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
87
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.
88
89
    def test_probe_passes(self):
90
        """UnicodeFilename._probe passes."""
91
        # We can't test much more than that because the behaviour depends
92
        # on the platform.
93
        tests.UnicodeFilename._probe()
94
95
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
96
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.
97
98
    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.
99
        self.requireFeature(tests.UnicodeFilename)
100
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
101
        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.
102
        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.
103
        self.failUnlessExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
104
105
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
106
class TestTransportScenarios(tests.TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
107
    """A group of tests that test the transport implementation adaption core.
108
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
109
    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
110
    transports.
111
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
112
    This will be generalised in the future which is why it is in this
1530.1.21 by Robert Collins
Review feedback fixes.
113
    test file even though it is specific to transport tests at the moment.
114
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
115
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
116
    def test_get_transport_permutations(self):
3455.1.1 by Vincent Ladeuil
Fix typos in comments.
117
        # 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.
118
        # 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.
119
        class MockModule(object):
120
            def get_test_permutations(self):
121
                return sample_permutation
122
        sample_permutation = [(1,2), (3,4)]
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
123
        from bzrlib.tests.test_transport_implementations \
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
124
            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.
125
        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.
126
                         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.
127
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
128
    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.
129
        # this checks that the scenario generator returns as many permutations
130
        # as there are in all the registered transport modules - we assume if
131
        # this matches its probably doing the right thing especially in
132
        # combination with the tests for setting the right classes below.
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
133
        from bzrlib.tests.test_transport_implementations \
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
134
            import transport_test_permutations
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
135
        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.
136
        modules = _get_transport_modules()
137
        permutation_count = 0
138
        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.
139
            try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
140
                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.
141
                    (module + ".get_test_permutations").split('.')[1:],
142
                     __import__(module))())
143
            except errors.DependencyNotPresent:
144
                pass
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
145
        scenarios = transport_test_permutations()
146
        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.
147
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
148
    def test_scenarios_include_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
149
        # This test used to know about all the possible transports and the
150
        # order they were returned but that seems overly brittle (mbp
151
        # 20060307)
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
152
        from bzrlib.tests.test_transport_implementations \
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
153
            import transport_test_permutations
154
        scenarios = transport_test_permutations()
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
155
        # there are at least that many builtin transports
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
156
        self.assertTrue(len(scenarios) > 6)
157
        one_scenario = scenarios[0]
158
        self.assertIsInstance(one_scenario[0], str)
159
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
160
                                   bzrlib.transport.Transport))
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
161
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
162
                                   bzrlib.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
163
164
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
165
class TestBranchScenarios(tests.TestCase):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
166
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
167
    def test_scenarios(self):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
168
        # check that constructor parameters are passed through to the adapted
169
        # test.
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
170
        from bzrlib.tests.branch_implementations import make_scenarios
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
171
        server1 = "a"
172
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
173
        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.
174
        scenarios = make_scenarios(server1, server2, formats)
175
        self.assertEqual(2, len(scenarios))
2553.2.6 by Robert Collins
And overhaul BranchTestProviderAdapter too.
176
        self.assertEqual([
177
            ('str',
178
             {'branch_format': 'c',
179
              'bzrdir_format': 'C',
180
              'transport_readonly_server': 'b',
181
              'transport_server': 'a'}),
182
            ('str',
183
             {'branch_format': 'd',
184
              'bzrdir_format': 'D',
185
              'transport_readonly_server': 'b',
186
              '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.
187
            scenarios)
188
189
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
190
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.
191
192
    def test_scenarios(self):
1534.4.39 by Robert Collins
Basic BzrDir support.
193
        # check that constructor parameters are passed through to the adapted
194
        # test.
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
195
        from bzrlib.tests.bzrdir_implementations import make_scenarios
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
196
        vfs_factory = "v"
1534.4.39 by Robert Collins
Basic BzrDir support.
197
        server1 = "a"
198
        server2 = "b"
199
        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.
200
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
2553.2.7 by Robert Collins
And overhaul BzrDirTestProviderAdapter too.
201
        self.assertEqual([
202
            ('str',
203
             {'bzrdir_format': 'c',
204
              'transport_readonly_server': 'b',
205
              'transport_server': 'a',
206
              'vfs_transport_factory': 'v'}),
207
            ('str',
208
             {'bzrdir_format': 'd',
209
              'transport_readonly_server': 'b',
210
              'transport_server': 'a',
211
              '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.
212
            scenarios)
213
214
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
215
class TestRepositoryScenarios(tests.TestCase):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
216
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
217
    def test_formats_to_scenarios(self):
3689.1.3 by John Arbash Meinel
Track down other tests that used repository_implementations.
218
        from bzrlib.tests.per_repository import formats_to_scenarios
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
219
        formats = [("(c)", remote.RemoteRepositoryFormat()),
220
                   ("(d)", repository.format_registry.get(
221
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
222
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
223
            None)
224
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
225
            vfs_transport_factory="vfs")
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
226
        # no_vfs generate scenarios without vfs_transport_factory
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
227
        self.assertEqual([
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
228
            ('RemoteRepositoryFormat(c)',
229
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
230
              'repository_format': remote.RemoteRepositoryFormat(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
231
              'transport_readonly_server': 'readonly',
232
              'transport_server': 'server'}),
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
233
            ('RepositoryFormatKnitPack1(d)',
234
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
235
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
236
              'transport_readonly_server': 'readonly',
237
              'transport_server': 'server'})],
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
238
            no_vfs_scenarios)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
239
        self.assertEqual([
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
240
            ('RemoteRepositoryFormat(c)',
241
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
242
              'repository_format': remote.RemoteRepositoryFormat(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
243
              'transport_readonly_server': 'readonly',
244
              'transport_server': 'server',
245
              'vfs_transport_factory': 'vfs'}),
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
246
            ('RepositoryFormatKnitPack1(d)',
247
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
248
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
249
              'transport_readonly_server': 'readonly',
250
              'transport_server': 'server',
251
              'vfs_transport_factory': 'vfs'})],
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
252
            vfs_scenarios)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
253
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
254
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
255
class TestTestScenarioApplication(tests.TestCase):
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
256
    """Tests for the test adaption facilities."""
257
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
258
    def test_apply_scenario(self):
259
        from bzrlib.tests import apply_scenario
260
        input_test = TestTestScenarioApplication("test_apply_scenario")
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
261
        # 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.
262
        adapted_test1 = apply_scenario(input_test,
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
263
            ("new id",
264
            {"bzrdir_format":"bzr_format",
265
             "repository_format":"repo_fmt",
266
             "transport_server":"transport_server",
267
             "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.
268
        adapted_test2 = apply_scenario(input_test,
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
269
            ("new id 2", {"bzrdir_format":None}))
270
        # input_test should have been altered.
271
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
272
        # the new tests are mutually incompatible, ensuring it has
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
273
        # made new ones, and unspecified elements in the scenario
274
        # should not have been altered.
275
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
276
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
277
        self.assertEqual("transport_server", adapted_test1.transport_server)
278
        self.assertEqual("readonly-server",
279
            adapted_test1.transport_readonly_server)
280
        self.assertEqual(
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
281
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
282
            "test_apply_scenario(new id)",
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
283
            adapted_test1.id())
284
        self.assertEqual(None, adapted_test2.bzrdir_format)
285
        self.assertEqual(
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
286
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
287
            "test_apply_scenario(new id 2)",
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
288
            adapted_test2.id())
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
289
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
290
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
291
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.
292
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
293
    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.
294
        # check that constructor parameters are passed through to the adapted
295
        # test.
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
296
        from bzrlib.tests.interrepository_implementations import \
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
297
            make_scenarios
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
298
        server1 = "a"
299
        server2 = "b"
1563.2.20 by Robert Collins
Add a revision store test adapter.
300
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
301
        scenarios = make_scenarios(server1, server2, formats)
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
302
        self.assertEqual([
3302.5.4 by Vincent Ladeuil
Make interreop parametrized tests IDs unique.
303
            ('str,str,str',
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
304
             {'repository_format': 'C1',
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
305
              'repository_format_to': 'C2',
306
              'transport_readonly_server': 'b',
307
              'transport_server': 'a'}),
3302.5.4 by Vincent Ladeuil
Make interreop parametrized tests IDs unique.
308
            ('int,str,str',
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
309
             {'repository_format': 'D1',
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
310
              'repository_format_to': 'D2',
311
              'transport_readonly_server': 'b',
312
              'transport_server': 'a'})],
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
313
            scenarios)
314
315
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
316
class TestWorkingTreeScenarios(tests.TestCase):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
317
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
318
    def test_scenarios(self):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
319
        # check that constructor parameters are passed through to the adapted
320
        # test.
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
321
        from bzrlib.tests.workingtree_implementations \
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
322
            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
352
        from bzrlib.tests.tree_implementations 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.
434
        from bzrlib.tests.tree_implementations import (
435
            return_parameter,
436
            revision_tree_from_workingtree
437
            )
438
        from bzrlib.tests.intertree_implementations 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
2875.1.1 by Vincent Ladeuil
Fix #147986 by monitoring a safety .bzr directory.
581
    def test_safety_net(self):
582
        """No test should modify the safety .bzr directory.
583
584
        We just test that the _check_safety_net private method raises
2875.1.2 by Vincent Ladeuil
Update NEWS, fix typo.
585
        AssertionError, it's easier than building a test suite with the same
2875.1.1 by Vincent Ladeuil
Fix #147986 by monitoring a safety .bzr directory.
586
        test.
587
        """
588
        # Oops, a commit in the current directory (i.e. without local .bzr
589
        # directory) will crawl up the hierarchy to find a .bzr directory.
590
        self.run_bzr(['commit', '-mfoo', '--unchanged'])
591
        # But we have a safety net in place.
592
        self.assertRaises(AssertionError, self._check_safety_net)
593
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
594
    def test_dangling_locks_cause_failures(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
595
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
596
            def test_function(self):
597
                t = self.get_transport('.')
598
                l = lockdir.LockDir(t, 'lock')
599
                l.create()
600
                l.attempt_lock()
601
        test = TestDanglingLock('test_function')
4314.2.1 by Robert Collins
Update lock debugging support patch.
602
        result = test.run()
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
603
        self.assertEqual(1, len(result.errors))
604
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
605
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
606
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
607
    """Tests for the convenience functions TestCaseWithTransport introduces."""
608
609
    def test_get_readonly_url_none(self):
610
        from bzrlib.transport import get_transport
611
        from bzrlib.transport.memory import MemoryServer
612
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
613
        self.vfs_transport_factory = MemoryServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
614
        self.transport_readonly_server = None
615
        # calling get_readonly_transport() constructs a decorator on the url
616
        # for the server
617
        url = self.get_readonly_url()
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
618
        url2 = self.get_readonly_url('foo/bar')
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
619
        t = get_transport(url)
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
620
        t2 = get_transport(url2)
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
621
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
622
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
623
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
624
625
    def test_get_readonly_url_http(self):
2929.3.7 by Vincent Ladeuil
Rename bzrlib/test/HttpServer.py to bzrlib/tests/http_server.py and fix uses.
626
        from bzrlib.tests.http_server import HttpServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
627
        from bzrlib.transport import get_transport
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
628
        from bzrlib.transport.local import LocalURLServer
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
629
        from bzrlib.transport.http import HttpTransportBase
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
630
        self.transport_server = LocalURLServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
631
        self.transport_readonly_server = HttpServer
632
        # calling get_readonly_transport() gives us a HTTP server instance.
633
        url = self.get_readonly_url()
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
634
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
635
        # the transport returned may be any HttpTransportBase subclass
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
636
        t = get_transport(url)
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
637
        t2 = get_transport(url2)
1540.3.6 by Martin Pool
[merge] update from bzr.dev
638
        self.failUnless(isinstance(t, HttpTransportBase))
639
        self.failUnless(isinstance(t2, HttpTransportBase))
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
640
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
641
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
642
    def test_is_directory(self):
643
        """Test assertIsDirectory assertion"""
644
        t = self.get_transport()
645
        self.build_tree(['a_dir/', 'a_file'], transport=t)
646
        self.assertIsDirectory('a_dir', t)
647
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
648
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
649
3567.4.13 by John Arbash Meinel
Test that make_branch_builder works on a real filesystem.
650
    def test_make_branch_builder(self):
651
        builder = self.make_branch_builder('dir')
652
        rev_id = builder.build_commit()
653
        self.failUnlessExists('dir')
654
        a_dir = bzrdir.BzrDir.open('dir')
655
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
656
        a_branch = a_dir.open_branch()
657
        builder_branch = builder.get_branch()
658
        self.assertEqual(a_branch.base, builder_branch.base)
659
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
660
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
661
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
662
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
663
class TestTestCaseTransports(tests.TestCaseWithTransport):
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
664
665
    def setUp(self):
666
        super(TestTestCaseTransports, self).setUp()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
667
        self.vfs_transport_factory = MemoryServer
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
668
669
    def test_make_bzrdir_preserves_transport(self):
670
        t = self.get_transport()
671
        result_bzrdir = self.make_bzrdir('subdir')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
672
        self.assertIsInstance(result_bzrdir.transport,
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
673
                              MemoryTransport)
674
        # should not be on disk, should only be in memory
675
        self.failIfExists('subdir')
676
677
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
678
class TestChrootedTest(tests.ChrootedTestCase):
1534.4.31 by Robert Collins
cleanedup test_outside_wt
679
680
    def test_root_is_root(self):
681
        from bzrlib.transport import get_transport
682
        t = get_transport(self.get_readonly_url())
683
        url = t.base
684
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
685
686
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
687
class MockProgress(progress._BaseProgressBar):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
688
    """Progress-bar standin that records calls.
689
690
    Useful for testing pb using code.
691
    """
692
693
    def __init__(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
694
        progress._BaseProgressBar.__init__(self)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
695
        self.calls = []
696
697
    def tick(self):
698
        self.calls.append(('tick',))
699
700
    def update(self, msg=None, current=None, total=None):
701
        self.calls.append(('update', msg, current, total))
702
703
    def clear(self):
704
        self.calls.append(('clear',))
705
1864.3.1 by John Arbash Meinel
Print out when a test fails in non verbose mode, run transport tests later
706
    def note(self, msg, *args):
707
        self.calls.append(('note', msg, args))
708
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
709
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
710
class TestTestResult(tests.TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
711
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
712
    def check_timing(self, test_case, expected_re):
2095.4.1 by Martin Pool
Better progress bars during tests
713
        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
714
                descriptions=0,
715
                verbosity=1,
716
                )
717
        test_case.run(result)
718
        timed_string = result._testTimeString(test_case)
719
        self.assertContainsRe(timed_string, expected_re)
720
721
    def test_test_reporting(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
722
        class ShortDelayTestCase(tests.TestCase):
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
723
            def test_short_delay(self):
724
                time.sleep(0.003)
725
            def test_short_benchmark(self):
726
                self.time(time.sleep, 0.003)
727
        self.check_timing(ShortDelayTestCase('test_short_delay'),
728
                          r"^ +[0-9]+ms$")
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
729
        # if a benchmark time is given, we want a x of y style result.
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
730
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
731
                          r"^ +[0-9]+ms/ +[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).
732
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
733
    def test_unittest_reporting_unittest_class(self):
734
        # getting the time from a non-bzrlib test works ok
735
        class ShortDelayTestCase(unittest.TestCase):
736
            def test_short_delay(self):
737
                time.sleep(0.003)
738
        self.check_timing(ShortDelayTestCase('test_short_delay'),
739
                          r"^ +[0-9]+ms$")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
740
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
741
    def test_assigned_benchmark_file_stores_date(self):
742
        output = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
743
        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
744
                                        descriptions=0,
745
                                        verbosity=1,
746
                                        bench_history=output
747
                                        )
748
        output_string = output.getvalue()
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
749
        # if you are wondering about the regexp please read the comment in
750
        # 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.
751
        # XXX: what comment?  -- Andrew Bennetts
752
        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
753
754
    def test_benchhistory_records_test_times(self):
755
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
756
        result = bzrlib.tests.TextTestResult(
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
757
            self._log_file,
758
            descriptions=0,
759
            verbosity=1,
760
            bench_history=result_stream
761
            )
762
763
        # we want profile a call and check that its test duration is recorded
764
        # make a new test instance that when run will generate a benchmark
765
        example_test_case = TestTestResult("_time_hello_world_encoding")
766
        # execute the test, which should succeed and record times
767
        example_test_case.run(result)
768
        lines = result_stream.getvalue().splitlines()
769
        self.assertEqual(2, len(lines))
770
        self.assertContainsRe(lines[1],
771
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
772
            "._time_hello_world_encoding")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
773
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
774
    def _time_hello_world_encoding(self):
775
        """Profile two sleep calls
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
        This is used to exercise the test framework.
778
        """
779
        self.time(unicode, 'hello', errors='replace')
780
        self.time(unicode, 'world', errors='replace')
781
782
    def test_lsprofiling(self):
783
        """Verbose test result prints lsprof statistics from test cases."""
1551.15.28 by Aaron Bentley
Improve Feature usage style w/ lsprof
784
        self.requireFeature(test_lsprof.LSProfFeature)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
785
        result_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
786
        result = bzrlib.tests.VerboseTestResult(
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
787
            unittest._WritelnDecorator(result_stream),
788
            descriptions=0,
789
            verbosity=2,
790
            )
791
        # we want profile a call of some sort and check it is output by
792
        # addSuccess. We dont care about addError or addFailure as they
793
        # are not that interesting for performance tuning.
794
        # make a new test instance that when run will generate a profile
795
        example_test_case = TestTestResult("_time_hello_world_encoding")
796
        example_test_case._gather_lsprof_in_benchmarks = True
797
        # execute the test, which should succeed and record profiles
798
        example_test_case.run(result)
799
        # lsprofile_something()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
800
        # if this worked we want
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
801
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
802
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
803
        # (the lsprof header)
804
        # ... an arbitrary number of lines
805
        # and the function call which is time.sleep.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
806
        #           1        0            ???         ???       ???(sleep)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
807
        # and then repeated but with 'world', rather than 'hello'.
808
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
809
        output = result_stream.getvalue()
810
        self.assertContainsRe(output,
811
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
812
        self.assertContainsRe(output,
813
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
814
        self.assertContainsRe(output,
815
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
816
        self.assertContainsRe(output,
817
            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
818
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
819
    def test_known_failure(self):
820
        """A KnownFailure being raised should trigger several result actions."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
821
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
822
            def done(self): pass
823
            def startTests(self): pass
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
824
            def report_test_start(self, test): pass
825
            def report_known_failure(self, test, err):
826
                self._call = test, err
827
        result = InstrumentedTestResult(None, None, None, None)
828
        def test_function():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
829
            raise tests.KnownFailure('failed!')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
830
        test = unittest.FunctionTestCase(test_function)
831
        test.run(result)
832
        # it should invoke 'report_known_failure'.
833
        self.assertEqual(2, len(result._call))
834
        self.assertEqual(test, result._call[0])
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
835
        self.assertEqual(tests.KnownFailure, result._call[1][0])
836
        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
837
        # we dont introspec the traceback, if the rest is ok, it would be
838
        # exceptional for it not to be.
839
        # it should update the known_failure_count on the object.
840
        self.assertEqual(1, result.known_failure_count)
841
        # the result should be successful.
842
        self.assertTrue(result.wasSuccessful())
843
844
    def test_verbose_report_known_failure(self):
845
        # verbose test output formatting
846
        result_stream = StringIO()
847
        result = bzrlib.tests.VerboseTestResult(
848
            unittest._WritelnDecorator(result_stream),
849
            descriptions=0,
850
            verbosity=2,
851
            )
852
        test = self.get_passing_test()
853
        result.startTest(test)
854
        prefix = len(result_stream.getvalue())
855
        # the err parameter has the shape:
856
        # (class, exception object, traceback)
857
        # KnownFailures dont get their tracebacks shown though, so we
858
        # can skip that.
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
859
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
860
        result.report_known_failure(test, err)
861
        output = result_stream.getvalue()[prefix:]
862
        lines = output.splitlines()
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
863
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
864
        self.assertEqual(lines[1], '    foo')
865
        self.assertEqual(2, len(lines))
866
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
867
    def test_text_report_known_failure(self):
868
        # text test output formatting
869
        pb = MockProgress()
870
        result = bzrlib.tests.TextTestResult(
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
871
            StringIO(),
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
872
            descriptions=0,
873
            verbosity=1,
874
            pb=pb,
875
            )
876
        test = self.get_passing_test()
877
        # this seeds the state to handle reporting the test.
878
        result.startTest(test)
879
        # the err parameter has the shape:
880
        # (class, exception object, traceback)
881
        # KnownFailures dont get their tracebacks shown though, so we
882
        # can skip that.
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
883
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
884
        result.report_known_failure(test, err)
885
        self.assertEqual(
886
            [
887
            ('update', '[1 in 0s] passing_test', None, None),
888
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
889
            ],
890
            pb.calls)
891
        # known_failures should be printed in the summary, so if we run a test
892
        # after there are some known failures, the update prefix should match
893
        # this.
894
        result.known_failure_count = 3
895
        test.run(result)
896
        self.assertEqual(
897
            [
3297.1.3 by Martin Pool
Fix up selftest progress tests
898
            ('update', '[2 in 0s] passing_test', None, None),
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
899
            ],
900
            pb.calls[2:])
901
902
    def get_passing_test(self):
903
        """Return a test object that can't be run usefully."""
904
        def passing_test():
905
            pass
906
        return unittest.FunctionTestCase(passing_test)
907
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
908
    def test_add_not_supported(self):
909
        """Test the behaviour of invoking addNotSupported."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
910
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
911
            def done(self): pass
912
            def startTests(self): pass
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
913
            def report_test_start(self, test): pass
914
            def report_unsupported(self, test, feature):
915
                self._call = test, feature
916
        result = InstrumentedTestResult(None, None, None, None)
917
        test = SampleTestCase('_test_pass')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
918
        feature = tests.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
919
        result.startTest(test)
920
        result.addNotSupported(test, feature)
921
        # it should invoke 'report_unsupported'.
922
        self.assertEqual(2, len(result._call))
923
        self.assertEqual(test, result._call[0])
924
        self.assertEqual(feature, result._call[1])
925
        # the result should be successful.
926
        self.assertTrue(result.wasSuccessful())
927
        # it should record the test against a count of tests not run due to
928
        # this feature.
929
        self.assertEqual(1, result.unsupported['Feature'])
930
        # and invoking it again should increment that counter
931
        result.addNotSupported(test, feature)
932
        self.assertEqual(2, result.unsupported['Feature'])
933
934
    def test_verbose_report_unsupported(self):
935
        # verbose test output formatting
936
        result_stream = StringIO()
937
        result = bzrlib.tests.VerboseTestResult(
938
            unittest._WritelnDecorator(result_stream),
939
            descriptions=0,
940
            verbosity=2,
941
            )
942
        test = self.get_passing_test()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
943
        feature = tests.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
944
        result.startTest(test)
945
        prefix = len(result_stream.getvalue())
946
        result.report_unsupported(test, feature)
947
        output = result_stream.getvalue()[prefix:]
948
        lines = output.splitlines()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
949
        self.assertEqual(lines, ['NODEP                   0ms',
950
                                 "    The feature 'Feature' is not available."])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
951
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
952
    def test_text_report_unsupported(self):
953
        # text test output formatting
954
        pb = MockProgress()
955
        result = bzrlib.tests.TextTestResult(
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
956
            StringIO(),
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
957
            descriptions=0,
958
            verbosity=1,
959
            pb=pb,
960
            )
961
        test = self.get_passing_test()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
962
        feature = tests.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
963
        # this seeds the state to handle reporting the test.
964
        result.startTest(test)
965
        result.report_unsupported(test, feature)
966
        # no output on unsupported features
967
        self.assertEqual(
968
            [('update', '[1 in 0s] passing_test', None, None)
969
            ],
970
            pb.calls)
971
        # the number of missing features should be printed in the progress
972
        # summary, so check for that.
973
        result.unsupported = {'foo':0, 'bar':0}
974
        test.run(result)
975
        self.assertEqual(
976
            [
3297.1.3 by Martin Pool
Fix up selftest progress tests
977
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
978
            ],
979
            pb.calls[1:])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
980
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
981
    def test_unavailable_exception(self):
982
        """An UnavailableFeature being raised should invoke addNotSupported."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
983
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
984
            def done(self): pass
985
            def startTests(self): pass
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
986
            def report_test_start(self, test): pass
987
            def addNotSupported(self, test, feature):
988
                self._call = test, feature
989
        result = InstrumentedTestResult(None, None, None, None)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
990
        feature = tests.Feature()
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
991
        def test_function():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
992
            raise tests.UnavailableFeature(feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
993
        test = unittest.FunctionTestCase(test_function)
994
        test.run(result)
995
        # it should invoke 'addNotSupported'.
996
        self.assertEqual(2, len(result._call))
997
        self.assertEqual(test, result._call[0])
998
        self.assertEqual(feature, result._call[1])
999
        # and not count as an error
1000
        self.assertEqual(0, result.error_count)
1001
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1002
    def test_strict_with_unsupported_feature(self):
1003
        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
1004
                                             verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1005
        test = self.get_passing_test()
1006
        feature = "Unsupported Feature"
1007
        result.addNotSupported(test, feature)
1008
        self.assertFalse(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
1009
        self.assertEqual(None, result._extractBenchmarkTime(test))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1010
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1011
    def test_strict_with_known_failure(self):
1012
        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
1013
                                             verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1014
        test = self.get_passing_test()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1015
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
1016
        result._addKnownFailure(test, err)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1017
        self.assertFalse(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
1018
        self.assertEqual(None, result._extractBenchmarkTime(test))
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1019
1020
    def test_strict_with_success(self):
1021
        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
1022
                                             verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1023
        test = self.get_passing_test()
1024
        result.addSuccess(test)
1025
        self.assertTrue(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
1026
        self.assertEqual(None, result._extractBenchmarkTime(test))
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
1027
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
1028
    def test_startTests(self):
1029
        """Starting the first test should trigger startTests."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1030
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
1031
            calls = 0
1032
            def startTests(self): self.calls += 1
4271.2.4 by Vincent Ladeuil
Take subunit update into account.
1033
            def report_test_start(self, test): pass
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
1034
        result = InstrumentedTestResult(None, None, None, None)
1035
        def test_function():
1036
            pass
1037
        test = unittest.FunctionTestCase(test_function)
1038
        test.run(result)
1039
        self.assertEquals(1, result.calls)
1040
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
1041
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1042
class TestUnicodeFilenameFeature(tests.TestCase):
3477.1.1 by John Arbash Meinel
Move UnicodeFeature into a core 'tests' feature, rather than living in test_diff.
1043
1044
    def test_probe_passes(self):
3477.1.2 by John Arbash Meinel
Rename UnicodeFilename => UnicodeFilenameFeature
1045
        """UnicodeFilenameFeature._probe passes."""
3477.1.1 by John Arbash Meinel
Move UnicodeFeature into a core 'tests' feature, rather than living in test_diff.
1046
        # We can't test much more than that because the behaviour depends
1047
        # on the platform.
3477.1.2 by John Arbash Meinel
Rename UnicodeFilename => UnicodeFilenameFeature
1048
        tests.UnicodeFilenameFeature._probe()
3477.1.1 by John Arbash Meinel
Move UnicodeFeature into a core 'tests' feature, rather than living in test_diff.
1049
1050
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1051
class TestRunner(tests.TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
1052
1053
    def dummy_test(self):
1054
        pass
1055
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1056
    def run_test_runner(self, testrunner, test):
1057
        """Run suite in testrunner, saving global state and restoring it.
1058
1059
        This current saves and restores:
1060
        TestCaseInTempDir.TEST_ROOT
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1061
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1062
        There should be no tests in this file that use
1063
        bzrlib.tests.TextTestRunner without using this convenience method,
1064
        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.
1065
        """
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1066
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1067
        try:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1068
            tests.TestCaseInTempDir.TEST_ROOT = None
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1069
            return testrunner.run(test)
1070
        finally:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1071
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1072
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1073
    def test_known_failure_failed_run(self):
1074
        # run a test that generates a known failure which should be printed in
1075
        # the final output when real failures occur.
1076
        def known_failure_test():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1077
            raise tests.KnownFailure('failed')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1078
        test = unittest.TestSuite()
1079
        test.addTest(unittest.FunctionTestCase(known_failure_test))
1080
        def failing_test():
1081
            raise AssertionError('foo')
1082
        test.addTest(unittest.FunctionTestCase(failing_test))
1083
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1084
        runner = tests.TextTestRunner(stream=stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1085
        result = self.run_test_runner(runner, test)
1086
        lines = stream.getvalue().splitlines()
1087
        self.assertEqual([
1088
            '',
1089
            '======================================================================',
1090
            'FAIL: unittest.FunctionTestCase (failing_test)',
1091
            '----------------------------------------------------------------------',
1092
            'Traceback (most recent call last):',
1093
            '    raise AssertionError(\'foo\')',
1094
            'AssertionError: foo',
1095
            '',
1096
            '----------------------------------------------------------------------',
1097
            '',
1098
            'FAILED (failures=1, known_failure_count=1)'],
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
1099
            lines[3:8] + lines[9:13] + lines[14:])
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1100
1101
    def test_known_failure_ok_run(self):
1102
        # run a test that generates a known failure which should be printed in the final output.
1103
        def known_failure_test():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1104
            raise tests.KnownFailure('failed')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1105
        test = unittest.FunctionTestCase(known_failure_test)
1106
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1107
        runner = tests.TextTestRunner(stream=stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1108
        result = self.run_test_runner(runner, test)
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
1109
        self.assertContainsRe(stream.getvalue(),
1110
            '\n'
1111
            '-*\n'
1112
            'Ran 1 test in .*\n'
1113
            '\n'
1114
            'OK \\(known_failures=1\\)\n')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1115
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1116
    def test_skipped_test(self):
1117
        # run a test that is skipped, and check the suite as a whole still
1118
        # succeeds.
1119
        # 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.
1120
        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.
1121
            def skipping_test(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1122
                raise tests.TestSkipped('test intentionally skipped')
1123
        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.
1124
        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.
1125
        result = self.run_test_runner(runner, test)
1126
        self.assertTrue(result.wasSuccessful())
1127
1128
    def test_skipped_from_setup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1129
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1130
        class SkippedSetupTest(tests.TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1131
1132
            def setUp(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1133
                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.
1134
                self.addCleanup(self.cleanup)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1135
                raise tests.TestSkipped('skipped setup')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1136
1137
            def test_skip(self):
1138
                self.fail('test reached')
1139
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1140
            def cleanup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1141
                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.
1142
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1143
        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.
1144
        test = SkippedSetupTest('test_skip')
1145
        result = self.run_test_runner(runner, test)
1146
        self.assertTrue(result.wasSuccessful())
1147
        # 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.
1148
        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.
1149
1150
    def test_skipped_from_test(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1151
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1152
        class SkippedTest(tests.TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1153
1154
            def setUp(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1155
                tests.TestCase.setUp(self)
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1156
                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.
1157
                self.addCleanup(self.cleanup)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1158
1159
            def test_skip(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1160
                raise tests.TestSkipped('skipped test')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1161
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1162
            def cleanup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1163
                calls.append('cleanup')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1164
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1165
        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.
1166
        test = SkippedTest('test_skip')
1167
        result = self.run_test_runner(runner, test)
1168
        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.
1169
        # 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.
1170
        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.
1171
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1172
    def test_not_applicable(self):
1173
        # run a test that is skipped because it's not applicable
1174
        def not_applicable_test():
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1175
            raise tests.TestNotApplicable('this test never runs')
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1176
        out = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1177
        runner = tests.TextTestRunner(stream=out, verbosity=2)
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1178
        test = unittest.FunctionTestCase(not_applicable_test)
1179
        result = self.run_test_runner(runner, test)
1180
        self._log_file.write(out.getvalue())
1181
        self.assertTrue(result.wasSuccessful())
1182
        self.assertTrue(result.wasStrictlySuccessful())
1183
        self.assertContainsRe(out.getvalue(),
1184
                r'(?m)not_applicable_test   * N/A')
1185
        self.assertContainsRe(out.getvalue(),
1186
                r'(?m)^    this test never runs')
1187
1188
    def test_not_applicable_demo(self):
1189
        # just so you can see it in the test output
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1190
        raise tests.TestNotApplicable('this test is just a demonstation')
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1191
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1192
    def test_unsupported_features_listed(self):
1193
        """When unsupported features are encountered they are detailed."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1194
        class Feature1(tests.Feature):
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1195
            def _probe(self): return False
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1196
        class Feature2(tests.Feature):
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1197
            def _probe(self): return False
1198
        # create sample tests
1199
        test1 = SampleTestCase('_test_pass')
1200
        test1._test_needs_features = [Feature1()]
1201
        test2 = SampleTestCase('_test_pass')
1202
        test2._test_needs_features = [Feature2()]
1203
        test = unittest.TestSuite()
1204
        test.addTest(test1)
1205
        test.addTest(test2)
1206
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1207
        runner = tests.TextTestRunner(stream=stream)
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1208
        result = self.run_test_runner(runner, test)
1209
        lines = stream.getvalue().splitlines()
1210
        self.assertEqual([
1211
            'OK',
1212
            "Missing feature 'Feature1' skipped 1 tests.",
1213
            "Missing feature 'Feature2' skipped 1 tests.",
1214
            ],
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1215
            lines[-3:])
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1216
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1217
    def test_bench_history(self):
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
1218
        # tests that the running the benchmark produces a history file
1219
        # containing a timestamp and the revision id of the bzrlib source which
1220
        # was tested.
1221
        workingtree = _get_bzr_source_tree()
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1222
        test = TestRunner('dummy_test')
1223
        output = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1224
        runner = tests.TextTestRunner(stream=self._log_file,
1225
                                      bench_history=output)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1226
        result = self.run_test_runner(runner, test)
1227
        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.
1228
        self.assertContainsRe(output_string, "--date [0-9.]+")
1229
        if workingtree is not None:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1230
            revision_id = workingtree.get_parent_ids()[0]
1951.1.1 by Andrew Bennetts
Make test_bench_history and _get_bzr_source_tree tolerant of UnknownFormatError for the bzr workingtree.
1231
            self.assertEndsWith(output_string.rstrip(), revision_id)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1232
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1233
    def assertLogDeleted(self, test):
1234
        log = test._get_log()
1235
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1236
        self.assertEqual('', test._log_contents)
1237
        self.assertIs(None, test._log_file_name)
1238
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1239
    def test_success_log_deleted(self):
1240
        """Successful tests have their log deleted"""
1241
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1242
        class LogTester(tests.TestCase):
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1243
1244
            def test_success(self):
1245
                self.log('this will be removed\n')
1246
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1247
        sio = StringIO()
1248
        runner = tests.TextTestRunner(stream=sio)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1249
        test = LogTester('test_success')
1250
        result = self.run_test_runner(runner, test)
1251
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1252
        self.assertLogDeleted(test)
1253
1254
    def test_skipped_log_deleted(self):
1255
        """Skipped tests have their log deleted"""
1256
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1257
        class LogTester(tests.TestCase):
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1258
1259
            def test_skipped(self):
1260
                self.log('this will be removed\n')
1261
                raise tests.TestSkipped()
1262
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1263
        sio = StringIO()
1264
        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.
1265
        test = LogTester('test_skipped')
1266
        result = self.run_test_runner(runner, test)
1267
1268
        self.assertLogDeleted(test)
1269
1270
    def test_not_aplicable_log_deleted(self):
1271
        """Not applicable tests have their log deleted"""
1272
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1273
        class LogTester(tests.TestCase):
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1274
1275
            def test_not_applicable(self):
1276
                self.log('this will be removed\n')
1277
                raise tests.TestNotApplicable()
1278
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1279
        sio = StringIO()
1280
        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.
1281
        test = LogTester('test_not_applicable')
1282
        result = self.run_test_runner(runner, test)
1283
1284
        self.assertLogDeleted(test)
1285
1286
    def test_known_failure_log_deleted(self):
1287
        """Know failure tests have their log deleted"""
1288
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1289
        class LogTester(tests.TestCase):
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1290
1291
            def test_known_failure(self):
1292
                self.log('this will be removed\n')
1293
                raise tests.KnownFailure()
1294
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1295
        sio = StringIO()
1296
        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.
1297
        test = LogTester('test_known_failure')
1298
        result = self.run_test_runner(runner, test)
1299
1300
        self.assertLogDeleted(test)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1301
1302
    def test_fail_log_kept(self):
1303
        """Failed tests have their log kept"""
1304
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1305
        class LogTester(tests.TestCase):
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1306
1307
            def test_fail(self):
1308
                self.log('this will be kept\n')
1309
                self.fail('this test fails')
1310
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1311
        sio = StringIO()
1312
        runner = tests.TextTestRunner(stream=sio)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1313
        test = LogTester('test_fail')
1314
        result = self.run_test_runner(runner, test)
1315
1316
        text = sio.getvalue()
1317
        self.assertContainsRe(text, 'this will be kept')
1318
        self.assertContainsRe(text, 'this test fails')
1319
1320
        log = test._get_log()
1321
        self.assertContainsRe(log, 'this will be kept')
1322
        self.assertEqual(log, test._log_contents)
1323
1324
    def test_error_log_kept(self):
1325
        """Tests with errors have their log kept"""
1326
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1327
        class LogTester(tests.TestCase):
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1328
1329
            def test_error(self):
1330
                self.log('this will be kept\n')
1331
                raise ValueError('random exception raised')
1332
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1333
        sio = StringIO()
1334
        runner = tests.TextTestRunner(stream=sio)
2036.1.1 by John Arbash Meinel
test that logs are kept or deleted when appropriate
1335
        test = LogTester('test_error')
1336
        result = self.run_test_runner(runner, test)
1337
1338
        text = sio.getvalue()
1339
        self.assertContainsRe(text, 'this will be kept')
1340
        self.assertContainsRe(text, 'random exception raised')
1341
1342
        log = test._get_log()
1343
        self.assertContainsRe(log, 'this will be kept')
1344
        self.assertEqual(log, test._log_contents)
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
1345
2036.1.2 by John Arbash Meinel
whitespace fix
1346
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1347
class SampleTestCase(tests.TestCase):
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1348
1349
    def _test_pass(self):
1350
        pass
1351
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1352
class _TestException(Exception):
1353
    pass
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1354
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1355
class TestTestCase(tests.TestCase):
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1356
    """Tests that test the core bzrlib TestCase."""
1357
4144.1.1 by Robert Collins
New assertLength method based on one Martin has squirreled away somewhere.
1358
    def test_assertLength_matches_empty(self):
1359
        a_list = []
1360
        self.assertLength(0, a_list)
1361
1362
    def test_assertLength_matches_nonempty(self):
1363
        a_list = [1, 2, 3]
1364
        self.assertLength(3, a_list)
1365
1366
    def test_assertLength_fails_different(self):
1367
        a_list = []
1368
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1369
1370
    def test_assertLength_shows_sequence_in_failure(self):
1371
        a_list = [1, 2, 3]
1372
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
1373
            a_list)
1374
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1375
            exception.args[0])
1376
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1377
    def test_base_setUp_not_called_causes_failure(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1378
        class TestCaseWithBrokenSetUp(tests.TestCase):
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1379
            def setUp(self):
1380
                pass # does not call TestCase.setUp
1381
            def test_foo(self):
1382
                pass
1383
        test = TestCaseWithBrokenSetUp('test_foo')
1384
        result = unittest.TestResult()
1385
        test.run(result)
1386
        self.assertFalse(result.wasSuccessful())
4153.1.5 by Andrew Bennetts
Tweak assertions based on Robert's review.
1387
        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.
1388
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1389
    def test_base_tearDown_not_called_causes_failure(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1390
        class TestCaseWithBrokenTearDown(tests.TestCase):
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1391
            def tearDown(self):
1392
                pass # does not call TestCase.tearDown
1393
            def test_foo(self):
1394
                pass
1395
        test = TestCaseWithBrokenTearDown('test_foo')
1396
        result = unittest.TestResult()
1397
        test.run(result)
1398
        self.assertFalse(result.wasSuccessful())
4153.1.5 by Andrew Bennetts
Tweak assertions based on Robert's review.
1399
        self.assertEqual(1, result.testsRun)
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1400
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1401
    def test_debug_flags_sanitised(self):
1402
        """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.
1403
        if 'allow_debug' in tests.selftest_debug_flags:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1404
            raise tests.TestNotApplicable(
3731.3.2 by Andrew Bennetts
Fix typo.
1405
                '-Eallow_debug option prevents debug flag sanitisation')
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1406
        # we could set something and run a test that will check
1407
        # it gets santised, but this is probably sufficient for now:
1408
        # if someone runs the test with -Dsomething it will error.
1409
        self.assertEqual(set(), bzrlib.debug.debug_flags)
1410
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1411
    def change_selftest_debug_flags(self, new_flags):
1412
        orig_selftest_flags = tests.selftest_debug_flags
1413
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1414
        tests.selftest_debug_flags = set(new_flags)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1415
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1416
    def _restore_selftest_debug_flags(self, flags):
1417
        tests.selftest_debug_flags = flags
1418
1419
    def test_allow_debug_flag(self):
1420
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1421
        sanitised (i.e. cleared) before running a test.
1422
        """
1423
        self.change_selftest_debug_flags(set(['allow_debug']))
1424
        bzrlib.debug.debug_flags = set(['a-flag'])
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1425
        class TestThatRecordsFlags(tests.TestCase):
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1426
            def test_foo(nested_self):
1427
                self.flags = set(bzrlib.debug.debug_flags)
1428
        test = TestThatRecordsFlags('test_foo')
1429
        test.run(self.make_test_result())
1430
        self.assertEqual(set(['a-flag']), self.flags)
1431
1432
    def test_debug_flags_restored(self):
1433
        """The bzrlib debug flags should be restored to their original state
1434
        after the test was run, even if allow_debug is set.
1435
        """
1436
        self.change_selftest_debug_flags(set(['allow_debug']))
1437
        # Now run a test that modifies debug.debug_flags.
1438
        bzrlib.debug.debug_flags = set(['original-state'])
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1439
        class TestThatModifiesFlags(tests.TestCase):
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1440
            def test_foo(self):
1441
                bzrlib.debug.debug_flags = set(['modified'])
1442
        test = TestThatModifiesFlags('test_foo')
1443
        test.run(self.make_test_result())
1444
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1445
1446
    def make_test_result(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1447
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1448
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1449
    def inner_test(self):
1450
        # the inner child test
1451
        note("inner_test")
1452
1453
    def outer_child(self):
1454
        # the outer child test
1455
        note("outer_start")
1456
        self.inner_test = TestTestCase("inner_child")
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1457
        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.
1458
        self.inner_test.run(result)
1459
        note("outer finish")
1460
1461
    def test_trace_nesting(self):
1462
        # this tests that each test case nests its trace facility correctly.
1463
        # we do this by running a test case manually. That test case (A)
1464
        # should setup a new log, log content to it, setup a child case (B),
1465
        # which should log independently, then case (A) should log a trailer
1466
        # and return.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1467
        # 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.
1468
        # logs after the outer child finishes is correct, which a bad clean
1469
        # up routine in tearDown might trigger a fault in our test with only
1470
        # one child, we should instead see the bad result inside our test with
1471
        # the two children.
1472
        # the outer child test
1473
        original_trace = bzrlib.trace._trace_file
1474
        outer_test = TestTestCase("outer_child")
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1475
        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.
1476
        outer_test.run(result)
1477
        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)
1478
1479
    def method_that_times_a_bit_twice(self):
1480
        # 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.
1481
        self.time(time.sleep, 0.007)
1482
        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)
1483
1484
    def test_time_creates_benchmark_in_result(self):
1485
        """Test that the TestCase.time() method accumulates a benchmark time."""
1486
        sample_test = TestTestCase("method_that_times_a_bit_twice")
1487
        output_stream = StringIO()
2095.4.1 by Martin Pool
Better progress bars during tests
1488
        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)
1489
            unittest._WritelnDecorator(output_stream),
1490
            descriptions=0,
2095.4.1 by Martin Pool
Better progress bars during tests
1491
            verbosity=2,
1492
            num_tests=sample_test.countTestCases())
1707.2.4 by Robert Collins
Teach the bzrlib TestCase to report the time take by calls to self.time as benchmark time, allowing granular reporting of time during benchmarks. See bzrlib.benchmarks.bench_add. (Robert Collins, Martin Pool)
1493
        sample_test.run(result)
1494
        self.assertContainsRe(
1495
            output_stream.getvalue(),
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1496
            r"\d+ms/ +\d+ms\n$")
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1497
1498
    def test_hooks_sanitised(self):
1499
        """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.
1500
        # Note this test won't fail with hooks that the core library doesn't
1501
        # use - but it trigger with a plugin that adds hooks, so its still a
1502
        # 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.
1503
        self.assertEqual(bzrlib.branch.BranchHooks(),
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1504
            bzrlib.branch.Branch.hooks)
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
1505
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1506
            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.
1507
        self.assertEqual(bzrlib.commands.CommandHooks(),
1508
            bzrlib.commands.Command.hooks)
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1509
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1510
    def test__gather_lsprof_in_benchmarks(self):
1511
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1512
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1513
        Each self.time() call is individually and separately profiled.
1514
        """
1551.15.28 by Aaron Bentley
Improve Feature usage style w/ lsprof
1515
        self.requireFeature(test_lsprof.LSProfFeature)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1516
        # 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
1517
        # needed.
1518
        self._gather_lsprof_in_benchmarks = True
1519
        self.time(time.sleep, 0.000)
1520
        self.time(time.sleep, 0.003)
1521
        self.assertEqual(2, len(self._benchcalls))
1522
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1523
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1524
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1525
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1526
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1527
    def test_knownFailure(self):
1528
        """Self.knownFailure() should raise a KnownFailure exception."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1529
        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
1530
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1531
    def test_requireFeature_available(self):
1532
        """self.requireFeature(available) is a no-op."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1533
        class Available(tests.Feature):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1534
            def _probe(self):return True
1535
        feature = Available()
1536
        self.requireFeature(feature)
1537
1538
    def test_requireFeature_unavailable(self):
1539
        """self.requireFeature(unavailable) raises UnavailableFeature."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1540
        class Unavailable(tests.Feature):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1541
            def _probe(self):return False
1542
        feature = Unavailable()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1543
        self.assertRaises(tests.UnavailableFeature,
1544
                          self.requireFeature, feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1545
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1546
    def test_run_no_parameters(self):
1547
        test = SampleTestCase('_test_pass')
1548
        test.run()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1549
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1550
    def test_run_enabled_unittest_result(self):
1551
        """Test we revert to regular behaviour when the test is enabled."""
1552
        test = SampleTestCase('_test_pass')
1553
        class EnabledFeature(object):
1554
            def available(self):
1555
                return True
1556
        test._test_needs_features = [EnabledFeature()]
1557
        result = unittest.TestResult()
1558
        test.run(result)
1559
        self.assertEqual(1, result.testsRun)
1560
        self.assertEqual([], result.errors)
1561
        self.assertEqual([], result.failures)
1562
1563
    def test_run_disabled_unittest_result(self):
1564
        """Test our compatability for disabled tests with unittest results."""
1565
        test = SampleTestCase('_test_pass')
1566
        class DisabledFeature(object):
1567
            def available(self):
1568
                return False
1569
        test._test_needs_features = [DisabledFeature()]
1570
        result = unittest.TestResult()
1571
        test.run(result)
1572
        self.assertEqual(1, result.testsRun)
1573
        self.assertEqual([], result.errors)
1574
        self.assertEqual([], result.failures)
1575
1576
    def test_run_disabled_supporting_result(self):
1577
        """Test disabled tests behaviour with support aware results."""
1578
        test = SampleTestCase('_test_pass')
1579
        class DisabledFeature(object):
1580
            def available(self):
1581
                return False
1582
        the_feature = DisabledFeature()
1583
        test._test_needs_features = [the_feature]
1584
        class InstrumentedTestResult(unittest.TestResult):
1585
            def __init__(self):
1586
                unittest.TestResult.__init__(self)
1587
                self.calls = []
1588
            def startTest(self, test):
1589
                self.calls.append(('startTest', test))
1590
            def stopTest(self, test):
1591
                self.calls.append(('stopTest', test))
1592
            def addNotSupported(self, test, feature):
1593
                self.calls.append(('addNotSupported', test, feature))
1594
        result = InstrumentedTestResult()
1595
        test.run(result)
1596
        self.assertEqual([
1597
            ('startTest', test),
1598
            ('addNotSupported', test, the_feature),
1599
            ('stopTest', test),
1600
            ],
1601
            result.calls)
1602
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1603
    def test_assert_list_raises_on_generator(self):
1604
        def generator_which_will_raise():
1605
            # This will not raise until after the first yield
1606
            yield 1
1607
            raise _TestException()
1608
1609
        e = self.assertListRaises(_TestException, generator_which_will_raise)
1610
        self.assertIsInstance(e, _TestException)
1611
1612
        e = self.assertListRaises(Exception, generator_which_will_raise)
1613
        self.assertIsInstance(e, _TestException)
1614
1615
    def test_assert_list_raises_on_plain(self):
1616
        def plain_exception():
1617
            raise _TestException()
1618
            return []
1619
1620
        e = self.assertListRaises(_TestException, plain_exception)
1621
        self.assertIsInstance(e, _TestException)
1622
1623
        e = self.assertListRaises(Exception, plain_exception)
1624
        self.assertIsInstance(e, _TestException)
1625
1626
    def test_assert_list_raises_assert_wrong_exception(self):
1627
        class _NotTestException(Exception):
1628
            pass
1629
1630
        def wrong_exception():
1631
            raise _NotTestException()
1632
1633
        def wrong_exception_generator():
1634
            yield 1
1635
            yield 2
1636
            raise _NotTestException()
1637
1638
        # Wrong exceptions are not intercepted
1639
        self.assertRaises(_NotTestException,
1640
            self.assertListRaises, _TestException, wrong_exception)
1641
        self.assertRaises(_NotTestException,
1642
            self.assertListRaises, _TestException, wrong_exception_generator)
1643
1644
    def test_assert_list_raises_no_exception(self):
1645
        def success():
1646
            return []
1647
1648
        def success_generator():
1649
            yield 1
1650
            yield 2
1651
1652
        self.assertRaises(AssertionError,
1653
            self.assertListRaises, _TestException, success)
1654
1655
        self.assertRaises(AssertionError,
1656
            self.assertListRaises, _TestException, success_generator)
1657
1534.11.4 by Robert Collins
Merge from mainline.
1658
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1659
# NB: Don't delete this; it's not actually from 0.11!
1660
@deprecated_function(deprecated_in((0, 11, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1661
def sample_deprecated_function():
1662
    """A deprecated function to test applyDeprecated with."""
1663
    return 2
1664
1665
1666
def sample_undeprecated_function(a_param):
1667
    """A undeprecated function to test applyDeprecated with."""
1668
1669
1670
class ApplyDeprecatedHelper(object):
1671
    """A helper class for ApplyDeprecated tests."""
1672
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1673
    @deprecated_method(deprecated_in((0, 11, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1674
    def sample_deprecated_method(self, param_one):
1675
        """A deprecated method for testing with."""
1676
        return param_one
1677
1678
    def sample_normal_method(self):
1679
        """A undeprecated method."""
1680
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1681
    @deprecated_method(deprecated_in((0, 10, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1682
    def sample_nested_deprecation(self):
1683
        return sample_deprecated_function()
1684
1685
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1686
class TestExtraAssertions(tests.TestCase):
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1687
    """Tests for new test assertions in bzrlib test suite"""
1688
1689
    def test_assert_isinstance(self):
1690
        self.assertIsInstance(2, int)
1691
        self.assertIsInstance(u'', basestring)
1692
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1693
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1694
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
1695
    def test_assertEndsWith(self):
1696
        self.assertEndsWith('foo', 'oo')
1697
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1698
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1699
    def test_applyDeprecated_not_deprecated(self):
1700
        sample_object = ApplyDeprecatedHelper()
1701
        # 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
1702
        self.assertRaises(AssertionError, self.applyDeprecated,
1703
            deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1704
            sample_object.sample_normal_method)
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1705
        self.assertRaises(AssertionError, self.applyDeprecated,
1706
            deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1707
            sample_undeprecated_function, "a param value")
1708
        # calling a deprecated callable (function or method) with the wrong
1709
        # expected deprecation fails.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1710
        self.assertRaises(AssertionError, self.applyDeprecated,
1711
            deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1712
            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
1713
        self.assertRaises(AssertionError, self.applyDeprecated,
1714
            deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1715
            sample_deprecated_function)
1716
        # calling a deprecated callable (function or method) with the right
1717
        # expected deprecation returns the functions result.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1718
        self.assertEqual("a param value",
1719
            self.applyDeprecated(deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1720
            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
1721
        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
1722
            sample_deprecated_function))
1723
        # calling a nested deprecation with the wrong deprecation version
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1724
        # 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
1725
        # supplied version.
1726
        self.assertRaises(AssertionError, self.applyDeprecated,
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1727
            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
1728
        # calling a nested deprecation with the right deprecation value
1729
        # returns the calls result.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1730
        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
1731
            sample_object.sample_nested_deprecation))
1732
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1733
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1734
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1735
            if be_deprecated is True:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1736
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1737
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1738
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1739
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1740
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1741
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1742
        self.assertEqual('result', result)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1743
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1744
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1745
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1746
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1747
class TestWarningTests(tests.TestCase):
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1748
    """Tests for calling methods that raise warnings."""
1749
1750
    def test_callCatchWarnings(self):
1751
        def meth(a, b):
1752
            warnings.warn("this is your last warning")
1753
            return a + b
1754
        wlist, result = self.callCatchWarnings(meth, 1, 2)
1755
        self.assertEquals(3, result)
1756
        # would like just to compare them, but UserWarning doesn't implement
1757
        # eq well
1758
        w0, = wlist
1759
        self.assertIsInstance(w0, UserWarning)
2592.3.247 by Andrew Bennetts
Fix test_callCatchWarnings to pass when run with Python 2.4.
1760
        self.assertEquals("this is your last warning", str(w0))
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1761
1762
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1763
class TestConvenienceMakers(tests.TestCaseWithTransport):
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1764
    """Test for the make_* convenience functions."""
1765
1766
    def test_make_branch_and_tree_with_format(self):
1767
        # we should be able to supply a format to make_branch_and_tree
1768
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1769
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1770
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1771
                              bzrlib.bzrdir.BzrDirMetaFormat1)
1772
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1773
                              bzrlib.bzrdir.BzrDirFormat6)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1774
1986.2.1 by Robert Collins
Bugfix - the name of the test for make_branch_and_memory_tree was wrong.
1775
    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
1776
        # we should be able to get a new branch and a mutable tree from
1777
        # TestCaseWithTransport
1778
        tree = self.make_branch_and_memory_tree('a')
1779
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1780
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1781
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1782
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
1783
1784
    def test_make_tree_for_sftp_branch(self):
1785
        """Transports backed by local directories create local trees."""
1786
1787
        tree = self.make_branch_and_tree('t1')
1788
        base = tree.bzrdir.root_transport.base
1789
        self.failIf(base.startswith('sftp'),
1790
                'base %r is on sftp but should be local' % base)
1791
        self.assertEquals(tree.bzrdir.root_transport,
1792
                tree.branch.bzrdir.root_transport)
1793
        self.assertEquals(tree.bzrdir.root_transport,
1794
                tree.branch.repository.bzrdir.root_transport)
1795
1796
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1797
class TestSelftest(tests.TestCase):
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1798
    """Tests of bzrlib.tests.selftest."""
1799
1800
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1801
        factory_called = []
1802
        def factory():
1803
            factory_called.append(True)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1804
            return TestUtil.TestSuite()
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1805
        out = StringIO()
1806
        err = StringIO()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1807
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
1808
            test_suite_factory=factory)
1809
        self.assertEqual([True], factory_called)
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
1810
1811
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1812
class TestKnownFailure(tests.TestCase):
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1813
1814
    def test_known_failure(self):
1815
        """Check that KnownFailure is defined appropriately."""
1816
        # a KnownFailure is an assertion error for compatability with unaware
1817
        # runners.
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1818
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1819
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1820
    def test_expect_failure(self):
1821
        try:
1822
            self.expectFailure("Doomed to failure", self.assertTrue, False)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1823
        except tests.KnownFailure, e:
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1824
            self.assertEqual('Doomed to failure', e.args[0])
1825
        try:
1826
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1827
        except AssertionError, e:
1828
            self.assertEqual('Unexpected success.  Should have failed:'
1829
                             ' Doomed to failure', e.args[0])
1830
        else:
1831
            self.fail('Assertion not raised')
1832
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1833
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1834
class TestFeature(tests.TestCase):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1835
1836
    def test_caching(self):
1837
        """Feature._probe is called by the feature at most once."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1838
        class InstrumentedFeature(tests.Feature):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1839
            def __init__(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1840
                super(InstrumentedFeature, self).__init__()
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1841
                self.calls = []
1842
            def _probe(self):
1843
                self.calls.append('_probe')
1844
                return False
1845
        feature = InstrumentedFeature()
1846
        feature.available()
1847
        self.assertEqual(['_probe'], feature.calls)
1848
        feature.available()
1849
        self.assertEqual(['_probe'], feature.calls)
1850
1851
    def test_named_str(self):
1852
        """Feature.__str__ should thunk to feature_name()."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1853
        class NamedFeature(tests.Feature):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1854
            def feature_name(self):
1855
                return 'symlinks'
1856
        feature = NamedFeature()
1857
        self.assertEqual('symlinks', str(feature))
1858
1859
    def test_default_str(self):
1860
        """Feature.__str__ should default to __class__.__name__."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1861
        class NamedFeature(tests.Feature):
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
1862
            pass
1863
        feature = NamedFeature()
1864
        self.assertEqual('NamedFeature', str(feature))
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1865
1866
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1867
class TestUnavailableFeature(tests.TestCase):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1868
1869
    def test_access_feature(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1870
        feature = tests.Feature()
1871
        exception = tests.UnavailableFeature(feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1872
        self.assertIs(feature, exception.args[0])
2394.2.5 by Ian Clatworthy
list-only working, include test not
1873
1874
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1875
class TestSelftestFiltering(tests.TestCase):
2394.2.5 by Ian Clatworthy
list-only working, include test not
1876
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
1877
    def setUp(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1878
        tests.TestCase.setUp(self)
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
1879
        self.suite = TestUtil.TestSuite()
1880
        self.loader = TestUtil.TestLoader()
1881
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1882
            'bzrlib.tests.test_selftest']))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1883
        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
1884
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
1885
    def test_condition_id_re(self):
1886
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1887
            'test_condition_id_re')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1888
        filtered_suite = tests.filter_suite_by_condition(
1889
            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.
1890
        self.assertEqual([test_name], _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
1891
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
1892
    def test_condition_id_in_list(self):
1893
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1894
                      'test_condition_id_in_list']
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
1895
        id_list = tests.TestIdList(test_names)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1896
        filtered_suite = tests.filter_suite_by_condition(
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
1897
            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.
1898
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1899
        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.
1900
        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.
1901
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
1902
    def test_condition_id_startswith(self):
1903
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
1904
        start1 = klass + 'test_condition_id_starts'
1905
        start2 = klass + 'test_condition_id_in'
1906
        test_names = [ klass + 'test_condition_id_in_list',
1907
                      klass + 'test_condition_id_startswith',
1908
                     ]
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1909
        filtered_suite = tests.filter_suite_by_condition(
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
1910
            self.suite, tests.condition_id_startswith([start1, start2]))
1911
        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.
1912
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
1913
    def test_condition_isinstance(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1914
        filtered_suite = tests.filter_suite_by_condition(
1915
            self.suite, tests.condition_isinstance(self.__class__))
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
1916
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1917
        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.
1918
        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
1919
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
1920
    def test_exclude_tests_by_condition(self):
1921
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1922
            'test_exclude_tests_by_condition')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1923
        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
1924
            lambda x:x.id() == excluded_name)
1925
        self.assertEqual(len(self.all_names) - 1,
1926
            filtered_suite.countTestCases())
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1927
        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
1928
        remaining_names = list(self.all_names)
1929
        remaining_names.remove(excluded_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1930
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
1931
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
1932
    def test_exclude_tests_by_re(self):
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1933
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1934
        filtered_suite = tests.exclude_tests_by_re(self.suite,
1935
                                                   'exclude_tests_by_re')
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
1936
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1937
            'test_exclude_tests_by_re')
1938
        self.assertEqual(len(self.all_names) - 1,
1939
            filtered_suite.countTestCases())
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1940
        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
1941
        remaining_names = list(self.all_names)
1942
        remaining_names.remove(excluded_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1943
        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
1944
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
1945
    def test_filter_suite_by_condition(self):
1946
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1947
            'test_filter_suite_by_condition')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1948
        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
1949
            lambda x:x.id() == test_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1950
        self.assertEqual([test_name], _test_ids(filtered_suite))
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
1951
2394.2.5 by Ian Clatworthy
list-only working, include test not
1952
    def test_filter_suite_by_re(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1953
        filtered_suite = tests.filter_suite_by_re(self.suite,
1954
                                                  'test_filter_suite_by_r')
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1955
        filtered_names = _test_ids(filtered_suite)
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
1956
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1957
            '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
1958
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
1959
    def test_filter_suite_by_id_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
1960
        test_list = ['bzrlib.tests.test_selftest.'
1961
                     '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.
1962
        filtered_suite = tests.filter_suite_by_id_list(
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
1963
            self.suite, tests.TestIdList(test_list))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1964
        filtered_names = _test_ids(filtered_suite)
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
1965
        self.assertEqual(
1966
            filtered_names,
1967
            ['bzrlib.tests.test_selftest.'
1968
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
1969
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
1970
    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.
1971
        # 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.
1972
        # 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.
1973
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
1974
        start1 = klass + 'test_filter_suite_by_id_starts'
1975
        start2 = klass + 'test_filter_suite_by_id_li'
1976
        test_list = [klass + 'test_filter_suite_by_id_list',
1977
                     klass + 'test_filter_suite_by_id_startswith',
1978
                     ]
1979
        filtered_suite = tests.filter_suite_by_id_startswith(
1980
            self.suite, [start1, start2])
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
1981
        self.assertEqual(
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
1982
            test_list,
1983
            _test_ids(filtered_suite),
1984
            )
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
1985
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
1986
    def test_preserve_input(self):
1987
        # NB: Surely this is something in the stdlib to do this?
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1988
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
1989
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
1990
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
1991
    def test_randomize_suite(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1992
        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.
1993
        # randomizing should not add or remove test names.
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
1994
        self.assertEqual(set(_test_ids(self.suite)),
1995
                         set(_test_ids(randomized_suite)))
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
1996
        # Technically, this *can* fail, because random.shuffle(list) can be
1997
        # equal to list. Trying multiple times just pushes the frequency back.
1998
        # As its len(self.all_names)!:1, the failure frequency should be low
1999
        # enough to ignore. RBC 20071021.
2000
        # It should change the order.
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2001
        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
2002
        # But not the length. (Possibly redundant with the set test, but not
2003
        # necessarily.)
3302.7.4 by Vincent Ladeuil
Cosmetic change.
2004
        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
2005
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
2006
    def test_split_suit_by_condition(self):
2007
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2008
        condition = tests.condition_id_re('test_filter_suite_by_r')
2009
        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``.
2010
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2011
            'test_filter_suite_by_re')
2012
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2013
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2014
        remaining_names = list(self.all_names)
2015
        remaining_names.remove(filtered_name)
2016
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2017
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2018
    def test_split_suit_by_re(self):
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2019
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2020
        split_suite = tests.split_suite_by_re(self.suite,
2021
                                              'test_filter_suite_by_r')
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2022
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2023
            'test_filter_suite_by_re')
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2024
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2025
        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
2026
        remaining_names = list(self.all_names)
2027
        remaining_names.remove(filtered_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2028
        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
2029
2545.3.2 by James Westby
Add a test for check_inventory_shape.
2030
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2031
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2545.3.2 by James Westby
Add a test for check_inventory_shape.
2032
2033
    def test_check_inventory_shape(self):
2561.1.2 by Aaron Bentley
Fix indenting in TestCheckInventoryShape
2034
        files = ['a', 'b/', 'b/c']
2035
        tree = self.make_branch_and_tree('.')
2036
        self.build_tree(files)
2037
        tree.add(files)
2038
        tree.lock_read()
2039
        try:
2040
            self.check_inventory_shape(tree.inventory, files)
2041
        finally:
2042
            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
2043
2044
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2045
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
2046
    """Tests for testsuite blackbox features."""
2047
2048
    def test_run_bzr_failure_not_caught(self):
2049
        # When we run bzr in blackbox mode, we want any unexpected errors to
2050
        # propagate up to the test suite so that it can show the error in the
2051
        # usual way, and we won't get a double traceback.
2052
        e = self.assertRaises(
2053
            AssertionError,
2054
            self.run_bzr, ['assert-fail'])
2055
        # make sure we got the real thing, not an error from somewhere else in
2056
        # the test framework
2057
        self.assertEquals('always fails', str(e))
2058
        # check that there's no traceback in the test log
2059
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
2060
            r'Traceback')
2061
2062
    def test_run_bzr_user_error_caught(self):
2063
        # Running bzr in blackbox mode, normal/expected/user errors should be
2064
        # caught in the regular way and turned into an error message plus exit
2065
        # code.
2066
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
2067
        self.assertEqual(out, '')
3146.4.7 by Aaron Bentley
Remove UNIX path assumption
2068
        self.assertContainsRe(err,
2069
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2070
2071
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2072
class TestTestLoader(tests.TestCase):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2073
    """Tests for the test loader."""
2074
2075
    def _get_loader_and_module(self):
2076
        """Gets a TestLoader and a module with one test in it."""
2077
        loader = TestUtil.TestLoader()
2078
        module = {}
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2079
        class Stub(tests.TestCase):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2080
            def test_foo(self):
2081
                pass
2082
        class MyModule(object):
2083
            pass
2084
        MyModule.a_class = Stub
2085
        module = MyModule()
2086
        return loader, module
2087
2088
    def test_module_no_load_tests_attribute_loads_classes(self):
2089
        loader, module = self._get_loader_and_module()
2090
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2091
2092
    def test_module_load_tests_attribute_gets_called(self):
2093
        loader, module = self._get_loader_and_module()
2094
        # 'self' is here because we're faking the module with a class. Regular
2095
        # load_tests do not need that :)
2096
        def load_tests(self, standard_tests, module, loader):
2097
            result = loader.suiteClass()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2098
            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``
2099
                result.addTests([test, test])
2100
            return result
2101
        # add a load_tests() method which multiplies the tests from the module.
2102
        module.__class__.load_tests = load_tests
2103
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2104
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2105
    def test_load_tests_from_module_name_smoke_test(self):
2106
        loader = TestUtil.TestLoader()
2107
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2108
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2109
                          _test_ids(suite))
2110
3302.7.8 by Vincent Ladeuil
Fix typos.
2111
    def test_load_tests_from_module_name_with_bogus_module_name(self):
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2112
        loader = TestUtil.TestLoader()
2113
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2114
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2115
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2116
class TestTestIdList(tests.TestCase):
2117
2118
    def _create_id_list(self, test_list):
2119
        return tests.TestIdList(test_list)
2120
2121
    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.
2122
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2123
        class Stub(tests.TestCase):
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
2124
            def test_foo(self):
2125
                pass
2126
2127
        def _create_test_id(id):
2128
            return lambda: id
2129
2130
        suite = TestUtil.TestSuite()
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2131
        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.
2132
            t  = Stub('test_foo')
2133
            t.id = _create_test_id(id)
2134
            suite.addTest(t)
2135
        return suite
2136
2137
    def _test_ids(self, test_suite):
2138
        """Get the ids for the tests in a test suite."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2139
        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.
2140
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2141
    def test_empty_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2142
        id_list = self._create_id_list([])
2143
        self.assertEquals({}, id_list.tests)
2144
        self.assertEquals({}, id_list.modules)
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2145
2146
    def test_valid_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2147
        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
2148
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2149
             'mod1.func1', 'mod1.cl2.meth2',
2150
             'mod1.submod1',
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
2151
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2152
             ])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2153
        self.assertTrue(id_list.refers_to('mod1'))
2154
        self.assertTrue(id_list.refers_to('mod1.submod1'))
2155
        self.assertTrue(id_list.refers_to('mod1.submod2'))
2156
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2157
        self.assertTrue(id_list.includes('mod1.submod1'))
2158
        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.
2159
2160
    def test_bad_chars_in_params(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2161
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2162
        self.assertTrue(id_list.refers_to('mod1'))
2163
        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
2164
2165
    def test_module_used(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2166
        id_list = self._create_id_list(['mod.class.meth'])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2167
        self.assertTrue(id_list.refers_to('mod'))
2168
        self.assertTrue(id_list.refers_to('mod.class'))
2169
        self.assertTrue(id_list.refers_to('mod.class.meth'))
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2170
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2171
    def test_test_suite_matches_id_list_with_unknown(self):
2172
        loader = TestUtil.TestLoader()
3302.7.6 by Vincent Ladeuil
Catch up with loadTestsFromModuleName use.
2173
        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
2174
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2175
                     'bogus']
2176
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2177
        self.assertEquals(['bogus'], not_found)
2178
        self.assertEquals([], duplicates)
2179
2180
    def test_suite_matches_id_list_with_duplicates(self):
2181
        loader = TestUtil.TestLoader()
3302.7.6 by Vincent Ladeuil
Catch up with loadTestsFromModuleName use.
2182
        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
2183
        dupes = loader.suiteClass()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2184
        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
2185
            dupes.addTest(test)
2186
            dupes.addTest(test) # Add it again
2187
2188
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2189
        not_found, duplicates = tests.suite_matches_id_list(
2190
            dupes, test_list)
2191
        self.assertEquals([], not_found)
2192
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2193
                          duplicates)
2194
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2195
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2196
class TestTestSuite(tests.TestCase):
2197
2198
    def test_test_suite(self):
2199
        # This test is slow, so we do a single test with one test in each
2200
        # category
2201
        test_list = [
2202
            # testmod_names
2203
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2204
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2205
            # transport implementations
2206
            'bzrlib.tests.test_transport_implementations.TransportTests'
2207
            '.test_abspath(LocalURLServer)',
2208
            # modules_to_doctest
2209
            'bzrlib.timestamp.format_highres_date',
2210
            # plugins can't be tested that way since selftest may be run with
2211
            # --no-plugins
2212
            ]
2213
        suite = tests.test_suite(test_list)
2214
        self.assertEquals(test_list, _test_ids(suite))
2215
2216
    def test_test_suite_list_and_start(self):
2217
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2218
        suite = tests.test_suite(test_list,
2219
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
2220
        # test_test_suite_list_and_start is not included 
2221
        self.assertEquals(test_list, _test_ids(suite))
2222
2223
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2224
class TestLoadTestIdList(tests.TestCaseInTempDir):
2225
2226
    def _create_test_list_file(self, file_name, content):
2227
        fl = open(file_name, 'wt')
2228
        fl.write(content)
2229
        fl.close()
2230
2231
    def test_load_unknown(self):
2232
        self.assertRaises(errors.NoSuchFile,
2233
                          tests.load_test_id_list, 'i_do_not_exist')
2234
2235
    def test_load_test_list(self):
2236
        test_list_fname = 'test.list'
2237
        self._create_test_list_file(test_list_fname,
2238
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2239
        tlist = tests.load_test_id_list(test_list_fname)
2240
        self.assertEquals(2, len(tlist))
2241
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2242
        self.assertEquals('mod2.cl2.meth2', tlist[1])
2243
2244
    def test_load_dirty_file(self):
2245
        test_list_fname = 'test.list'
2246
        self._create_test_list_file(test_list_fname,
2247
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
2248
                                    'bar baz\n')
2249
        tlist = tests.load_test_id_list(test_list_fname)
2250
        self.assertEquals(4, len(tlist))
2251
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2252
        self.assertEquals('', tlist[1])
2253
        self.assertEquals('mod2.cl2.meth2', tlist[2])
2254
        self.assertEquals('bar baz', tlist[3])
2255
2256
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
2257
class TestFilteredByModuleTestLoader(tests.TestCase):
2258
2259
    def _create_loader(self, test_list):
2260
        id_filter = tests.TestIdList(test_list)
3302.8.4 by Vincent Ladeuil
Cosmetic changes.
2261
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
2262
        return loader
2263
2264
    def test_load_tests(self):
2265
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2266
        loader = self._create_loader(test_list)
2267
2268
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2269
        self.assertEquals(test_list, _test_ids(suite))
2270
2271
    def test_exclude_tests(self):
2272
        test_list = ['bogus']
2273
        loader = self._create_loader(test_list)
2274
2275
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2276
        self.assertEquals([], _test_ids(suite))
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2277
2278
2279
class TestFilteredByNameStartTestLoader(tests.TestCase):
2280
2281
    def _create_loader(self, name_start):
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
2282
        def needs_module(name):
2283
            return name.startswith(name_start) or name_start.startswith(name)
2284
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2285
        return loader
2286
2287
    def test_load_tests(self):
2288
        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.
2289
        loader = self._create_loader('bzrlib.tests.test_samp')
2290
2291
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2292
        self.assertEquals(test_list, _test_ids(suite))
2293
2294
    def test_load_tests_inside_module(self):
2295
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2296
        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.
2297
2298
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2299
        self.assertEquals(test_list, _test_ids(suite))
2300
2301
    def test_exclude_tests(self):
2302
        test_list = ['bogus']
2303
        loader = self._create_loader('bogus')
2304
2305
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2306
        self.assertEquals([], _test_ids(suite))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
2307
2308
2309
class TestTestPrefixRegistry(tests.TestCase):
2310
2311
    def _get_registry(self):
2312
        tp_registry = tests.TestPrefixAliasRegistry()
2313
        return tp_registry
2314
2315
    def test_register_new_prefix(self):
2316
        tpr = self._get_registry()
2317
        tpr.register('foo', 'fff.ooo.ooo')
2318
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2319
2320
    def test_register_existing_prefix(self):
2321
        tpr = self._get_registry()
2322
        tpr.register('bar', 'bbb.aaa.rrr')
2323
        tpr.register('bar', 'bBB.aAA.rRR')
2324
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2325
        self.assertContainsRe(self._get_log(keep_log_file=True),
2326
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2327
2328
    def test_get_unknown_prefix(self):
2329
        tpr = self._get_registry()
2330
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2331
2332
    def test_resolve_prefix(self):
2333
        tpr = self._get_registry()
2334
        tpr.register('bar', 'bb.aa.rr')
2335
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2336
2337
    def test_resolve_unknown_alias(self):
2338
        tpr = self._get_registry()
2339
        self.assertRaises(errors.BzrCommandError,
2340
                          tpr.resolve_alias, 'I am not a prefix')
2341
2342
    def test_predefined_prefixes(self):
2343
        tpr = tests.test_prefix_alias_registry
2344
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2345
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2346
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2347
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2348
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2349
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
2350
2351
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2352
class TestRunSuite(tests.TestCase):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
2353
2354
    def test_runner_class(self):
2355
        """run_suite accepts and uses a runner_class keyword argument."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2356
        class Stub(tests.TestCase):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
2357
            def test_foo(self):
2358
                pass
2359
        suite = Stub("test_foo")
2360
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2361
        class MyRunner(tests.TextTestRunner):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
2362
            def run(self, test):
2363
                calls.append(test)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2364
                return tests.ExtendedTestResult(self.stream, self.descriptions,
2365
                                                self.verbosity)
2366
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
2367
        self.assertEqual(calls, [suite])
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
2368
2369
    def test_done(self):
2370
        """run_suite should call result.done()"""
2371
        self.calls = 0
2372
        def one_more_call(): self.calls += 1
2373
        def test_function():
2374
            pass
2375
        test = unittest.FunctionTestCase(test_function)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2376
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
2377
            def done(self): one_more_call()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2378
        class MyRunner(tests.TextTestRunner):
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
2379
            def run(self, test):
2380
                return InstrumentedTestResult(self.stream, self.descriptions,
2381
                                              self.verbosity)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2382
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
2383
        self.assertEquals(1, self.calls)