/brz/remove-bazaar

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