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