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