/brz/remove-bazaar

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