/brz/remove-bazaar

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