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