~bzr-pqm/bzr/bzr.dev

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