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