/brz/remove-bazaar

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