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