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