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