/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1
# Copyright (C) 2005-2013, 2016 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
5340.15.1 by John Arbash Meinel
supersede exc-info branch
19
import gc
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
20
import doctest
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
5412.1.3 by Martin
Add tests for test case thread leak detection
24
import threading
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
25
import time
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
26
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.
27
import warnings
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
28
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
29
from testtools import (
30
    ExtendedToOriginalDecorator,
31
    MultiTestResult,
32
    )
5050.33.2 by Andrew Bennetts
More robust fix for TestCase cloning, this time with tests.
33
from testtools.content import Content
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]).
34
from testtools.content_type import ContentType
35
from testtools.matchers import (
36
    DocTestMatches,
37
    Equals,
38
    )
5340.15.1 by John Arbash Meinel
supersede exc-info branch
39
import testtools.testresult.doubles
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).
40
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
41
import breezy
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
42
from .. import (
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
43
    branchbuilder,
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
44
    controldir,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
45
    errors,
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
46
    hooks,
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
47
    lockdir,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
48
    memorytree,
49
    osutils,
50
    repository,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
51
    symbol_versioning,
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
52
    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.
53
    transport,
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
54
    workingtree,
6670.4.1 by Jelmer Vernooij
Update imports.
55
    )
56
from ..bzr import (
57
    bzrdir,
6670.4.14 by Jelmer Vernooij
Move remote to breezy.bzr.
58
    remote,
5816.5.4 by Jelmer Vernooij
Merge bzr.dev.
59
    workingtree_3,
5816.2.4 by Jelmer Vernooij
Fix some imports.
60
    workingtree_4,
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
61
    )
6670.4.5 by Jelmer Vernooij
Move breezy.repofmt contents to breezy.bzr.
62
from ..bzr import (
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
63
    groupcompress_repo,
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
64
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
65
from ..sixish import (
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
66
    StringIO,
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
67
    text_type,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
68
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
69
from ..symbol_versioning import (
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
70
    deprecated_function,
71
    deprecated_in,
72
    deprecated_method,
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
73
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
74
from . import (
4913.2.17 by John Arbash Meinel
Found another paramiko dependent
75
    features,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
76
    test_lsprof,
5017.3.24 by Vincent Ladeuil
selftest -s bt.test_selftest passing
77
    test_server,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
78
    TestUtil,
79
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
80
from ..trace import note, mutter
81
from ..transport import memory
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
82
83
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
84
def _test_ids(test_suite):
85
    """Get the ids for the tests in a test suite."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
86
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
87
88
89
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.
90
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
91
    def test_logging(self):
92
        """Test logs are captured when a test fails."""
93
        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]).
94
        details = self.getDetails()
95
        log = details['log']
96
        self.assertThat(log.content_type, Equals(ContentType(
97
            "text", "plain", {"charset": "utf8"})))
4794.1.15 by Robert Collins
Review feedback.
98
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
99
        self.assertThat(self.get_log(),
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
100
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
101
102
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
103
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.
104
105
    def test_unicode_paths(self):
5967.12.3 by Martin Pool
Unify duplicated UnicodeFilename and _PosixPermissionsFeature
106
        self.requireFeature(features.UnicodeFilenameFeature)
3287.20.2 by John Arbash Meinel
Raise a clear error about the offending filename when there is a filename with bad characters.
107
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.
108
        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.
109
        self.build_tree_contents([(filename, 'contents of hello')])
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
110
        self.assertPathExists(filename)
1526.1.3 by Robert Collins
Merge from upstream.
111
112
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
113
class TestClassesAvailable(tests.TestCase):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
114
    """As a convenience we expose Test* classes from breezy.tests"""
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
115
116
    def test_test_case(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
117
        from . import TestCase
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
118
119
    def test_test_loader(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
120
        from . import TestLoader
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
121
122
    def test_test_suite(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
123
        from . import TestSuite
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
124
125
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
126
class TestTransportScenarios(tests.TestCase):
1530.1.21 by Robert Collins
Review feedback fixes.
127
    """A group of tests that test the transport implementation adaption core.
128
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
129
    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
130
    transports.
131
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
132
    This will be generalised in the future which is why it is in this
1530.1.21 by Robert Collins
Review feedback fixes.
133
    test file even though it is specific to transport tests at the moment.
134
    """
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
135
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.
136
    def test_get_transport_permutations(self):
3455.1.1 by Vincent Ladeuil
Fix typos in comments.
137
        # 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.
138
        # 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.
139
        class MockModule(object):
140
            def get_test_permutations(self):
141
                return sample_permutation
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
142
        sample_permutation = [(1, 2), (3, 4)]
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
143
        from .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.
144
        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.
145
                         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.
146
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
147
    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.
148
        # this checks that the scenario generator returns as many permutations
149
        # as there are in all the registered transport modules - we assume if
150
        # this matches its probably doing the right thing especially in
151
        # combination with the tests for setting the right classes below.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
152
        from .per_transport import transport_test_permutations
153
        from ..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.
154
        modules = _get_transport_modules()
155
        permutation_count = 0
156
        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.
157
            try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
158
                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.
159
                    (module + ".get_test_permutations").split('.')[1:],
160
                     __import__(module))())
161
            except errors.DependencyNotPresent:
162
                pass
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
163
        scenarios = transport_test_permutations()
164
        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.
165
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
166
    def test_scenarios_include_transport_class(self):
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
167
        # This test used to know about all the possible transports and the
168
        # order they were returned but that seems overly brittle (mbp
169
        # 20060307)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
170
        from .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.
171
        scenarios = transport_test_permutations()
1540.3.21 by Martin Pool
Trim test for TestTransportProviderAdapter to be less dependent on
172
        # there are at least that many builtin transports
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
173
        self.assertTrue(len(scenarios) > 6)
174
        one_scenario = scenarios[0]
175
        self.assertIsInstance(one_scenario[0], str)
176
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
177
                                   breezy.transport.Transport))
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
178
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
179
                                   breezy.transport.Server))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
180
181
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
182
class TestBranchScenarios(tests.TestCase):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
183
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
184
    def test_scenarios(self):
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
185
        # check that constructor parameters are passed through to the adapted
186
        # test.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
187
        from .per_branch import make_scenarios
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
188
        server1 = "a"
189
        server2 = "b"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
190
        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.
191
        scenarios = make_scenarios(server1, server2, formats)
192
        self.assertEqual(2, len(scenarios))
2553.2.6 by Robert Collins
And overhaul BranchTestProviderAdapter too.
193
        self.assertEqual([
194
            ('str',
195
             {'branch_format': 'c',
196
              'bzrdir_format': 'C',
197
              'transport_readonly_server': 'b',
198
              'transport_server': 'a'}),
199
            ('str',
200
             {'branch_format': 'd',
201
              'bzrdir_format': 'D',
202
              'transport_readonly_server': 'b',
203
              '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.
204
            scenarios)
205
206
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
207
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.
208
209
    def test_scenarios(self):
1534.4.39 by Robert Collins
Basic BzrDir support.
210
        # check that constructor parameters are passed through to the adapted
211
        # test.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
212
        from .per_controldir import make_scenarios
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
213
        vfs_factory = "v"
1534.4.39 by Robert Collins
Basic BzrDir support.
214
        server1 = "a"
215
        server2 = "b"
216
        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.
217
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
2553.2.7 by Robert Collins
And overhaul BzrDirTestProviderAdapter too.
218
        self.assertEqual([
219
            ('str',
220
             {'bzrdir_format': 'c',
221
              'transport_readonly_server': 'b',
222
              'transport_server': 'a',
223
              'vfs_transport_factory': 'v'}),
224
            ('str',
225
             {'bzrdir_format': 'd',
226
              'transport_readonly_server': 'b',
227
              'transport_server': 'a',
228
              '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.
229
            scenarios)
230
231
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
232
class TestRepositoryScenarios(tests.TestCase):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
233
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
234
    def test_formats_to_scenarios(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
235
        from .per_repository import formats_to_scenarios
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
236
        formats = [("(c)", remote.RemoteRepositoryFormat()),
237
                   ("(d)", repository.format_registry.get(
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
238
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
239
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
240
            None)
241
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
242
            vfs_transport_factory="vfs")
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
243
        # no_vfs generate scenarios without vfs_transport_factory
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
244
        expected = [
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
245
            ('RemoteRepositoryFormat(c)',
246
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
247
              'repository_format': remote.RemoteRepositoryFormat(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
248
              'transport_readonly_server': 'readonly',
249
              'transport_server': 'server'}),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
250
            ('RepositoryFormat2a(d)',
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
251
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
252
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
253
              'transport_readonly_server': 'readonly',
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
254
              'transport_server': 'server'})]
255
        self.assertEqual(expected, no_vfs_scenarios)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
256
        self.assertEqual([
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',
262
              'vfs_transport_factory': 'vfs'}),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
263
            ('RepositoryFormat2a(d)',
3543.1.4 by Martin Pool
test_formats_to_scenarios uses real format objects
264
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
4599.4.16 by Robert Collins
Update test_selftest for the 2a default format change.
265
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
266
              'transport_readonly_server': 'readonly',
267
              'transport_server': 'server',
268
              'vfs_transport_factory': 'vfs'})],
3221.10.5 by Robert Collins
Update repository parameterisation tests to match refactoring.
269
            vfs_scenarios)
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
270
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
271
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
272
class TestTestScenarioApplication(tests.TestCase):
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
273
    """Tests for the test adaption facilities."""
274
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
275
    def test_apply_scenario(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
276
        from breezy.tests import apply_scenario
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
277
        input_test = TestTestScenarioApplication("test_apply_scenario")
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
278
        # 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.
279
        adapted_test1 = apply_scenario(input_test,
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
280
            ("new id",
281
            {"bzrdir_format":"bzr_format",
282
             "repository_format":"repo_fmt",
283
             "transport_server":"transport_server",
284
             "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.
285
        adapted_test2 = apply_scenario(input_test,
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
286
            ("new id 2", {"bzrdir_format":None}))
287
        # input_test should have been altered.
288
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
289
        # the new tests are mutually incompatible, ensuring it has
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
290
        # made new ones, and unspecified elements in the scenario
291
        # should not have been altered.
292
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
293
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
294
        self.assertEqual("transport_server", adapted_test1.transport_server)
295
        self.assertEqual("readonly-server",
296
            adapted_test1.transport_readonly_server)
297
        self.assertEqual(
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
298
            "breezy.tests.test_selftest.TestTestScenarioApplication."
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
299
            "test_apply_scenario(new id)",
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
300
            adapted_test1.id())
301
        self.assertEqual(None, adapted_test2.bzrdir_format)
302
        self.assertEqual(
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
303
            "breezy.tests.test_selftest.TestTestScenarioApplication."
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
304
            "test_apply_scenario(new id 2)",
2553.2.1 by Robert Collins
Overhaul RepositoryTestAdapter to be cleaner and more modular.
305
            adapted_test2.id())
2018.5.64 by Robert Collins
Allow Repository tests to be backed onto a specific VFS as needed.
306
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
307
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
308
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.
309
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
310
    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.
311
        # check that constructor parameters are passed through to the adapted
312
        # test.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
313
        from .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.
314
        server1 = "a"
315
        server2 = "b"
5050.32.2 by Andrew Bennetts
Fix test_selftest.TestInterRepositoryScenarios to expect the extra_setup field in the format tuples.
316
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
317
        scenarios = make_scenarios(server1, server2, formats)
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
318
        self.assertEqual([
4476.3.85 by Andrew Bennetts
Update TestInterRepositoryScenarios.test_scenarios for change to per_interrepo make_scenarios.
319
            ('C0,str,str',
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
320
             {'repository_format': 'C1',
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
321
              'repository_format_to': 'C2',
322
              'transport_readonly_server': 'b',
5050.32.2 by Andrew Bennetts
Fix test_selftest.TestInterRepositoryScenarios to expect the extra_setup field in the format tuples.
323
              'transport_server': 'a',
324
              'extra_setup': 'C3'}),
4476.3.85 by Andrew Bennetts
Update TestInterRepositoryScenarios.test_scenarios for change to per_interrepo make_scenarios.
325
            ('D0,str,str',
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
326
             {'repository_format': 'D1',
2553.2.4 by Robert Collins
Treat InterRepositoryTestProviderAdapter like RepositoryTestProviderAdapter
327
              'repository_format_to': 'D2',
328
              'transport_readonly_server': 'b',
5050.32.2 by Andrew Bennetts
Fix test_selftest.TestInterRepositoryScenarios to expect the extra_setup field in the format tuples.
329
              'transport_server': 'a',
330
              'extra_setup': 'D3'})],
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
331
            scenarios)
332
333
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
334
class TestWorkingTreeScenarios(tests.TestCase):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
335
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
336
    def test_scenarios(self):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
337
        # check that constructor parameters are passed through to the adapted
338
        # test.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
339
        from .per_workingtree import make_scenarios
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
340
        server1 = "a"
341
        server2 = "b"
5816.2.4 by Jelmer Vernooij
Fix some imports.
342
        formats = [workingtree_4.WorkingTreeFormat4(),
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
343
                   workingtree_3.WorkingTreeFormat3(),
344
                   workingtree_4.WorkingTreeFormat6()]
345
        scenarios = make_scenarios(server1, server2, formats,
346
            remote_server='c', remote_readonly_server='d',
347
            remote_backing_server='e')
2553.2.10 by Robert Collins
And overhaul WorkingTreeTestProviderAdapter too.
348
        self.assertEqual([
5582.10.30 by Jelmer Vernooij
Remove more weave_fmt imports.
349
            ('WorkingTreeFormat4',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
350
             {'bzrdir_format': formats[0]._matchingcontroldir,
3543.1.8 by Martin Pool
Update more scenario tests to use real format objects.
351
              'transport_readonly_server': 'b',
352
              'transport_server': 'a',
353
              'workingtree_format': formats[0]}),
354
            ('WorkingTreeFormat3',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
355
             {'bzrdir_format': formats[1]._matchingcontroldir,
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
356
              'transport_readonly_server': 'b',
357
              'transport_server': 'a',
358
              'workingtree_format': formats[1]}),
359
            ('WorkingTreeFormat6',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
360
             {'bzrdir_format': formats[2]._matchingcontroldir,
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
361
              'transport_readonly_server': 'b',
362
              'transport_server': 'a',
363
              'workingtree_format': formats[2]}),
364
            ('WorkingTreeFormat6,remote',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
365
             {'bzrdir_format': formats[2]._matchingcontroldir,
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
366
              'repo_is_remote': True,
367
              'transport_readonly_server': 'd',
368
              'transport_server': 'c',
369
              'vfs_transport_factory': 'e',
370
              'workingtree_format': formats[2]}),
371
            ], scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
372
373
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
374
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.
375
376
    def test_scenarios(self):
377
        # the tree implementation scenario generator is meant to setup one
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
378
        # instance for each working tree format, one additional instance
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
379
        # that will use the default wt format, but create a revision tree for
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
380
        # the tests, and one more that uses the default wt format as a
381
        # lightweight checkout of a remote repository.  This means that the wt
382
        # ones should have the workingtree_to_test_tree attribute set to
383
        # 'return_parameter' and the revision one set to
384
        # revision_tree_from_workingtree.
1852.6.1 by Robert Collins
Start tree implementation tests.
385
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
386
        from .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.
387
            _dirstate_tree_from_workingtree,
388
            make_scenarios,
389
            preview_tree_pre,
390
            preview_tree_post,
1852.6.1 by Robert Collins
Start tree implementation tests.
391
            return_parameter,
392
            revision_tree_from_workingtree
393
            )
394
        server1 = "a"
395
        server2 = "b"
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
396
        smart_server = test_server.SmartTCPServer_for_testing
397
        smart_readonly_server = test_server.ReadonlySmartTCPServer_for_testing
398
        mem_server = memory.MemoryServer
5816.2.4 by Jelmer Vernooij
Fix some imports.
399
        formats = [workingtree_4.WorkingTreeFormat4(),
5816.5.4 by Jelmer Vernooij
Merge bzr.dev.
400
                   workingtree_3.WorkingTreeFormat3(),]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
401
        scenarios = make_scenarios(server1, server2, formats)
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
402
        self.assertEqual(8, len(scenarios))
5662.3.5 by Jelmer Vernooij
Fix retrieval of default working tree format in test.
403
        default_wt_format = workingtree.format_registry.get_default()
5816.2.4 by Jelmer Vernooij
Fix some imports.
404
        wt4_format = workingtree_4.WorkingTreeFormat4()
405
        wt5_format = workingtree_4.WorkingTreeFormat5()
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
406
        wt6_format = workingtree_4.WorkingTreeFormat6()
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
407
        expected_scenarios = [
5669.2.1 by Jelmer Vernooij
Avoid the use of weave formats in test_selftest.
408
            ('WorkingTreeFormat4',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
409
             {'bzrdir_format': formats[0]._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
410
              'transport_readonly_server': 'b',
411
              'transport_server': 'a',
412
              'workingtree_format': formats[0],
413
              '_workingtree_to_test_tree': return_parameter,
414
              }),
415
            ('WorkingTreeFormat3',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
416
             {'bzrdir_format': formats[1]._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
417
              'transport_readonly_server': 'b',
418
              'transport_server': 'a',
419
              'workingtree_format': formats[1],
420
              '_workingtree_to_test_tree': return_parameter,
421
             }),
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
422
            ('WorkingTreeFormat6,remote',
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
423
             {'bzrdir_format': wt6_format._matchingcontroldir,
6437.70.16 by John Arbash Meinel
per_tree re-uses the per_workingtree scenarios.
424
              'repo_is_remote': True,
425
              'transport_readonly_server': smart_readonly_server,
426
              'transport_server': smart_server,
427
              'vfs_transport_factory': mem_server,
428
              'workingtree_format': wt6_format,
429
              '_workingtree_to_test_tree': return_parameter,
430
             }),
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
431
            ('RevisionTree',
432
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
433
              'bzrdir_format': default_wt_format._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
434
              'transport_readonly_server': 'b',
435
              'transport_server': 'a',
436
              'workingtree_format': default_wt_format,
437
             }),
438
            ('DirStateRevisionTree,WT4',
439
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
440
              'bzrdir_format': wt4_format._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
441
              'transport_readonly_server': 'b',
442
              'transport_server': 'a',
443
              'workingtree_format': wt4_format,
444
             }),
445
            ('DirStateRevisionTree,WT5',
446
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
447
              'bzrdir_format': wt5_format._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
448
              'transport_readonly_server': 'b',
449
              'transport_server': 'a',
450
              'workingtree_format': wt5_format,
451
             }),
452
            ('PreviewTree',
453
             {'_workingtree_to_test_tree': preview_tree_pre,
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
454
              'bzrdir_format': default_wt_format._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
455
              'transport_readonly_server': 'b',
456
              'transport_server': 'a',
457
              'workingtree_format': default_wt_format}),
458
            ('PreviewTreePost',
459
             {'_workingtree_to_test_tree': preview_tree_post,
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
460
              'bzrdir_format': default_wt_format._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
461
              'transport_readonly_server': 'b',
462
              'transport_server': 'a',
463
              'workingtree_format': default_wt_format}),
464
             ]
465
        self.assertEqual(expected_scenarios, scenarios)
466
467
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
468
class TestInterTreeScenarios(tests.TestCase):
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
469
    """A group of tests that test the InterTreeTestAdapter."""
470
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
471
    def test_scenarios(self):
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
472
        # check that constructor parameters are passed through to the adapted
473
        # test.
474
        # for InterTree tests we want the machinery to bring up two trees in
475
        # each instance: the base one, and the one we are interacting with.
476
        # because each optimiser can be direction specific, we need to test
477
        # each optimiser in its chosen direction.
478
        # unlike the TestProviderAdapter we dont want to automatically add a
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
479
        # 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.
480
        # ones to add.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
481
        from .per_tree import (
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
482
            return_parameter,
483
            )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
484
        from .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.
485
            make_scenarios,
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
486
            )
6670.4.3 by Jelmer Vernooij
Fix more imports.
487
        from ..bzr.workingtree_3 import WorkingTreeFormat3
488
        from ..bzr.workingtree_4 import WorkingTreeFormat4
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
489
        input_test = TestInterTreeScenarios(
490
            "test_scenarios")
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
491
        server1 = "a"
492
        server2 = "b"
5582.10.30 by Jelmer Vernooij
Remove more weave_fmt imports.
493
        format1 = WorkingTreeFormat4()
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
494
        format2 = WorkingTreeFormat3()
3696.4.19 by Robert Collins
Update missed test for InterTree test generation.
495
        formats = [("1", str, format1, format2, "converter1"),
496
            ("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.
497
        scenarios = make_scenarios(server1, server2, formats)
498
        self.assertEqual(2, len(scenarios))
499
        expected_scenarios = [
500
            ("1", {
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
501
                "bzrdir_format": format1._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
502
                "intertree_class": formats[0][1],
503
                "workingtree_format": formats[0][2],
504
                "workingtree_format_to": formats[0][3],
505
                "mutable_trees_to_test_trees": formats[0][4],
506
                "_workingtree_to_test_tree": return_parameter,
507
                "transport_server": server1,
508
                "transport_readonly_server": server2,
509
                }),
510
            ("2", {
6746.2.1 by Jelmer Vernooij
Rename matchingbzrdir to matchingcontroldir.
511
                "bzrdir_format": format2._matchingcontroldir,
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
512
                "intertree_class": formats[1][1],
513
                "workingtree_format": formats[1][2],
514
                "workingtree_format_to": formats[1][3],
515
                "mutable_trees_to_test_trees": formats[1][4],
516
                "_workingtree_to_test_tree": return_parameter,
517
                "transport_server": server1,
518
                "transport_readonly_server": server2,
519
                }),
520
            ]
521
        self.assertEqual(scenarios, expected_scenarios)
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
522
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
523
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
524
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
525
526
    def test_home_is_not_working(self):
527
        self.assertNotEqual(self.test_dir, self.test_home_dir)
528
        cwd = osutils.getcwd()
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
529
        self.assertIsSameRealPath(self.test_dir, cwd)
530
        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
531
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
532
    def test_assertEqualStat_equal(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
533
        from .test_dirstate import _FakeStat
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
534
        self.build_tree(["foo"])
535
        real = os.lstat("foo")
536
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
537
            real.st_dev, real.st_ino, real.st_mode)
538
        self.assertEqualStat(real, fake)
539
540
    def test_assertEqualStat_notequal(self):
4789.26.10 by John Arbash Meinel
If the filesystem has low resolution build_tree(['a', 'b'])
541
        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.
542
        self.assertRaises(AssertionError, self.assertEqualStat,
4789.26.10 by John Arbash Meinel
If the filesystem has low resolution build_tree(['a', 'b'])
543
            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.
544
5784.1.2 by Martin Pool
Deprecate, and test, failIfExists and failUnlessExists
545
    def test_assertPathExists(self):
546
        self.assertPathExists('.')
547
        self.build_tree(['foo/', 'foo/bar'])
548
        self.assertPathExists('foo/bar')
549
        self.assertPathDoesNotExist('foo/foo')
550
1987.1.1 by John Arbash Meinel
Update the test suite to put HOME in a different directory
551
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
552
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
553
554
    def test_home_is_non_existant_dir_under_root(self):
555
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
556
557
        This is because TestCaseWithMemoryTransport is for tests that do not
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
558
        need any disk resources: they should be hooked into breezy in such a
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
559
        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
560
        few tests should need to do that), and having a missing dir as home is
561
        an effective way to ensure that this is the case.
562
        """
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
563
        self.assertIsSameRealPath(
564
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
565
            self.test_home_dir)
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
566
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
567
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
568
    def test_cwd_is_TEST_ROOT(self):
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
569
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
570
        cwd = osutils.getcwd()
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
571
        self.assertIsSameRealPath(self.test_dir, cwd)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
572
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
573
    def test_BRZ_HOME_and_HOME_are_bytestrings(self):
574
        """The $BRZ_HOME and $HOME environment variables should not be unicode.
4815.2.5 by Michael Hudson
NEWS, comment in test
575
4815.2.6 by Michael Hudson
final tweak
576
        See https://bugs.launchpad.net/bzr/+bug/464174
4815.2.3 by Michael Hudson
add test
577
        """
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
578
        self.assertIsInstance(os.environ['BRZ_HOME'], str)
4815.2.3 by Michael Hudson
add test
579
        self.assertIsInstance(os.environ['HOME'], str)
580
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
581
    def test_make_branch_and_memory_tree(self):
582
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
583
584
        This is hard to comprehensively robustly test, so we settle for making
585
        a branch and checking no directory was created at its relpath.
586
        """
587
        tree = self.make_branch_and_memory_tree('dir')
2227.2.2 by v.ladeuil+lp at free
Cleanup.
588
        # Guard against regression into MemoryTransport leaking
589
        # files to disk instead of keeping them in memory.
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
590
        self.assertFalse(osutils.lexists('dir'))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
591
        self.assertIsInstance(tree, memorytree.MemoryTree)
592
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
593
    def test_make_branch_and_memory_tree_with_format(self):
594
        """make_branch_and_memory_tree should accept a format option."""
595
        format = bzrdir.BzrDirMetaFormat1()
5669.2.1 by Jelmer Vernooij
Avoid the use of weave formats in test_selftest.
596
        format.repository_format = repository.format_registry.get_default()
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
597
        tree = self.make_branch_and_memory_tree('dir', format=format)
2227.2.2 by v.ladeuil+lp at free
Cleanup.
598
        # Guard against regression into MemoryTransport leaking
599
        # files to disk instead of keeping them in memory.
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
600
        self.assertFalse(osutils.lexists('dir'))
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
601
        self.assertIsInstance(tree, memorytree.MemoryTree)
602
        self.assertEqual(format.repository_format.__class__,
603
            tree.branch.repository._format.__class__)
604
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
605
    def test_make_branch_builder(self):
606
        builder = self.make_branch_builder('dir')
607
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
608
        # Guard against regression into MemoryTransport leaking
609
        # files to disk instead of keeping them in memory.
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
610
        self.assertFalse(osutils.lexists('dir'))
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
611
612
    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.
613
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
614
        # that the format objects are used.
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
615
        format = bzrdir.BzrDirMetaFormat1()
5669.2.1 by Jelmer Vernooij
Avoid the use of weave formats in test_selftest.
616
        repo_format = repository.format_registry.get_default()
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
617
        format.repository_format = repo_format
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
618
        builder = self.make_branch_builder('dir', format=format)
619
        the_branch = builder.get_branch()
620
        # Guard against regression into MemoryTransport leaking
621
        # files to disk instead of keeping them in memory.
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
622
        self.assertFalse(osutils.lexists('dir'))
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
623
        self.assertEqual(format.repository_format.__class__,
624
                         the_branch.repository._format.__class__)
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
625
        self.assertEqual(repo_format.get_format_string(),
626
                         self.get_transport().get_bytes(
627
                            'dir/.bzr/repository/format'))
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
628
629
    def test_make_branch_builder_with_format_name(self):
630
        builder = self.make_branch_builder('dir', format='knit')
631
        the_branch = builder.get_branch()
632
        # Guard against regression into MemoryTransport leaking
633
        # files to disk instead of keeping them in memory.
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
634
        self.assertFalse(osutils.lexists('dir'))
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
635
        dir_format = controldir.format_registry.make_controldir('knit')
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
636
        self.assertEqual(dir_format.repository_format.__class__,
637
                         the_branch.repository._format.__class__)
3567.4.18 by John Arbash Meinel
Apply the review changes from Martin to the exact patch he approved.
638
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
639
                         self.get_transport().get_bytes(
640
                            'dir/.bzr/repository/format'))
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
641
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
642
    def test_dangling_locks_cause_failures(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
643
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
644
            def test_function(self):
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
645
                t = self.get_transport_from_path('.')
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
646
                l = lockdir.LockDir(t, 'lock')
647
                l.create()
648
                l.attempt_lock()
649
        test = TestDanglingLock('test_function')
4314.2.1 by Robert Collins
Update lock debugging support patch.
650
        result = test.run()
5223.2.1 by Robert Collins
Selftest was failing with testtools 0.9.3, which caused an
651
        total_failures = result.errors + result.failures
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
652
        if self._lock_check_thorough:
4797.70.1 by Vincent Ladeuil
Skip chmodbits dependent tests when running as root
653
            self.assertEqual(1, len(total_failures))
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
654
        else:
655
            # When _lock_check_thorough is disabled, then we don't trigger a
656
            # failure
4797.70.1 by Vincent Ladeuil
Skip chmodbits dependent tests when running as root
657
            self.assertEqual(0, len(total_failures))
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
658
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
659
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
660
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
661
    """Tests for the convenience functions TestCaseWithTransport introduces."""
662
663
    def test_get_readonly_url_none(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
664
        from ..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.
665
        self.vfs_transport_factory = memory.MemoryServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
666
        self.transport_readonly_server = None
667
        # calling get_readonly_transport() constructs a decorator on the url
668
        # for the server
669
        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.
670
        url2 = self.get_readonly_url('foo/bar')
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
671
        t = transport.get_transport_from_url(url)
672
        t2 = transport.get_transport_from_url(url2)
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
673
        self.assertIsInstance(t, ReadonlyTransportDecorator)
674
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
675
        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.
676
677
    def test_get_readonly_url_http(self):
6625 by Jelmer Vernooij
Fix relative import.
678
        from .http_server import HttpServer
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
679
        from ..transport.http import HttpTransportBase
5017.3.24 by Vincent Ladeuil
selftest -s bt.test_selftest passing
680
        self.transport_server = test_server.LocalURLServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
681
        self.transport_readonly_server = HttpServer
682
        # calling get_readonly_transport() gives us a HTTP server instance.
683
        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.
684
        url2 = self.get_readonly_url('foo/bar')
1540.3.6 by Martin Pool
[merge] update from bzr.dev
685
        # the transport returned may be any HttpTransportBase subclass
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
686
        t = transport.get_transport_from_url(url)
687
        t2 = transport.get_transport_from_url(url2)
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
688
        self.assertIsInstance(t, HttpTransportBase)
689
        self.assertIsInstance(t2, HttpTransportBase)
1534.4.11 by Robert Collins
Convert test_open_containing from being a Remote test to being the more accurate Chrooted test.
690
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
1534.4.31 by Robert Collins
cleanedup test_outside_wt
691
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
692
    def test_is_directory(self):
693
        """Test assertIsDirectory assertion"""
694
        t = self.get_transport()
695
        self.build_tree(['a_dir/', 'a_file'], transport=t)
696
        self.assertIsDirectory('a_dir', t)
697
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
698
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
1534.4.31 by Robert Collins
cleanedup test_outside_wt
699
3567.4.13 by John Arbash Meinel
Test that make_branch_builder works on a real filesystem.
700
    def test_make_branch_builder(self):
701
        builder = self.make_branch_builder('dir')
702
        rev_id = builder.build_commit()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
703
        self.assertPathExists('dir')
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
704
        a_dir = controldir.ControlDir.open('dir')
3567.4.13 by John Arbash Meinel
Test that make_branch_builder works on a real filesystem.
705
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
706
        a_branch = a_dir.open_branch()
707
        builder_branch = builder.get_branch()
708
        self.assertEqual(a_branch.base, builder_branch.base)
709
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
710
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
711
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
712
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
713
class TestTestCaseTransports(tests.TestCaseWithTransport):
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
714
715
    def setUp(self):
716
        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.
717
        self.vfs_transport_factory = memory.MemoryServer
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
718
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
719
    def test_make_controldir_preserves_transport(self):
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
720
        t = self.get_transport()
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
721
        result_bzrdir = self.make_controldir('subdir')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
722
        self.assertIsInstance(result_bzrdir.transport,
5017.3.24 by Vincent Ladeuil
selftest -s bt.test_selftest passing
723
                              memory.MemoryTransport)
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
724
        # should not be on disk, should only be in memory
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
725
        self.assertPathDoesNotExist('subdir')
1910.13.1 by Andrew Bennetts
Make make_bzrdir preserve the transport.
726
727
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
728
class TestChrootedTest(tests.ChrootedTestCase):
1534.4.31 by Robert Collins
cleanedup test_outside_wt
729
730
    def test_root_is_root(self):
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
731
        t = transport.get_transport_from_url(self.get_readonly_url())
1534.4.31 by Robert Collins
cleanedup test_outside_wt
732
        url = t.base
733
        self.assertEqual(url, t.clone('..').base)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
734
735
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
736
class TestProfileResult(tests.TestCase):
737
738
    def test_profiles_tests(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
739
        self.requireFeature(features.lsprof_feature)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
740
        terminal = testtools.testresult.doubles.ExtendedTestResult()
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
741
        result = tests.ProfileResult(terminal)
742
        class Sample(tests.TestCase):
743
            def a(self):
744
                self.sample_function()
745
            def sample_function(self):
746
                pass
747
        test = Sample("a")
748
        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).
749
        case = terminal._events[0][1]
750
        self.assertLength(1, case._benchcalls)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
751
        # 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).
752
        (_, _, _), stats = case._benchcalls[0]
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
753
        self.assertTrue(callable(stats.pprint))
754
755
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
756
class TestTestResult(tests.TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
757
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
758
    def check_timing(self, test_case, expected_re):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
759
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
760
        capture = testtools.testresult.doubles.ExtendedTestResult()
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).
761
        test_case.run(MultiTestResult(result, capture))
762
        run_case = capture._events[0][1]
763
        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
764
        self.assertContainsRe(timed_string, expected_re)
765
766
    def test_test_reporting(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
767
        class ShortDelayTestCase(tests.TestCase):
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
768
            def test_short_delay(self):
769
                time.sleep(0.003)
770
            def test_short_benchmark(self):
771
                self.time(time.sleep, 0.003)
772
        self.check_timing(ShortDelayTestCase('test_short_delay'),
773
                          r"^ +[0-9]+ms$")
4536.5.3 by Martin Pool
Correction to selftest test for benchmark time display
774
        # if a benchmark time is given, we now show just that time followed by
775
        # a star
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
776
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
4536.5.3 by Martin Pool
Correction to selftest test for benchmark time display
777
                          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).
778
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
779
    def test_unittest_reporting_unittest_class(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
780
        # getting the time from a non-breezy test works ok
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
781
        class ShortDelayTestCase(unittest.TestCase):
782
            def test_short_delay(self):
783
                time.sleep(0.003)
784
        self.check_timing(ShortDelayTestCase('test_short_delay'),
785
                          r"^ +[0-9]+ms$")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
786
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
787
    def _time_hello_world_encoding(self):
788
        """Profile two sleep calls
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
789
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
790
        This is used to exercise the test framework.
791
        """
792
        self.time(unicode, 'hello', errors='replace')
793
        self.time(unicode, 'world', errors='replace')
794
795
    def test_lsprofiling(self):
796
        """Verbose test result prints lsprof statistics from test cases."""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
797
        self.requireFeature(features.lsprof_feature)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
798
        result_stream = StringIO()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
799
        result = breezy.tests.VerboseTestResult(
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
800
            result_stream,
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
801
            descriptions=0,
802
            verbosity=2,
803
            )
804
        # we want profile a call of some sort and check it is output by
805
        # addSuccess. We dont care about addError or addFailure as they
806
        # are not that interesting for performance tuning.
807
        # make a new test instance that when run will generate a profile
808
        example_test_case = TestTestResult("_time_hello_world_encoding")
809
        example_test_case._gather_lsprof_in_benchmarks = True
810
        # execute the test, which should succeed and record profiles
811
        example_test_case.run(result)
812
        # lsprofile_something()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
813
        # if this worked we want
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
814
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
815
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
816
        # (the lsprof header)
817
        # ... an arbitrary number of lines
818
        # and the function call which is time.sleep.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
819
        #           1        0            ???         ???       ???(sleep)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
820
        # and then repeated but with 'world', rather than 'hello'.
821
        # this should appear in the output stream of our test result.
1831.2.1 by Martin Pool
[trivial] Simplify & fix up lsprof blackbox test
822
        output = result_stream.getvalue()
823
        self.assertContainsRe(output,
824
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
825
        self.assertContainsRe(output,
826
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
827
        self.assertContainsRe(output,
828
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
829
        self.assertContainsRe(output,
830
            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
831
5445.1.1 by Martin
Use times from testtools for individual test case timings
832
    def test_uses_time_from_testtools(self):
833
        """Test case timings in verbose results should use testtools times"""
834
        import datetime
835
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
836
            def startTest(self, test):
837
                self.time(datetime.datetime.utcfromtimestamp(1.145))
838
                super(TimeAddedVerboseTestResult, self).startTest(test)
839
            def addSuccess(self, test):
840
                self.time(datetime.datetime.utcfromtimestamp(51.147))
841
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
842
            def report_tests_starting(self): pass
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
843
        sio = StringIO()
5445.1.1 by Martin
Use times from testtools for individual test case timings
844
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
845
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
846
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
847
    def test_known_failure(self):
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
848
        """Using knownFailure should trigger several result actions."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
849
        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.
850
            def stopTestRun(self): pass
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
851
            def report_tests_starting(self): pass
4794.1.15 by Robert Collins
Review feedback.
852
            def report_known_failure(self, test, err=None, details=None):
853
                self._call = test, 'known failure'
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
854
        result = InstrumentedTestResult(None, None, None, None)
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
855
        class Test(tests.TestCase):
856
            def test_function(self):
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
857
                self.knownFailure('failed!')
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
858
        test = Test("test_function")
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
859
        test.run(result)
860
        # it should invoke 'report_known_failure'.
861
        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).
862
        self.assertEqual(test.id(), result._call[0].id())
4794.1.15 by Robert Collins
Review feedback.
863
        self.assertEqual('known failure', result._call[1])
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
864
        # we dont introspec the traceback, if the rest is ok, it would be
865
        # exceptional for it not to be.
866
        # it should update the known_failure_count on the object.
867
        self.assertEqual(1, result.known_failure_count)
868
        # the result should be successful.
869
        self.assertTrue(result.wasSuccessful())
870
871
    def test_verbose_report_known_failure(self):
872
        # verbose test output formatting
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
873
        result_stream = StringIO()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
874
        result = breezy.tests.VerboseTestResult(
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
875
            result_stream,
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
876
            descriptions=0,
877
            verbosity=2,
878
            )
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
879
        _get_test("test_xfail").run(result)
880
        self.assertContainsRe(result_stream.getvalue(),
6048.1.2 by Martin
Minor wording nits and add release notes
881
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
882
            "\\s*(?:Text attachment: )?reason"
883
            "(?:\n-+\n|: {{{)"
884
            "this_fails"
885
            "(?:\n-+\n|}}}\n)")
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
886
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
887
    def get_passing_test(self):
888
        """Return a test object that can't be run usefully."""
889
        def passing_test():
890
            pass
891
        return unittest.FunctionTestCase(passing_test)
892
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
893
    def test_add_not_supported(self):
894
        """Test the behaviour of invoking addNotSupported."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
895
        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.
896
            def stopTestRun(self): pass
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
897
            def report_tests_starting(self): pass
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
898
            def report_unsupported(self, test, feature):
899
                self._call = test, feature
900
        result = InstrumentedTestResult(None, None, None, None)
901
        test = SampleTestCase('_test_pass')
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
902
        feature = features.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
903
        result.startTest(test)
904
        result.addNotSupported(test, feature)
905
        # it should invoke 'report_unsupported'.
906
        self.assertEqual(2, len(result._call))
907
        self.assertEqual(test, result._call[0])
908
        self.assertEqual(feature, result._call[1])
909
        # the result should be successful.
910
        self.assertTrue(result.wasSuccessful())
911
        # it should record the test against a count of tests not run due to
912
        # this feature.
913
        self.assertEqual(1, result.unsupported['Feature'])
914
        # and invoking it again should increment that counter
915
        result.addNotSupported(test, feature)
916
        self.assertEqual(2, result.unsupported['Feature'])
917
918
    def test_verbose_report_unsupported(self):
919
        # verbose test output formatting
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
920
        result_stream = StringIO()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
921
        result = breezy.tests.VerboseTestResult(
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
922
            result_stream,
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
923
            descriptions=0,
924
            verbosity=2,
925
            )
926
        test = self.get_passing_test()
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
927
        feature = features.Feature()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
928
        result.startTest(test)
929
        prefix = len(result_stream.getvalue())
930
        result.report_unsupported(test, feature)
931
        output = result_stream.getvalue()[prefix:]
932
        lines = output.splitlines()
4861.1.1 by Vincent Ladeuil
Fix a test timing-dependency issue.
933
        # We don't check for the final '0ms' since it may fail on slow hosts
934
        self.assertStartsWith(lines[0], 'NODEP')
935
        self.assertEqual(lines[1],
936
                         "    The feature 'Feature' is not available.")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
937
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
938
    def test_unavailable_exception(self):
939
        """An UnavailableFeature being raised should invoke addNotSupported."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
940
        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.
941
            def stopTestRun(self): pass
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
942
            def report_tests_starting(self): pass
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
943
            def addNotSupported(self, test, feature):
944
                self._call = test, feature
945
        result = InstrumentedTestResult(None, None, None, None)
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
946
        feature = features.Feature()
4780.1.1 by Robert Collins
Make addUnsupported more compatible with other TestResults.
947
        class Test(tests.TestCase):
948
            def test_function(self):
949
                raise tests.UnavailableFeature(feature)
950
        test = Test("test_function")
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
951
        test.run(result)
952
        # it should invoke 'addNotSupported'.
953
        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).
954
        self.assertEqual(test.id(), result._call[0].id())
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
955
        self.assertEqual(feature, result._call[1])
956
        # and not count as an error
957
        self.assertEqual(0, result.error_count)
958
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
959
    def test_strict_with_unsupported_feature(self):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
960
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
961
        test = self.get_passing_test()
962
        feature = "Unsupported Feature"
963
        result.addNotSupported(test, feature)
964
        self.assertFalse(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
965
        self.assertEqual(None, result._extractBenchmarkTime(test))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
966
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
967
    def test_strict_with_known_failure(self):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
968
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
969
        test = _get_test("test_xfail")
970
        test.run(result)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
971
        self.assertFalse(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
972
        self.assertEqual(None, result._extractBenchmarkTime(test))
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
973
974
    def test_strict_with_success(self):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
975
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
976
        test = self.get_passing_test()
977
        result.addSuccess(test)
978
        self.assertTrue(result.wasStrictlySuccessful())
2695.1.3 by Martin Pool
Fix up selftest tests for new extractBenchmarkTime behaviour; remove many unneeded calls to it
979
        self.assertEqual(None, result._extractBenchmarkTime(test))
2658.3.2 by Daniel Watkins
Added tests for ExtendedTestResult.wasStrictlySuccessful.
980
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
981
    def test_startTests(self):
982
        """Starting the first test should trigger startTests."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
983
        class InstrumentedTestResult(tests.ExtendedTestResult):
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
984
            calls = 0
985
            def startTests(self): self.calls += 1
986
        result = InstrumentedTestResult(None, None, None, None)
987
        def test_function():
988
            pass
989
        test = unittest.FunctionTestCase(test_function)
990
        test.run(result)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
991
        self.assertEqual(1, result.calls)
4271.2.3 by Vincent Ladeuil
Fix failure, add tests.
992
5412.1.5 by Martin
Move test count addition into startTest from report methods in subclasses
993
    def test_startTests_only_once(self):
994
        """With multiple tests startTests should still only be called once"""
995
        class InstrumentedTestResult(tests.ExtendedTestResult):
996
            calls = 0
997
            def startTests(self): self.calls += 1
998
        result = InstrumentedTestResult(None, None, None, None)
999
        suite = unittest.TestSuite([
1000
            unittest.FunctionTestCase(lambda: None),
1001
            unittest.FunctionTestCase(lambda: None)])
1002
        suite.run(result)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1003
        self.assertEqual(1, result.calls)
1004
        self.assertEqual(2, result.count)
5412.1.5 by Martin
Move test count addition into startTest from report methods in subclasses
1005
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
1006
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1007
class TestRunner(tests.TestCase):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
1008
1009
    def dummy_test(self):
1010
        pass
1011
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1012
    def run_test_runner(self, testrunner, test):
1013
        """Run suite in testrunner, saving global state and restoring it.
1014
1015
        This current saves and restores:
1016
        TestCaseInTempDir.TEST_ROOT
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1017
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1018
        There should be no tests in this file that use
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1019
        breezy.tests.TextTestRunner without using this convenience method,
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1020
        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.
1021
        """
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1022
        old_root = tests.TestCaseInTempDir.TEST_ROOT
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1023
        try:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1024
            tests.TestCaseInTempDir.TEST_ROOT = None
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1025
            return testrunner.run(test)
1026
        finally:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1027
            tests.TestCaseInTempDir.TEST_ROOT = old_root
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1028
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1029
    def test_known_failure_failed_run(self):
1030
        # run a test that generates a known failure which should be printed in
1031
        # the final output when real failures occur.
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
1032
        class Test(tests.TestCase):
1033
            def known_failure_test(self):
4794.1.15 by Robert Collins
Review feedback.
1034
                self.expectFailure('failed', self.assertTrue, False)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1035
        test = unittest.TestSuite()
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
1036
        test.addTest(Test("known_failure_test"))
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1037
        def failing_test():
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1038
            raise AssertionError('foo')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1039
        test.addTest(unittest.FunctionTestCase(failing_test))
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1040
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1041
        runner = tests.TextTestRunner(stream=stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1042
        result = self.run_test_runner(runner, test)
1043
        lines = stream.getvalue().splitlines()
4595.7.4 by Martin Pool
Change overly-tight selftest test to use a re
1044
        self.assertContainsRe(stream.getvalue(),
6622.1.4 by Jelmer Vernooij
Fix some more tests.
1045
            '(?sm)^brz selftest.*$'
4595.7.4 by Martin Pool
Change overly-tight selftest test to use a re
1046
            '.*'
1047
            '^======================================================================\n'
4789.29.3 by Robert Collins
And fix the one failing test.
1048
            '^FAIL: failing_test\n'
4595.7.4 by Martin Pool
Change overly-tight selftest test to use a re
1049
            '^----------------------------------------------------------------------\n'
1050
            'Traceback \\(most recent call last\\):\n'
1051
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1052
            '    raise AssertionError\\(\'foo\'\\)\n'
4595.7.4 by Martin Pool
Change overly-tight selftest test to use a re
1053
            '.*'
1054
            '^----------------------------------------------------------------------\n'
1055
            '.*'
1056
            'FAILED \\(failures=1, known_failure_count=1\\)'
1057
            )
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1058
1059
    def test_known_failure_ok_run(self):
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
1060
        # run a test that generates a known failure which should be printed in
1061
        # the final output.
1062
        class Test(tests.TestCase):
1063
            def known_failure_test(self):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1064
                self.knownFailure("Never works...")
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
1065
        test = Test("known_failure_test")
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1066
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1067
        runner = tests.TextTestRunner(stream=stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1068
        result = self.run_test_runner(runner, test)
2418.3.1 by John Arbash Meinel
Remove timing dependencies from the selftest tests.
1069
        self.assertContainsRe(stream.getvalue(),
1070
            '\n'
1071
            '-*\n'
1072
            'Ran 1 test in .*\n'
1073
            '\n'
1074
            'OK \\(known_failures=1\\)\n')
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1075
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
1076
    def test_unexpected_success_bad(self):
1077
        class Test(tests.TestCase):
1078
            def test_truth(self):
1079
                self.expectFailure("No absolute truth", self.assertTrue, True)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1080
        runner = tests.TextTestRunner(stream=StringIO())
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
1081
        result = self.run_test_runner(runner, Test("test_truth"))
1082
        self.assertContainsRe(runner.stream.getvalue(),
1083
            "=+\n"
6798.1.1 by Jelmer Vernooij
Properly escape backslashes.
1084
            "FAIL: \\S+\\.test_truth\n"
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
1085
            "-+\n"
1086
            "(?:.*\n)*"
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
1087
            "\\s*(?:Text attachment: )?reason"
1088
            "(?:\n-+\n|: {{{)"
1089
            "No absolute truth"
1090
            "(?:\n-+\n|}}}\n)"
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
1091
            "(?:.*\n)*"
1092
            "-+\n"
1093
            "Ran 1 test in .*\n"
1094
            "\n"
1095
            "FAILED \\(failures=1\\)\n\\Z")
1096
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1097
    def test_result_decorator(self):
1098
        # decorate results
1099
        calls = []
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
1100
        class LoggingDecorator(ExtendedToOriginalDecorator):
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1101
            def startTest(self, test):
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
1102
                ExtendedToOriginalDecorator.startTest(self, test)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1103
                calls.append('start')
1104
        test = unittest.FunctionTestCase(lambda:None)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1105
        stream = StringIO()
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
1106
        runner = tests.TextTestRunner(stream=stream,
1107
            result_decorators=[LoggingDecorator])
1108
        result = self.run_test_runner(runner, test)
1109
        self.assertLength(1, calls)
1110
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1111
    def test_skipped_test(self):
1112
        # run a test that is skipped, and check the suite as a whole still
1113
        # succeeds.
1114
        # 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.
1115
        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.
1116
            def skipping_test(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1117
                raise tests.TestSkipped('test intentionally skipped')
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1118
        runner = tests.TextTestRunner(stream=StringIO())
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1119
        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.
1120
        result = self.run_test_runner(runner, test)
1121
        self.assertTrue(result.wasSuccessful())
1122
1123
    def test_skipped_from_setup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1124
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1125
        class SkippedSetupTest(tests.TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1126
1127
            def setUp(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1128
                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.
1129
                self.addCleanup(self.cleanup)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1130
                raise tests.TestSkipped('skipped setup')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1131
1132
            def test_skip(self):
1133
                self.fail('test reached')
1134
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1135
            def cleanup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1136
                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.
1137
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1138
        runner = tests.TextTestRunner(stream=StringIO())
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1139
        test = SkippedSetupTest('test_skip')
1140
        result = self.run_test_runner(runner, test)
1141
        self.assertTrue(result.wasSuccessful())
1142
        # 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.
1143
        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.
1144
1145
    def test_skipped_from_test(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1146
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1147
        class SkippedTest(tests.TestCase):
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1148
1149
            def setUp(self):
6552.1.3 by Vincent Ladeuil
Use super() instead of calling <base>.setup(self), as the original fix illustrated a too-easy-to-fall-into trap.
1150
                super(SkippedTest, self).setUp()
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1151
                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.
1152
                self.addCleanup(self.cleanup)
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1153
1154
            def test_skip(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1155
                raise tests.TestSkipped('skipped test')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1156
2338.4.10 by Marien Zwart
Make a test skipped from setUp run tearDown again. Make calling _runCleanups twice safe. Clean up tests.
1157
            def cleanup(self):
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1158
                calls.append('cleanup')
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1159
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1160
        runner = tests.TextTestRunner(stream=StringIO())
2338.4.8 by Marien Zwart
Fix a bug in selftest causing tearDown to run twice for skipped tests.
1161
        test = SkippedTest('test_skip')
1162
        result = self.run_test_runner(runner, test)
1163
        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.
1164
        # 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.
1165
        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.
1166
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1167
    def test_not_applicable(self):
1168
        # 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.
1169
        class Test(tests.TestCase):
1170
            def not_applicable_test(self):
1171
                raise tests.TestNotApplicable('this test never runs')
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1172
        out = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1173
        runner = tests.TextTestRunner(stream=out, verbosity=2)
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
1174
        test = Test("not_applicable_test")
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1175
        result = self.run_test_runner(runner, test)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1176
        self.log(out.getvalue())
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1177
        self.assertTrue(result.wasSuccessful())
1178
        self.assertTrue(result.wasStrictlySuccessful())
1179
        self.assertContainsRe(out.getvalue(),
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1180
                r'(?m)not_applicable_test  * N/A')
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
1181
        self.assertContainsRe(out.getvalue(),
1182
                r'(?m)^    this test never runs')
1183
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1184
    def test_unsupported_features_listed(self):
1185
        """When unsupported features are encountered they are detailed."""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1186
        class Feature1(features.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
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1188
        class Feature2(features.Feature):
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1189
            def _probe(self): return False
1190
        # create sample tests
1191
        test1 = SampleTestCase('_test_pass')
1192
        test1._test_needs_features = [Feature1()]
1193
        test2 = SampleTestCase('_test_pass')
1194
        test2._test_needs_features = [Feature2()]
1195
        test = unittest.TestSuite()
1196
        test.addTest(test1)
1197
        test.addTest(test2)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1198
        stream = StringIO()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1199
        runner = tests.TextTestRunner(stream=stream)
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1200
        result = self.run_test_runner(runner, test)
1201
        lines = stream.getvalue().splitlines()
1202
        self.assertEqual([
1203
            'OK',
1204
            "Missing feature 'Feature1' skipped 1 tests.",
1205
            "Missing feature 'Feature2' skipped 1 tests.",
1206
            ],
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1207
            lines[-3:])
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
1208
5425.3.1 by Martin
Add failing test for test count reported at start of verbose test run
1209
    def test_verbose_test_count(self):
1210
        """A verbose test run reports the right test count at the start"""
1211
        suite = TestUtil.TestSuite([
1212
            unittest.FunctionTestCase(lambda:None),
1213
            unittest.FunctionTestCase(lambda:None)])
1214
        self.assertEqual(suite.countTestCases(), 2)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1215
        stream = StringIO()
5425.3.1 by Martin
Add failing test for test count reported at start of verbose test run
1216
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
1217
        # Need to use the CountingDecorator as that's what sets num_tests
1218
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
1219
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
1220
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
1221
    def test_startTestRun(self):
1222
        """run should call result.startTestRun()"""
1223
        calls = []
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
1224
        class LoggingDecorator(ExtendedToOriginalDecorator):
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
1225
            def startTestRun(self):
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
1226
                ExtendedToOriginalDecorator.startTestRun(self)
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
1227
                calls.append('startTestRun')
1228
        test = unittest.FunctionTestCase(lambda:None)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1229
        stream = StringIO()
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
1230
        runner = tests.TextTestRunner(stream=stream,
1231
            result_decorators=[LoggingDecorator])
1232
        result = self.run_test_runner(runner, test)
1233
        self.assertLength(1, calls)
1234
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1235
    def test_stopTestRun(self):
1236
        """run should call result.stopTestRun()"""
1237
        calls = []
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
1238
        class LoggingDecorator(ExtendedToOriginalDecorator):
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1239
            def stopTestRun(self):
5495.1.1 by Andrew Bennetts
Remove unused definition of ForwardingResult, and switch all code to use the testtools name for it. Also remove a few unused imports.
1240
                ExtendedToOriginalDecorator.stopTestRun(self)
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1241
                calls.append('stopTestRun')
1242
        test = unittest.FunctionTestCase(lambda:None)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1243
        stream = StringIO()
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
1244
        runner = tests.TextTestRunner(stream=stream,
1245
            result_decorators=[LoggingDecorator])
1246
        result = self.run_test_runner(runner, test)
1247
        self.assertLength(1, calls)
1248
5410.2.1 by Martin
Escape unprintable test result output rather than aborting selftest
1249
    def test_unicode_test_output_on_ascii_stream(self):
1250
        """Showing results should always succeed even on an ascii console"""
1251
        class FailureWithUnicode(tests.TestCase):
1252
            def test_log_unicode(self):
1253
                self.log(u"\u2606")
1254
                self.fail("Now print that log!")
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1255
        out = StringIO()
5410.2.1 by Martin
Escape unprintable test result output rather than aborting selftest
1256
        self.overrideAttr(osutils, "get_terminal_encoding",
1257
            lambda trace=False: "ascii")
1258
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
1259
            FailureWithUnicode("test_log_unicode"))
1260
        self.assertContainsRe(out.getvalue(),
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
1261
            "(?:Text attachment: )?log"
1262
            "(?:\n-+\n|: {{{)"
6798.1.1 by Jelmer Vernooij
Properly escape backslashes.
1263
            "\\d+\\.\\d+  \\\\u2606"
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
1264
            "(?:\n-+\n|}}}\n)")
5410.2.1 by Martin
Escape unprintable test result output rather than aborting selftest
1265
2036.1.2 by John Arbash Meinel
whitespace fix
1266
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1267
class SampleTestCase(tests.TestCase):
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1268
1269
    def _test_pass(self):
1270
        pass
1271
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1272
class _TestException(Exception):
1273
    pass
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1274
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1275
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1276
class TestTestCase(tests.TestCase):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1277
    """Tests that test the core breezy TestCase."""
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1278
4144.1.1 by Robert Collins
New assertLength method based on one Martin has squirreled away somewhere.
1279
    def test_assertLength_matches_empty(self):
1280
        a_list = []
1281
        self.assertLength(0, a_list)
1282
1283
    def test_assertLength_matches_nonempty(self):
1284
        a_list = [1, 2, 3]
1285
        self.assertLength(3, a_list)
1286
1287
    def test_assertLength_fails_different(self):
1288
        a_list = []
1289
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1290
1291
    def test_assertLength_shows_sequence_in_failure(self):
1292
        a_list = [1, 2, 3]
1293
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
1294
            a_list)
1295
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1296
            exception.args[0])
1297
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1298
    def test_base_setUp_not_called_causes_failure(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1299
        class TestCaseWithBrokenSetUp(tests.TestCase):
4153.1.1 by Andrew Bennetts
Check that TestCase.setUp was called in TestCase.run. If not, fail the test.
1300
            def setUp(self):
1301
                pass # does not call TestCase.setUp
1302
            def test_foo(self):
1303
                pass
1304
        test = TestCaseWithBrokenSetUp('test_foo')
1305
        result = unittest.TestResult()
1306
        test.run(result)
1307
        self.assertFalse(result.wasSuccessful())
4153.1.5 by Andrew Bennetts
Tweak assertions based on Robert's review.
1308
        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.
1309
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1310
    def test_base_tearDown_not_called_causes_failure(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1311
        class TestCaseWithBrokenTearDown(tests.TestCase):
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1312
            def tearDown(self):
1313
                pass # does not call TestCase.tearDown
1314
            def test_foo(self):
1315
                pass
1316
        test = TestCaseWithBrokenTearDown('test_foo')
1317
        result = unittest.TestResult()
1318
        test.run(result)
1319
        self.assertFalse(result.wasSuccessful())
4153.1.5 by Andrew Bennetts
Tweak assertions based on Robert's review.
1320
        self.assertEqual(1, result.testsRun)
4153.1.3 by Andrew Bennetts
Check that bzrlib.tests.TestCase.tearDown is called too.
1321
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1322
    def test_debug_flags_sanitised(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1323
        """The breezy debug flags should be sanitised by setUp."""
3731.3.1 by Andrew Bennetts
Make the test suite pass when -Eallow_debug is used.
1324
        if 'allow_debug' in tests.selftest_debug_flags:
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1325
            raise tests.TestNotApplicable(
3731.3.2 by Andrew Bennetts
Fix typo.
1326
                '-Eallow_debug option prevents debug flag sanitisation')
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1327
        # we could set something and run a test that will check
1328
        # it gets santised, but this is probably sufficient for now:
1329
        # 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.
1330
        flags = set()
1331
        if self._lock_check_thorough:
1332
            flags.add('strict_locks')
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1333
        self.assertEqual(flags, breezy.debug.debug_flags)
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1334
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1335
    def change_selftest_debug_flags(self, new_flags):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1336
        self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1337
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1338
    def test_allow_debug_flag(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1339
        """The -Eallow_debug flag prevents breezy.debug.debug_flags from being
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1340
        sanitised (i.e. cleared) before running a test.
1341
        """
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1342
        self.change_selftest_debug_flags({'allow_debug'})
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1343
        breezy.debug.debug_flags = {'a-flag'}
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1344
        class TestThatRecordsFlags(tests.TestCase):
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1345
            def test_foo(nested_self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1346
                self.flags = set(breezy.debug.debug_flags)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1347
        test = TestThatRecordsFlags('test_foo')
1348
        test.run(self.make_test_result())
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1349
        flags = {'a-flag'}
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1350
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
1351
            flags.add('strict_locks')
1352
        self.assertEqual(flags, self.flags)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1353
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1354
    def test_disable_lock_checks(self):
1355
        """The -Edisable_lock_checks flag disables thorough checks."""
1356
        class TestThatRecordsFlags(tests.TestCase):
1357
            def test_foo(nested_self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1358
                self.flags = set(breezy.debug.debug_flags)
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1359
                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.
1360
        self.change_selftest_debug_flags(set())
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1361
        test = TestThatRecordsFlags('test_foo')
1362
        test.run(self.make_test_result())
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1363
        # By default we do strict lock checking and thorough lock/unlock
1364
        # tracking.
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1365
        self.assertTrue(self.test_lock_check_thorough)
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1366
        self.assertEqual({'strict_locks'}, self.flags)
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1367
        # Now set the disable_lock_checks flag, and show that this changed.
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1368
        self.change_selftest_debug_flags({'disable_lock_checks'})
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1369
        test = TestThatRecordsFlags('test_foo')
1370
        test.run(self.make_test_result())
1371
        self.assertFalse(self.test_lock_check_thorough)
1372
        self.assertEqual(set(), self.flags)
1373
4523.4.13 by John Arbash Meinel
Add a test that thisFailsStrictLockCheck() does the right thing.
1374
    def test_this_fails_strict_lock_check(self):
1375
        class TestThatRecordsFlags(tests.TestCase):
1376
            def test_foo(nested_self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1377
                self.flags1 = set(breezy.debug.debug_flags)
4523.4.13 by John Arbash Meinel
Add a test that thisFailsStrictLockCheck() does the right thing.
1378
                self.thisFailsStrictLockCheck()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1379
                self.flags2 = set(breezy.debug.debug_flags)
4523.4.13 by John Arbash Meinel
Add a test that thisFailsStrictLockCheck() does the right thing.
1380
        # Make sure lock checking is active
1381
        self.change_selftest_debug_flags(set())
1382
        test = TestThatRecordsFlags('test_foo')
1383
        test.run(self.make_test_result())
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1384
        self.assertEqual({'strict_locks'}, self.flags1)
4523.4.13 by John Arbash Meinel
Add a test that thisFailsStrictLockCheck() does the right thing.
1385
        self.assertEqual(set(), self.flags2)
1386
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1387
    def test_debug_flags_restored(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1388
        """The breezy debug flags should be restored to their original state
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1389
        after the test was run, even if allow_debug is set.
1390
        """
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1391
        self.change_selftest_debug_flags({'allow_debug'})
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1392
        # Now run a test that modifies debug.debug_flags.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1393
        breezy.debug.debug_flags = {'original-state'}
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1394
        class TestThatModifiesFlags(tests.TestCase):
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1395
            def test_foo(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1396
                breezy.debug.debug_flags = {'modified'}
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1397
        test = TestThatModifiesFlags('test_foo')
1398
        test.run(self.make_test_result())
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1399
        self.assertEqual({'original-state'}, breezy.debug.debug_flags)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1400
1401
    def make_test_result(self):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1402
        """Get a test result that writes to a StringIO."""
1403
        return tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1404
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1405
    def inner_test(self):
1406
        # the inner child test
1407
        note("inner_test")
1408
1409
    def outer_child(self):
1410
        # the outer child test
1411
        note("outer_start")
1412
        self.inner_test = TestTestCase("inner_child")
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1413
        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.
1414
        self.inner_test.run(result)
1415
        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).
1416
        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.
1417
1418
    def test_trace_nesting(self):
1419
        # this tests that each test case nests its trace facility correctly.
1420
        # we do this by running a test case manually. That test case (A)
1421
        # should setup a new log, log content to it, setup a child case (B),
1422
        # which should log independently, then case (A) should log a trailer
1423
        # and return.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1424
        # 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.
1425
        # logs after the outer child finishes is correct, which a bad clean
1426
        # up routine in tearDown might trigger a fault in our test with only
1427
        # one child, we should instead see the bad result inside our test with
1428
        # the two children.
1429
        # the outer child test
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1430
        original_trace = breezy.trace._trace_file
1534.11.7 by Robert Collins
Test and correct the problem with nested test logs breaking further in-test logs.
1431
        outer_test = TestTestCase("outer_child")
3731.3.3 by Andrew Bennetts
Add tests suggested by Vincent.
1432
        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.
1433
        outer_test.run(result)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1434
        self.assertEqual(original_trace, breezy.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)
1435
1436
    def method_that_times_a_bit_twice(self):
1437
        # 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.
1438
        self.time(time.sleep, 0.007)
1439
        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)
1440
1441
    def test_time_creates_benchmark_in_result(self):
1442
        """Test that the TestCase.time() method accumulates a benchmark time."""
1443
        sample_test = TestTestCase("method_that_times_a_bit_twice")
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1444
        output_stream = StringIO()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1445
        result = breezy.tests.VerboseTestResult(
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
1446
            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)
1447
            descriptions=0,
4573.2.2 by Robert Collins
Fix selftest for TestResult progress changes.
1448
            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)
1449
        sample_test.run(result)
1450
        self.assertContainsRe(
1451
            output_stream.getvalue(),
4536.5.5 by Martin Pool
More selftest display test tweaks
1452
            r"\d+ms\*\n$")
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1453
1454
    def test_hooks_sanitised(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1455
        """The breezy 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.
1456
        # Note this test won't fail with hooks that the core library doesn't
1457
        # use - but it trigger with a plugin that adds hooks, so its still a
1458
        # useful warning in that case.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1459
        self.assertEqual(breezy.branch.BranchHooks(), breezy.branch.Branch.hooks)
1460
        self.assertEqual(
6670.4.16 by Jelmer Vernooij
Move smart to breezy.bzr.
1461
            breezy.bzr.smart.server.SmartServerHooks(),
1462
            breezy.bzr.smart.server.SmartTCPServer.hooks)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1463
        self.assertEqual(
1464
            breezy.commands.CommandHooks(), breezy.commands.Command.hooks)
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1465
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1466
    def test__gather_lsprof_in_benchmarks(self):
1467
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1468
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1469
        Each self.time() call is individually and separately profiled.
1470
        """
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1471
        self.requireFeature(features.lsprof_feature)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1472
        # 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
1473
        # needed.
1474
        self._gather_lsprof_in_benchmarks = True
1475
        self.time(time.sleep, 0.000)
1476
        self.time(time.sleep, 0.003)
1477
        self.assertEqual(2, len(self._benchcalls))
1478
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1479
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1480
        self.assertIsInstance(self._benchcalls[0][1], breezy.lsprof.Stats)
1481
        self.assertIsInstance(self._benchcalls[1][1], breezy.lsprof.Stats)
4641.3.1 by Robert Collins
Squelch test noise on test__gather_lsprof_in_benchmarks verbose mode.
1482
        del self._benchcalls[:]
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1483
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1484
    def test_knownFailure(self):
1485
        """Self.knownFailure() should raise a KnownFailure exception."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1486
        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
1487
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
    def test_open_bzrdir_safe_roots(self):
1489
        # even a memory transport should fail to open when its url isn't 
1490
        # permitted.
1491
        # Manually set one up (TestCase doesn't and shouldn't provide magic
1492
        # 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.
1493
        transport_server = memory.MemoryServer()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
1494
        transport_server.start_server()
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
1495
        self.addCleanup(transport_server.stop_server)
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
1496
        t = transport.get_transport_from_url(transport_server.get_url())
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
1497
        controldir.ControlDir.create(t.base)
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.
1498
        self.assertRaises(errors.BzrError,
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
1499
            controldir.ControlDir.open_from_transport, t)
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.
1500
        # But if we declare this as safe, we can open the bzrdir.
1501
        self.permit_url(t.base)
1502
        self._bzr_selftest_roots.append(t.base)
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
1503
        controldir.ControlDir.open_from_transport(t)
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.
1504
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1505
    def test_requireFeature_available(self):
1506
        """self.requireFeature(available) is a no-op."""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1507
        class Available(features.Feature):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1508
            def _probe(self):return True
1509
        feature = Available()
1510
        self.requireFeature(feature)
1511
1512
    def test_requireFeature_unavailable(self):
1513
        """self.requireFeature(unavailable) raises UnavailableFeature."""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1514
        class Unavailable(features.Feature):
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1515
            def _probe(self):return False
1516
        feature = Unavailable()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1517
        self.assertRaises(tests.UnavailableFeature,
1518
                          self.requireFeature, feature)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1519
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1520
    def test_run_no_parameters(self):
1521
        test = SampleTestCase('_test_pass')
1522
        test.run()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1523
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1524
    def test_run_enabled_unittest_result(self):
5050.33.3 by Andrew Bennetts
Restore accidentally deleted test docstring.
1525
        """Test we revert to regular behaviour when the test is enabled."""
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1526
        test = SampleTestCase('_test_pass')
1527
        class EnabledFeature(object):
1528
            def available(self):
1529
                return True
1530
        test._test_needs_features = [EnabledFeature()]
1531
        result = unittest.TestResult()
1532
        test.run(result)
1533
        self.assertEqual(1, result.testsRun)
1534
        self.assertEqual([], result.errors)
1535
        self.assertEqual([], result.failures)
1536
1537
    def test_run_disabled_unittest_result(self):
1538
        """Test our compatability for disabled tests with unittest results."""
1539
        test = SampleTestCase('_test_pass')
1540
        class DisabledFeature(object):
1541
            def available(self):
1542
                return False
1543
        test._test_needs_features = [DisabledFeature()]
1544
        result = unittest.TestResult()
1545
        test.run(result)
1546
        self.assertEqual(1, result.testsRun)
1547
        self.assertEqual([], result.errors)
1548
        self.assertEqual([], result.failures)
1549
1550
    def test_run_disabled_supporting_result(self):
1551
        """Test disabled tests behaviour with support aware results."""
1552
        test = SampleTestCase('_test_pass')
1553
        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).
1554
            def __eq__(self, other):
1555
                return isinstance(other, DisabledFeature)
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1556
            def available(self):
1557
                return False
1558
        the_feature = DisabledFeature()
1559
        test._test_needs_features = [the_feature]
1560
        class InstrumentedTestResult(unittest.TestResult):
1561
            def __init__(self):
1562
                unittest.TestResult.__init__(self)
1563
                self.calls = []
1564
            def startTest(self, test):
1565
                self.calls.append(('startTest', test))
1566
            def stopTest(self, test):
1567
                self.calls.append(('stopTest', test))
1568
            def addNotSupported(self, test, feature):
1569
                self.calls.append(('addNotSupported', test, feature))
1570
        result = InstrumentedTestResult()
1571
        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).
1572
        case = result.calls[0][1]
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1573
        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).
1574
            ('startTest', case),
1575
            ('addNotSupported', case, the_feature),
1576
            ('stopTest', case),
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1577
            ],
1578
            result.calls)
1579
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.
1580
    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.
1581
        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.
1582
        # A little strict, but unlikely to be changed soon.
1583
        self.assertEqual([], self._bzr_selftest_roots)
1584
        self.start_server(transport_server)
1585
        self.assertSubset([transport_server.get_url()],
1586
            self._bzr_selftest_roots)
1587
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1588
    def test_assert_list_raises_on_generator(self):
1589
        def generator_which_will_raise():
1590
            # This will not raise until after the first yield
1591
            yield 1
1592
            raise _TestException()
1593
1594
        e = self.assertListRaises(_TestException, generator_which_will_raise)
1595
        self.assertIsInstance(e, _TestException)
1596
1597
        e = self.assertListRaises(Exception, generator_which_will_raise)
1598
        self.assertIsInstance(e, _TestException)
1599
1600
    def test_assert_list_raises_on_plain(self):
1601
        def plain_exception():
1602
            raise _TestException()
1603
            return []
1604
1605
        e = self.assertListRaises(_TestException, plain_exception)
1606
        self.assertIsInstance(e, _TestException)
1607
1608
        e = self.assertListRaises(Exception, plain_exception)
1609
        self.assertIsInstance(e, _TestException)
1610
1611
    def test_assert_list_raises_assert_wrong_exception(self):
1612
        class _NotTestException(Exception):
1613
            pass
1614
1615
        def wrong_exception():
1616
            raise _NotTestException()
1617
1618
        def wrong_exception_generator():
1619
            yield 1
1620
            yield 2
1621
            raise _NotTestException()
1622
1623
        # Wrong exceptions are not intercepted
1624
        self.assertRaises(_NotTestException,
1625
            self.assertListRaises, _TestException, wrong_exception)
1626
        self.assertRaises(_NotTestException,
1627
            self.assertListRaises, _TestException, wrong_exception_generator)
1628
1629
    def test_assert_list_raises_no_exception(self):
1630
        def success():
1631
            return []
1632
1633
        def success_generator():
1634
            yield 1
1635
            yield 2
1636
1637
        self.assertRaises(AssertionError,
1638
            self.assertListRaises, _TestException, success)
1639
1640
        self.assertRaises(AssertionError,
1641
            self.assertListRaises, _TestException, success_generator)
1642
6015.60.1 by John Arbash Meinel
Teach TestCase.overrideAttr how to handle attributes that don't exist yet.
1643
    def _run_successful_test(self, test):
1644
        result = testtools.TestResult()
1645
        test.run(result)
1646
        self.assertTrue(result.wasSuccessful())
1647
        return result
1648
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
1649
    def test_overrideAttr_without_value(self):
4985.1.2 by Vincent Ladeuil
We're testing TestCase not TestRunner.
1650
        self.test_attr = 'original' # Define a test attribute
1651
        obj = self # Make 'obj' visible to the embedded test
1652
        class Test(tests.TestCase):
1653
1654
            def setUp(self):
6552.1.3 by Vincent Ladeuil
Use super() instead of calling <base>.setup(self), as the original fix illustrated a too-easy-to-fall-into trap.
1655
                super(Test, self).setUp()
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
1656
                self.orig = self.overrideAttr(obj, 'test_attr')
1657
1658
            def test_value(self):
1659
                self.assertEqual('original', self.orig)
1660
                self.assertEqual('original', obj.test_attr)
4985.1.2 by Vincent Ladeuil
We're testing TestCase not TestRunner.
1661
                obj.test_attr = 'modified'
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
1662
                self.assertEqual('modified', obj.test_attr)
1663
6015.60.1 by John Arbash Meinel
Teach TestCase.overrideAttr how to handle attributes that don't exist yet.
1664
        self._run_successful_test(Test('test_value'))
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
1665
        self.assertEqual('original', obj.test_attr)
1666
1667
    def test_overrideAttr_with_value(self):
1668
        self.test_attr = 'original' # Define a test attribute
1669
        obj = self # Make 'obj' visible to the embedded test
1670
        class Test(tests.TestCase):
1671
1672
            def setUp(self):
6552.1.3 by Vincent Ladeuil
Use super() instead of calling <base>.setup(self), as the original fix illustrated a too-easy-to-fall-into trap.
1673
                super(Test, self).setUp()
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
1674
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
4985.1.2 by Vincent Ladeuil
We're testing TestCase not TestRunner.
1675
1676
            def test_value(self):
1677
                self.assertEqual('original', self.orig)
1678
                self.assertEqual('modified', obj.test_attr)
1679
6015.60.1 by John Arbash Meinel
Teach TestCase.overrideAttr how to handle attributes that don't exist yet.
1680
        self._run_successful_test(Test('test_value'))
4985.1.2 by Vincent Ladeuil
We're testing TestCase not TestRunner.
1681
        self.assertEqual('original', obj.test_attr)
1682
6015.60.1 by John Arbash Meinel
Teach TestCase.overrideAttr how to handle attributes that don't exist yet.
1683
    def test_overrideAttr_with_no_existing_value_and_value(self):
1684
        # Do not define the test_attribute
1685
        obj = self # Make 'obj' visible to the embedded test
1686
        class Test(tests.TestCase):
1687
1688
            def setUp(self):
1689
                tests.TestCase.setUp(self)
1690
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1691
1692
            def test_value(self):
1693
                self.assertEqual(tests._unitialized_attr, self.orig)
1694
                self.assertEqual('modified', obj.test_attr)
1695
1696
        self._run_successful_test(Test('test_value'))
1697
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1698
1699
    def test_overrideAttr_with_no_existing_value_and_no_value(self):
1700
        # Do not define the test_attribute
1701
        obj = self # Make 'obj' visible to the embedded test
1702
        class Test(tests.TestCase):
1703
1704
            def setUp(self):
1705
                tests.TestCase.setUp(self)
1706
                self.orig = self.overrideAttr(obj, 'test_attr')
1707
1708
            def test_value(self):
1709
                self.assertEqual(tests._unitialized_attr, self.orig)
1710
                self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1711
1712
        self._run_successful_test(Test('test_value'))
1713
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
1714
6006.4.1 by Martin Pool
Add recordCalls test helper
1715
    def test_recordCalls(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1716
        from breezy.tests import test_selftest
6006.4.1 by Martin Pool
Add recordCalls test helper
1717
        calls = self.recordCalls(
1718
            test_selftest, '_add_numbers')
1719
        self.assertEqual(test_selftest._add_numbers(2, 10),
1720
            12)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1721
        self.assertEqual(calls, [((2, 10), {})])
6006.4.1 by Martin Pool
Add recordCalls test helper
1722
1723
1724
def _add_numbers(a, b):
1725
    return a + b
1726
1534.11.4 by Robert Collins
Merge from mainline.
1727
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1728
class _MissingFeature(features.Feature):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1729
    def _probe(self):
1730
        return False
1731
missing_feature = _MissingFeature()
1732
1733
1734
def _get_test(name):
1735
    """Get an instance of a specific example test.
1736
1737
    We protect this in a function so that they don't auto-run in the test
1738
    suite.
1739
    """
1740
1741
    class ExampleTests(tests.TestCase):
1742
1743
        def test_fail(self):
1744
            mutter('this was a failing test')
1745
            self.fail('this test will fail')
1746
1747
        def test_error(self):
1748
            mutter('this test errored')
1749
            raise RuntimeError('gotcha')
1750
1751
        def test_missing_feature(self):
1752
            mutter('missing the feature')
1753
            self.requireFeature(missing_feature)
1754
1755
        def test_skip(self):
1756
            mutter('this test will be skipped')
1757
            raise tests.TestSkipped('reason')
1758
1759
        def test_success(self):
1760
            mutter('this test succeeds')
1761
1762
        def test_xfail(self):
1763
            mutter('test with expected failure')
1764
            self.knownFailure('this_fails')
1765
1766
        def test_unexpected_success(self):
1767
            mutter('test with unexpected success')
1768
            self.expectFailure('should_fail', lambda: None)
1769
1770
    return ExampleTests(name)
1771
1772
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1773
def _get_skip_reasons(result):
1774
    # GZ 2017-06-06: Newer testtools doesn't have this, uses detail instead
1775
    return result.skip_reasons
1776
1777
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1778
class TestTestCaseLogDetails(tests.TestCase):
1779
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1780
    def _run_test(self, test_name):
1781
        test = _get_test(test_name)
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1782
        result = testtools.TestResult()
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1783
        test.run(result)
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1784
        return result
1785
1786
    def test_fail_has_log(self):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1787
        result = self._run_test('test_fail')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1788
        self.assertEqual(1, len(result.failures))
1789
        result_content = result.failures[0][1]
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
1790
        self.assertContainsRe(result_content,
1791
            '(?m)^(?:Text attachment: )?log(?:$|: )')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1792
        self.assertContainsRe(result_content, 'this was a failing test')
1793
1794
    def test_error_has_log(self):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1795
        result = self._run_test('test_error')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1796
        self.assertEqual(1, len(result.errors))
1797
        result_content = result.errors[0][1]
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
1798
        self.assertContainsRe(result_content,
1799
            '(?m)^(?:Text attachment: )?log(?:$|: )')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1800
        self.assertContainsRe(result_content, 'this test errored')
1801
1802
    def test_skip_has_no_log(self):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1803
        result = self._run_test('test_skip')
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1804
        reasons = _get_skip_reasons(result)
1805
        self.assertEqual({'reason'}, set(reasons))
1806
        skips = reasons['reason']
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1807
        self.assertEqual(1, len(skips))
1808
        test = skips[0]
1809
        self.assertFalse('log' in test.getDetails())
1810
1811
    def test_missing_feature_has_no_log(self):
1812
        # testtools doesn't know about addNotSupported, so it just gets
1813
        # considered as a skip
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1814
        result = self._run_test('test_missing_feature')
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
1815
        reasons = _get_skip_reasons(result)
6765.1.4 by Jelmer Vernooij
Fix tests.
1816
        self.assertEqual({str(missing_feature)}, set(reasons))
1817
        skips = reasons[str(missing_feature)]
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1818
        self.assertEqual(1, len(skips))
1819
        test = skips[0]
1820
        self.assertFalse('log' in test.getDetails())
1821
1822
    def test_xfail_has_no_log(self):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1823
        result = self._run_test('test_xfail')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1824
        self.assertEqual(1, len(result.expectedFailures))
1825
        result_content = result.expectedFailures[0][1]
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
1826
        self.assertNotContainsRe(result_content,
1827
            '(?m)^(?:Text attachment: )?log(?:$|: )')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1828
        self.assertNotContainsRe(result_content, 'test with expected failure')
1829
1830
    def test_unexpected_success_has_log(self):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
1831
        result = self._run_test('test_unexpected_success')
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1832
        self.assertEqual(1, len(result.unexpectedSuccesses))
1833
        # Inconsistency, unexpectedSuccesses is a list of tests,
1834
        # expectedFailures is a list of reasons?
1835
        test = result.unexpectedSuccesses[0]
1836
        details = test.getDetails()
1837
        self.assertTrue('log' in details)
1838
1839
5050.33.2 by Andrew Bennetts
More robust fix for TestCase cloning, this time with tests.
1840
class TestTestCloning(tests.TestCase):
1841
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
1842
1843
    def test_cloned_testcase_does_not_share_details(self):
1844
        """A TestCase cloned with clone_test does not share mutable attributes
1845
        such as details or cleanups.
1846
        """
1847
        class Test(tests.TestCase):
1848
            def test_foo(self):
1849
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
1850
        orig_test = Test('test_foo')
1851
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
1852
        orig_test.run(unittest.TestResult())
1853
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
1854
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
1855
1856
    def test_double_apply_scenario_preserves_first_scenario(self):
1857
        """Applying two levels of scenarios to a test preserves the attributes
1858
        added by both scenarios.
1859
        """
1860
        class Test(tests.TestCase):
1861
            def test_foo(self):
1862
                pass
1863
        test = Test('test_foo')
1864
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
1865
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
1866
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
1867
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
1868
        all_tests = list(tests.iter_suite_tests(suite))
1869
        self.assertLength(4, all_tests)
1870
        all_xys = sorted((t.x, t.y) for t in all_tests)
1871
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
1872
1873
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1874
# NB: Don't delete this; it's not actually from 0.11!
1875
@deprecated_function(deprecated_in((0, 11, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1876
def sample_deprecated_function():
1877
    """A deprecated function to test applyDeprecated with."""
1878
    return 2
1879
1880
1881
def sample_undeprecated_function(a_param):
1882
    """A undeprecated function to test applyDeprecated with."""
1883
1884
1885
class ApplyDeprecatedHelper(object):
1886
    """A helper class for ApplyDeprecated tests."""
1887
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1888
    @deprecated_method(deprecated_in((0, 11, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1889
    def sample_deprecated_method(self, param_one):
1890
        """A deprecated method for testing with."""
1891
        return param_one
1892
1893
    def sample_normal_method(self):
1894
        """A undeprecated method."""
1895
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1896
    @deprecated_method(deprecated_in((0, 10, 0)))
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1897
    def sample_nested_deprecation(self):
1898
        return sample_deprecated_function()
1899
1900
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1901
class TestExtraAssertions(tests.TestCase):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1902
    """Tests for new test assertions in breezy test suite"""
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1903
1904
    def test_assert_isinstance(self):
1905
        self.assertIsInstance(2, int)
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
1906
        self.assertIsInstance(u'', (str, text_type))
4449.3.43 by Martin Pool
More tests for assertIsInstance
1907
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1908
        self.assertEqual(str(e),
4449.3.43 by Martin Pool
More tests for assertIsInstance
1909
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1910
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
4449.3.43 by Martin Pool
More tests for assertIsInstance
1911
        e = self.assertRaises(AssertionError,
1912
            self.assertIsInstance, None, int, "it's just not")
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1913
        self.assertEqual(str(e),
4449.3.43 by Martin Pool
More tests for assertIsInstance
1914
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
1915
            ": it's just not")
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1916
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
1917
    def test_assertEndsWith(self):
1918
        self.assertEndsWith('foo', 'oo')
1919
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1920
4680.1.1 by Vincent Ladeuil
Surprisingly, assertEqualDiff was wrong.
1921
    def test_assertEqualDiff(self):
1922
        e = self.assertRaises(AssertionError,
1923
                              self.assertEqualDiff, '', '\n')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1924
        self.assertEqual(str(e),
4680.1.1 by Vincent Ladeuil
Surprisingly, assertEqualDiff was wrong.
1925
                          # Don't blink ! The '+' applies to the second string
1926
                          'first string is missing a final newline.\n+ \n')
1927
        e = self.assertRaises(AssertionError,
1928
                              self.assertEqualDiff, '\n', '')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1929
        self.assertEqual(str(e),
4680.1.1 by Vincent Ladeuil
Surprisingly, assertEqualDiff was wrong.
1930
                          # Don't blink ! The '-' applies to the second string
1931
                          'second string is missing a final newline.\n- \n')
1932
1933
1934
class TestDeprecations(tests.TestCase):
1935
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1936
    def test_applyDeprecated_not_deprecated(self):
1937
        sample_object = ApplyDeprecatedHelper()
1938
        # 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
1939
        self.assertRaises(AssertionError, self.applyDeprecated,
1940
            deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1941
            sample_object.sample_normal_method)
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1942
        self.assertRaises(AssertionError, self.applyDeprecated,
1943
            deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1944
            sample_undeprecated_function, "a param value")
1945
        # calling a deprecated callable (function or method) with the wrong
1946
        # expected deprecation fails.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1947
        self.assertRaises(AssertionError, self.applyDeprecated,
1948
            deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1949
            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
1950
        self.assertRaises(AssertionError, self.applyDeprecated,
1951
            deprecated_in((0, 10, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1952
            sample_deprecated_function)
1953
        # calling a deprecated callable (function or method) with the right
1954
        # expected deprecation returns the functions result.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1955
        self.assertEqual("a param value",
1956
            self.applyDeprecated(deprecated_in((0, 11, 0)),
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1957
            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
1958
        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
1959
            sample_deprecated_function))
1960
        # calling a nested deprecation with the wrong deprecation version
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1961
        # 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
1962
        # supplied version.
1963
        self.assertRaises(AssertionError, self.applyDeprecated,
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1964
            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
1965
        # calling a nested deprecation with the right deprecation value
1966
        # returns the calls result.
3948.3.1 by Martin Pool
Remove old static deprecation template strings, and update style of their tests
1967
        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
1968
            sample_object.sample_nested_deprecation))
1969
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1970
    def test_callDeprecated(self):
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1971
        def testfunc(be_deprecated, result=None):
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1972
            if be_deprecated is True:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1973
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1974
                                       stacklevel=1)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1975
            return result
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1976
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1977
        self.assertIs(None, result)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1978
        result = self.callDeprecated([], testfunc, False, 'result')
1551.8.8 by Aaron Bentley
Made assertDeprecated return the callable's result
1979
        self.assertEqual('result', result)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1980
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1551.8.9 by Aaron Bentley
Rename assertDeprecated to callDeprecated
1981
        self.callDeprecated([], testfunc, be_deprecated=False)
1910.2.10 by Aaron Bentley
Add tests for assertDeprecated
1982
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1983
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
1984
class TestWarningTests(tests.TestCase):
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1985
    """Tests for calling methods that raise warnings."""
1986
1987
    def test_callCatchWarnings(self):
1988
        def meth(a, b):
1989
            warnings.warn("this is your last warning")
1990
            return a + b
1991
        wlist, result = self.callCatchWarnings(meth, 1, 2)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1992
        self.assertEqual(3, result)
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1993
        # would like just to compare them, but UserWarning doesn't implement
1994
        # eq well
1995
        w0, = wlist
1996
        self.assertIsInstance(w0, UserWarning)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1997
        self.assertEqual("this is your last warning", str(w0))
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1998
1999
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2000
class TestConvenienceMakers(tests.TestCaseWithTransport):
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2001
    """Test for the make_* convenience functions."""
2002
2003
    def test_make_branch_and_tree_with_format(self):
2004
        # we should be able to supply a format to make_branch_and_tree
6670.4.3 by Jelmer Vernooij
Fix more imports.
2005
        self.make_branch_and_tree('a', format=breezy.bzr.bzrdir.BzrDirMetaFormat1())
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2006
        self.assertIsInstance(breezy.controldir.ControlDir.open('a')._format,
6670.4.3 by Jelmer Vernooij
Fix more imports.
2007
                              breezy.bzr.bzrdir.BzrDirMetaFormat1)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2008
1986.2.1 by Robert Collins
Bugfix - the name of the test for make_branch_and_memory_tree was wrong.
2009
    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
2010
        # we should be able to get a new branch and a mutable tree from
2011
        # TestCaseWithTransport
2012
        tree = self.make_branch_and_memory_tree('a')
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2013
        self.assertIsInstance(tree, breezy.memorytree.MemoryTree)
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
2014
4650.1.2 by Robert Collins
Remove unnecessary use of an SFTP server connection to test the behaviour of TestCase.make_branch_and_tree.
2015
    def test_make_tree_for_local_vfs_backed_transport(self):
2016
        # make_branch_and_tree has to use local branch and repositories
2017
        # when the vfs transport and local disk are colocated, even if
2018
        # a different transport is in use for url generation.
5017.3.24 by Vincent Ladeuil
selftest -s bt.test_selftest passing
2019
        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.
2020
        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.
2021
        tree = self.make_branch_and_tree('t1')
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
2022
        base = tree.controldir.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.
2023
        self.assertStartsWith(base, 'file://')
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
2024
        self.assertEqual(tree.controldir.root_transport,
2025
                tree.branch.controldir.root_transport)
2026
        self.assertEqual(tree.controldir.root_transport,
2027
                tree.branch.repository.controldir.root_transport)
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
2028
2029
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2030
class SelfTestHelper(object):
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2031
2032
    def run_selftest(self, **kwargs):
2033
        """Run selftest returning its output."""
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2034
        output = StringIO()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2035
        old_transport = breezy.tests.default_transport
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2036
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
2037
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
2038
        try:
2039
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
2040
        finally:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2041
            breezy.tests.default_transport = old_transport
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2042
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
2043
        output.seek(0)
2044
        return output
2045
2046
2047
class TestSelftest(tests.TestCase, SelfTestHelper):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2048
    """Tests of breezy.tests.selftest."""
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2049
2050
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
2051
        factory_called = []
2052
        def factory():
2053
            factory_called.append(True)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2054
            return TestUtil.TestSuite()
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2055
        out = StringIO()
2056
        err = StringIO()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2057
        self.apply_redirected(out, err, None, breezy.tests.selftest,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2058
            test_suite_factory=factory)
2059
        self.assertEqual([True], factory_called)
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
2060
4636.2.1 by Robert Collins
Test selftest --list-only and --randomize options using more precisely layers.
2061
    def factory(self):
2062
        """A test suite factory."""
2063
        class Test(tests.TestCase):
2064
            def a(self):
2065
                pass
2066
            def b(self):
2067
                pass
2068
            def c(self):
2069
                pass
2070
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
2071
2072
    def test_list_only(self):
2073
        output = self.run_selftest(test_suite_factory=self.factory,
2074
            list_only=True)
2075
        self.assertEqual(3, len(output.readlines()))
2076
2077
    def test_list_only_filtered(self):
2078
        output = self.run_selftest(test_suite_factory=self.factory,
2079
            list_only=True, pattern="Test.b")
2080
        self.assertEndsWith(output.getvalue(), "Test.b\n")
2081
        self.assertLength(1, output.readlines())
2082
2083
    def test_list_only_excludes(self):
2084
        output = self.run_selftest(test_suite_factory=self.factory,
2085
            list_only=True, exclude_pattern="Test.b")
2086
        self.assertNotContainsRe("Test.b", output.getvalue())
2087
        self.assertLength(2, output.readlines())
2088
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
2089
    def test_lsprof_tests(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
2090
        self.requireFeature(features.lsprof_feature)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
2091
        results = []
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
2092
        class Test(object):
2093
            def __call__(test, result):
2094
                test.run(result)
2095
            def run(test, result):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
2096
                results.append(result)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
2097
            def countTestCases(self):
2098
                return 1
2099
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
2100
        self.assertLength(1, results)
2101
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
2102
4636.2.1 by Robert Collins
Test selftest --list-only and --randomize options using more precisely layers.
2103
    def test_random(self):
2104
        # test randomising by listing a number of tests.
2105
        output_123 = self.run_selftest(test_suite_factory=self.factory,
2106
            list_only=True, random_seed="123")
2107
        output_234 = self.run_selftest(test_suite_factory=self.factory,
2108
            list_only=True, random_seed="234")
2109
        self.assertNotEqual(output_123, output_234)
2110
        # "Randominzing test order..\n\n
2111
        self.assertLength(5, output_123.readlines())
2112
        self.assertLength(5, output_234.readlines())
2113
2114
    def test_random_reuse_is_same_order(self):
2115
        # test randomising by listing a number of tests.
2116
        expected = self.run_selftest(test_suite_factory=self.factory,
2117
            list_only=True, random_seed="123")
2118
        repeated = self.run_selftest(test_suite_factory=self.factory,
2119
            list_only=True, random_seed="123")
2120
        self.assertEqual(expected.getvalue(), repeated.getvalue())
2121
4636.2.3 by Robert Collins
Layer tests for selftest --subunit better.
2122
    def test_runner_class(self):
4913.2.18 by John Arbash Meinel
Add a _CompatibilityThunkFeature.
2123
        self.requireFeature(features.subunit)
4636.2.3 by Robert Collins
Layer tests for selftest --subunit better.
2124
        from subunit import ProtocolTestCase
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
2125
        stream = self.run_selftest(
2126
            runner_class=tests.SubUnitBzrRunnerv1,
4636.2.3 by Robert Collins
Layer tests for selftest --subunit better.
2127
            test_suite_factory=self.factory)
2128
        test = ProtocolTestCase(stream)
2129
        result = unittest.TestResult()
2130
        test.run(result)
2131
        self.assertEqual(3, result.testsRun)
2132
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2133
    def test_starting_with_single_argument(self):
2134
        output = self.run_selftest(test_suite_factory=self.factory,
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2135
            starting_with=['breezy.tests.test_selftest.Test.a'],
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2136
            list_only=True)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2137
        self.assertEqual('breezy.tests.test_selftest.Test.a\n',
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2138
            output.getvalue())
2139
2140
    def test_starting_with_multiple_argument(self):
2141
        output = self.run_selftest(test_suite_factory=self.factory,
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2142
            starting_with=['breezy.tests.test_selftest.Test.a',
2143
                'breezy.tests.test_selftest.Test.b'],
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2144
            list_only=True)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2145
        self.assertEqual('breezy.tests.test_selftest.Test.a\n'
2146
            'breezy.tests.test_selftest.Test.b\n',
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2147
            output.getvalue())
2148
4636.2.2 by Robert Collins
Fix selftest tests for --transport to test each layer precisely.
2149
    def check_transport_set(self, transport_server):
2150
        captured_transport = []
2151
        def seen_transport(a_transport):
2152
            captured_transport.append(a_transport)
2153
        class Capture(tests.TestCase):
2154
            def a(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2155
                seen_transport(breezy.tests.default_transport)
4636.2.2 by Robert Collins
Fix selftest tests for --transport to test each layer precisely.
2156
        def factory():
2157
            return TestUtil.TestSuite([Capture("a")])
2158
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
2159
        self.assertEqual(transport_server, captured_transport[0])
2160
2161
    def test_transport_sftp(self):
4913.2.17 by John Arbash Meinel
Found another paramiko dependent
2162
        self.requireFeature(features.paramiko)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2163
        from breezy.tests import stub_sftp
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
2164
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
4636.2.2 by Robert Collins
Fix selftest tests for --transport to test each layer precisely.
2165
2166
    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.
2167
        self.check_transport_set(memory.MemoryServer)
4636.2.2 by Robert Collins
Fix selftest tests for --transport to test each layer precisely.
2168
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
2169
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2170
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2171
    # Does IO: reads test.list
2172
2173
    def test_load_list(self):
2174
        # Provide a list with one test - this test.
2175
        test_id_line = '%s\n' % self.id()
2176
        self.build_tree_contents([('test.list', test_id_line)])
2177
        # And generate a list of the tests in  the suite.
2178
        stream = self.run_selftest(load_list='test.list', list_only=True)
2179
        self.assertEqual(test_id_line, stream.getvalue())
2180
2181
    def test_load_unknown(self):
2182
        # Provide a list with one test - this test.
2183
        # And generate a list of the tests in  the suite.
2184
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
2185
            load_list='missing file name', list_only=True)
2186
2187
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2188
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
2189
2190
    _test_needs_features = [features.subunit]
2191
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2192
    def run_subunit_stream(self, test_name):
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2193
        from subunit import ProtocolTestCase
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2194
        def factory():
2195
            return TestUtil.TestSuite([_get_test(test_name)])
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
2196
        stream = self.run_selftest(
2197
            runner_class=tests.SubUnitBzrRunnerv1,
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2198
            test_suite_factory=factory)
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2199
        test = ProtocolTestCase(stream)
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2200
        result = testtools.TestResult()
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2201
        test.run(result)
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2202
        content = stream.getvalue()
2203
        return content, result
2204
2205
    def test_fail_has_log(self):
2206
        content, result = self.run_subunit_stream('test_fail')
2207
        self.assertEqual(1, len(result.failures))
2208
        self.assertContainsRe(content, '(?m)^log$')
2209
        self.assertContainsRe(content, 'this test will fail')
2210
2211
    def test_error_has_log(self):
2212
        content, result = self.run_subunit_stream('test_error')
2213
        self.assertContainsRe(content, '(?m)^log$')
2214
        self.assertContainsRe(content, 'this test errored')
2215
2216
    def test_skip_has_no_log(self):
2217
        content, result = self.run_subunit_stream('test_skip')
2218
        self.assertNotContainsRe(content, '(?m)^log$')
2219
        self.assertNotContainsRe(content, 'this test will be skipped')
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2220
        reasons = _get_skip_reasons(result)
2221
        self.assertEqual({'reason'}, set(reasons))
2222
        skips = reasons['reason']
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2223
        self.assertEqual(1, len(skips))
2224
        test = skips[0]
2225
        # RemotedTestCase doesn't preserve the "details"
2226
        ## self.assertFalse('log' in test.getDetails())
2227
2228
    def test_missing_feature_has_no_log(self):
2229
        content, result = self.run_subunit_stream('test_missing_feature')
2230
        self.assertNotContainsRe(content, '(?m)^log$')
2231
        self.assertNotContainsRe(content, 'missing the feature')
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2232
        reasons = _get_skip_reasons(result)
2233
        self.assertEqual({'_MissingFeature\n'}, set(reasons))
2234
        skips = reasons['_MissingFeature\n']
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2235
        self.assertEqual(1, len(skips))
2236
        test = skips[0]
2237
        # RemotedTestCase doesn't preserve the "details"
2238
        ## self.assertFalse('log' in test.getDetails())
2239
2240
    def test_xfail_has_no_log(self):
2241
        content, result = self.run_subunit_stream('test_xfail')
2242
        self.assertNotContainsRe(content, '(?m)^log$')
2243
        self.assertNotContainsRe(content, 'test with expected failure')
2244
        self.assertEqual(1, len(result.expectedFailures))
2245
        result_content = result.expectedFailures[0][1]
6015.33.14 by Martin Packman
Adapt test_selftest output regexps to accept both old and new testtools output
2246
        self.assertNotContainsRe(result_content,
2247
            '(?m)^(?:Text attachment: )?log(?:$|: )')
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2248
        self.assertNotContainsRe(result_content, 'test with expected failure')
2249
2250
    def test_unexpected_success_has_log(self):
2251
        content, result = self.run_subunit_stream('test_unexpected_success')
2252
        self.assertContainsRe(content, '(?m)^log$')
2253
        self.assertContainsRe(content, 'test with unexpected success')
5892.1.1 by Martin
Stop expecting subunit to get unexpected successes wrong if it has the recent fix
2254
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2255
        #                success, if a min version check is added remove this
2256
        from subunit import TestProtocolClient as _Client
6619.3.24 by Jelmer Vernooij
Run 2to3 methodattrs fixer.
2257
        if _Client.addUnexpectedSuccess.__func__ is _Client.addSuccess.__func__:
5892.1.1 by Martin
Stop expecting subunit to get unexpected successes wrong if it has the recent fix
2258
            self.expectFailure('subunit treats "unexpectedSuccess"'
2259
                               ' as a plain success',
2260
                self.assertEqual, 1, len(result.unexpectedSuccesses))
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2261
        self.assertEqual(1, len(result.unexpectedSuccesses))
2262
        test = result.unexpectedSuccesses[0]
2263
        # RemotedTestCase doesn't preserve the "details"
2264
        ## self.assertTrue('log' in test.getDetails())
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2265
2266
    def test_success_has_no_log(self):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
2267
        content, result = self.run_subunit_stream('test_success')
5387.2.5 by John Arbash Meinel
add a failing test that the subunit stream doesn't contain the log info.
2268
        self.assertEqual(1, result.testsRun)
2269
        self.assertNotContainsRe(content, '(?m)^log$')
2270
        self.assertNotContainsRe(content, 'this test succeeds')
2271
2272
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2273
class TestRunBzr(tests.TestCase):
2274
2275
    out = ''
2276
    err = ''
2277
2278
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2279
                         working_dir=None):
2280
        """Override _run_bzr_core to test how it is invoked by run_bzr.
2281
2282
        Attempts to run bzr from inside this class don't actually run it.
2283
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2284
        We test how run_bzr actually invokes bzr in another location.  Here we
2285
        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.
2286
        """
2287
        self.argv = list(argv)
2288
        self.retcode = retcode
2289
        self.encoding = encoding
2290
        self.stdin = stdin
2291
        self.working_dir = working_dir
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2292
        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.
2293
2294
    def test_run_bzr_error(self):
2295
        self.out = "It sure does!\n"
2296
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2297
        self.assertEqual(['rocks'], self.argv)
2298
        self.assertEqual(34, self.retcode)
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2299
        self.assertEqual('It sure does!\n', out)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2300
        self.assertEqual(out, self.out)
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2301
        self.assertEqual('', err)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2302
        self.assertEqual(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.
2303
2304
    def test_run_bzr_error_regexes(self):
2305
        self.out = ''
2306
        self.err = "bzr: ERROR: foobarbaz is not versioned"
2307
        out, err = self.run_bzr_error(
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2308
            ["bzr: ERROR: foobarbaz is not versioned"],
2309
            ['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.
2310
2311
    def test_encoding(self):
2312
        """Test that run_bzr passes encoding to _run_bzr_core"""
2313
        self.run_bzr('foo bar')
2314
        self.assertEqual(None, self.encoding)
2315
        self.assertEqual(['foo', 'bar'], self.argv)
2316
2317
        self.run_bzr('foo bar', encoding='baz')
2318
        self.assertEqual('baz', self.encoding)
2319
        self.assertEqual(['foo', 'bar'], self.argv)
2320
2321
    def test_retcode(self):
2322
        """Test that run_bzr passes retcode to _run_bzr_core"""
2323
        # Default is retcode == 0
2324
        self.run_bzr('foo bar')
2325
        self.assertEqual(0, self.retcode)
2326
        self.assertEqual(['foo', 'bar'], self.argv)
2327
2328
        self.run_bzr('foo bar', retcode=1)
2329
        self.assertEqual(1, self.retcode)
2330
        self.assertEqual(['foo', 'bar'], self.argv)
2331
2332
        self.run_bzr('foo bar', retcode=None)
2333
        self.assertEqual(None, self.retcode)
2334
        self.assertEqual(['foo', 'bar'], self.argv)
2335
2336
        self.run_bzr(['foo', 'bar'], retcode=3)
2337
        self.assertEqual(3, self.retcode)
2338
        self.assertEqual(['foo', 'bar'], self.argv)
2339
2340
    def test_stdin(self):
2341
        # test that the stdin keyword to run_bzr is passed through to
2342
        # _run_bzr_core as-is. We do this by overriding
2343
        # _run_bzr_core in this class, and then calling run_bzr,
2344
        # which is a convenience function for _run_bzr_core, so
2345
        # should invoke it.
2346
        self.run_bzr('foo bar', stdin='gam')
2347
        self.assertEqual('gam', self.stdin)
2348
        self.assertEqual(['foo', 'bar'], self.argv)
2349
2350
        self.run_bzr('foo bar', stdin='zippy')
2351
        self.assertEqual('zippy', self.stdin)
2352
        self.assertEqual(['foo', 'bar'], self.argv)
2353
2354
    def test_working_dir(self):
2355
        """Test that run_bzr passes working_dir to _run_bzr_core"""
2356
        self.run_bzr('foo bar')
2357
        self.assertEqual(None, self.working_dir)
2358
        self.assertEqual(['foo', 'bar'], self.argv)
2359
2360
        self.run_bzr('foo bar', working_dir='baz')
2361
        self.assertEqual('baz', self.working_dir)
2362
        self.assertEqual(['foo', 'bar'], self.argv)
2363
2364
    def test_reject_extra_keyword_arguments(self):
2365
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
2366
                          error_regex=['error message'])
2367
2368
2369
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2370
    # Does IO when testing the working_dir parameter.
2371
2372
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2373
                         a_callable=None, *args, **kwargs):
2374
        self.stdin = stdin
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2375
        self.factory_stdin = getattr(breezy.ui.ui_factory, "stdin", None)
2376
        self.factory = breezy.ui.ui_factory
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2377
        self.working_dir = osutils.getcwd()
2378
        stdout.write('foo\n')
2379
        stderr.write('bar\n')
2380
        return 0
2381
2382
    def test_stdin(self):
2383
        # test that the stdin keyword to _run_bzr_core is passed through to
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2384
        # apply_redirected as a StringIO. We do this by overriding
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2385
        # apply_redirected in this class, and then calling _run_bzr_core,
2386
        # which calls apply_redirected.
2387
        self.run_bzr(['foo', 'bar'], stdin='gam')
2388
        self.assertEqual('gam', self.stdin.read())
2389
        self.assertTrue(self.stdin is self.factory_stdin)
2390
        self.run_bzr(['foo', 'bar'], stdin='zippy')
2391
        self.assertEqual('zippy', self.stdin.read())
2392
        self.assertTrue(self.stdin is self.factory_stdin)
2393
2394
    def test_ui_factory(self):
2395
        # each invocation of self.run_bzr should get its
2396
        # own UI factory, which is an instance of TestUIFactory,
2397
        # with stdin, stdout and stderr attached to the stdin,
2398
        # stdout and stderr of the invoked run_bzr
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2399
        current_factory = breezy.ui.ui_factory
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2400
        self.run_bzr(['foo'])
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
2401
        self.assertFalse(current_factory is self.factory)
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2402
        self.assertNotEqual(sys.stdout, self.factory.stdout)
2403
        self.assertNotEqual(sys.stderr, self.factory.stderr)
2404
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
2405
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
2406
        self.assertIsInstance(self.factory, tests.TestUIFactory)
2407
2408
    def test_working_dir(self):
2409
        self.build_tree(['one/', 'two/'])
2410
        cwd = osutils.getcwd()
2411
2412
        # Default is to work in the current directory
2413
        self.run_bzr(['foo', 'bar'])
2414
        self.assertEqual(cwd, self.working_dir)
2415
2416
        self.run_bzr(['foo', 'bar'], working_dir=None)
2417
        self.assertEqual(cwd, self.working_dir)
2418
2419
        # The function should be run in the alternative directory
2420
        # but afterwards the current working dir shouldn't be changed
2421
        self.run_bzr(['foo', 'bar'], working_dir='one')
2422
        self.assertNotEqual(cwd, self.working_dir)
2423
        self.assertEndsWith(self.working_dir, 'one')
2424
        self.assertEqual(cwd, osutils.getcwd())
2425
2426
        self.run_bzr(['foo', 'bar'], working_dir='two')
2427
        self.assertNotEqual(cwd, self.working_dir)
2428
        self.assertEndsWith(self.working_dir, 'two')
2429
        self.assertEqual(cwd, osutils.getcwd())
2430
2431
2432
class StubProcess(object):
2433
    """A stub process for testing run_bzr_subprocess."""
2434
    
2435
    def __init__(self, out="", err="", retcode=0):
2436
        self.out = out
2437
        self.err = err
2438
        self.returncode = retcode
2439
2440
    def communicate(self):
2441
        return self.out, self.err
2442
2443
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2444
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2445
    """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.
2446
2447
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
2448
        super(TestWithFakedStartBzrSubprocess, self).setUp()
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2449
        self.subprocess_calls = []
2450
2451
    def start_bzr_subprocess(self, process_args, env_changes=None,
2452
                             skip_if_plan_to_signal=False,
2453
                             working_dir=None,
2454
                             allow_plugins=False):
2455
        """capture what run_bzr_subprocess tries to do."""
2456
        self.subprocess_calls.append({'process_args':process_args,
2457
            'env_changes':env_changes,
2458
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
2459
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
2460
        return self.next_subprocess
2461
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2462
2463
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2464
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2465
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2466
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
2467
2468
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2469
        that will return static results. This assertion method populates those
2470
        results and also checks the arguments run_bzr_subprocess generates.
2471
        """
2472
        self.next_subprocess = process
2473
        try:
2474
            result = self.run_bzr_subprocess(*args, **kwargs)
2475
        except:
2476
            self.next_subprocess = None
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2477
            for key, expected in expected_args.items():
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2478
                self.assertEqual(expected, self.subprocess_calls[-1][key])
2479
            raise
2480
        else:
2481
            self.next_subprocess = None
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
2482
            for key, expected in expected_args.items():
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2483
                self.assertEqual(expected, self.subprocess_calls[-1][key])
2484
            return result
2485
2486
    def test_run_bzr_subprocess(self):
2487
        """The run_bzr_helper_external command behaves nicely."""
2488
        self.assertRunBzrSubprocess({'process_args':['--version']},
2489
            StubProcess(), '--version')
2490
        self.assertRunBzrSubprocess({'process_args':['--version']},
2491
            StubProcess(), ['--version'])
2492
        # retcode=None disables retcode checking
2493
        result = self.assertRunBzrSubprocess({},
2494
            StubProcess(retcode=3), '--version', retcode=None)
2495
        result = self.assertRunBzrSubprocess({},
2496
            StubProcess(out="is free software"), '--version')
2497
        self.assertContainsRe(result[0], 'is free software')
2498
        # Running a subcommand that is missing errors
2499
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2500
            {'process_args':['--versionn']}, StubProcess(retcode=3),
2501
            '--versionn')
2502
        # Unless it is told to expect the error from the subprocess
2503
        result = self.assertRunBzrSubprocess({},
2504
            StubProcess(retcode=3), '--versionn', retcode=3)
2505
        # Or to ignore retcode checking
2506
        result = self.assertRunBzrSubprocess({},
2507
            StubProcess(err="unknown command", retcode=3), '--versionn',
2508
            retcode=None)
2509
        self.assertContainsRe(result[1], 'unknown command')
2510
2511
    def test_env_change_passes_through(self):
2512
        self.assertRunBzrSubprocess(
2513
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2514
            StubProcess(), '',
2515
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2516
2517
    def test_no_working_dir_passed_as_None(self):
2518
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2519
2520
    def test_no_working_dir_passed_through(self):
2521
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2522
            working_dir='dir')
2523
2524
    def test_run_bzr_subprocess_no_plugins(self):
2525
        self.assertRunBzrSubprocess({'allow_plugins': False},
2526
            StubProcess(), '')
2527
2528
    def test_allow_plugins(self):
2529
        self.assertRunBzrSubprocess({'allow_plugins': True},
2530
            StubProcess(), '', allow_plugins=True)
2531
2532
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2533
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2534
2535
    def test_finish_bzr_subprocess_with_error(self):
2536
        """finish_bzr_subprocess allows specification of the desired exit code.
2537
        """
2538
        process = StubProcess(err="unknown command", retcode=3)
2539
        result = self.finish_bzr_subprocess(process, retcode=3)
2540
        self.assertEqual('', result[0])
2541
        self.assertContainsRe(result[1], 'unknown command')
2542
2543
    def test_finish_bzr_subprocess_ignoring_retcode(self):
2544
        """finish_bzr_subprocess allows the exit code to be ignored."""
2545
        process = StubProcess(err="unknown command", retcode=3)
2546
        result = self.finish_bzr_subprocess(process, retcode=None)
2547
        self.assertEqual('', result[0])
2548
        self.assertContainsRe(result[1], 'unknown command')
2549
2550
    def test_finish_subprocess_with_unexpected_retcode(self):
2551
        """finish_bzr_subprocess raises self.failureException if the retcode is
2552
        not the expected one.
2553
        """
2554
        process = StubProcess(err="unknown command", retcode=3)
2555
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2556
                          process)
2557
2558
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2559
class _DontSpawnProcess(Exception):
2560
    """A simple exception which just allows us to skip unnecessary steps"""
2561
2562
5984.1.3 by Vincent Ladeuil
We don't need TestCaseInTempDir as we shouldn't touch the disk anyway.
2563
class TestStartBzrSubProcess(tests.TestCase):
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2564
    """Stub test start_bzr_subprocess."""
2565
5984.1.2 by Vincent Ladeuil
Really fix it.
2566
    def _subprocess_log_cleanup(self):
2567
        """Inhibits the base version as we don't produce a log file."""
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2568
2569
    def _popen(self, *args, **kwargs):
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2570
        """Override the base version to record the command that is run.
2571
2572
        From there we can ensure it is correct without spawning a real process.
2573
        """
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2574
        self.check_popen_state()
2575
        self._popen_args = args
2576
        self._popen_kwargs = kwargs
2577
        raise _DontSpawnProcess()
2578
5984.1.2 by Vincent Ladeuil
Really fix it.
2579
    def check_popen_state(self):
2580
        """Replace to make assertions when popen is called."""
2581
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2582
    def test_run_bzr_subprocess_no_plugins(self):
2583
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2584
        command = self._popen_args[0]
2585
        self.assertEqual(sys.executable, command[0])
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
2586
        self.assertEqual(self.get_brz_path(), command[1])
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2587
        self.assertEqual(['--no-plugins'], command[2:])
2588
2589
    def test_allow_plugins(self):
2590
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2591
                          allow_plugins=True)
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2592
        command = self._popen_args[0]
2593
        self.assertEqual([], command[2:])
2594
2595
    def test_set_env(self):
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
2596
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2597
        # set in the child
2598
        def check_environment():
2599
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2600
        self.check_popen_state = check_environment
2601
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2602
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2603
        # not set in theparent
2604
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2605
2606
    def test_run_bzr_subprocess_env_del(self):
2607
        """run_bzr_subprocess can remove environment variables too."""
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
2608
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2609
        def check_environment():
2610
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2611
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2612
        self.check_popen_state = check_environment
2613
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2614
                          env_changes={'EXISTANT_ENV_VAR':None})
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2615
        # Still set in parent
2616
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2617
        del os.environ['EXISTANT_ENV_VAR']
2618
2619
    def test_env_del_missing(self):
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
2620
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2621
        def check_environment():
2622
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2623
        self.check_popen_state = check_environment
2624
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2625
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2626
2627
    def test_working_dir(self):
2628
        """Test that we can specify the working dir for the child"""
2629
        orig_getcwd = osutils.getcwd
2630
        orig_chdir = os.chdir
2631
        chdirs = []
2632
        def chdir(path):
2633
            chdirs.append(path)
5984.1.1 by Vincent Ladeuil
Some cleanup and a first try at fixing bug #798698.
2634
        self.overrideAttr(os, 'chdir', chdir)
2635
        def getcwd():
2636
            return 'current'
2637
        self.overrideAttr(osutils, 'getcwd', getcwd)
2638
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2639
                          working_dir='foo')
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2640
        self.assertEqual(['foo', 'current'], chdirs)
2641
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2642
    def test_get_brz_path_with_cwd_breezy(self):
5340.3.1 by Martin
Add test for problem with TestCase.get_bzr_path method
2643
        self.get_source_path = lambda: ""
2644
        self.overrideAttr(os.path, "isfile", lambda path: True)
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
2645
        self.assertEqual(self.get_brz_path(), "brz")
5340.3.1 by Martin
Add test for problem with TestCase.get_bzr_path method
2646
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2647
4650.1.4 by Robert Collins
Make tests for finish_bzr_subprocess that really only care about the interface use StubProcess.
2648
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2649
    """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.
2650
2651
    def test_start_and_stop_bzr_subprocess_send_signal(self):
2652
        """finish_bzr_subprocess raises self.failureException if the retcode is
2653
        not the expected one.
2654
        """
4695.3.2 by Vincent Ladeuil
Simplified and claried as per Robert's review.
2655
        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.
2656
        process = self.start_bzr_subprocess(['wait-until-signalled'],
2657
                                            skip_if_plan_to_signal=True)
2658
        self.assertEqual('running\n', process.stdout.readline())
2659
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2660
                                            retcode=3)
2661
        self.assertEqual('', result[0])
6622.1.4 by Jelmer Vernooij
Fix some more tests.
2662
        self.assertEqual('brz: interrupted\n', result[1])
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
2663
2664
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2665
class TestSelftestFiltering(tests.TestCase):
2394.2.5 by Ian Clatworthy
list-only working, include test not
2666
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2667
    def setUp(self):
6552.1.3 by Vincent Ladeuil
Use super() instead of calling <base>.setup(self), as the original fix illustrated a too-easy-to-fall-into trap.
2668
        super(TestSelftestFiltering, self).setUp()
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2669
        self.suite = TestUtil.TestSuite()
2670
        self.loader = TestUtil.TestLoader()
4636.2.5 by Robert Collins
Minor tweaks to clarity in slower selftest tests.
2671
        self.suite.addTest(self.loader.loadTestsFromModule(
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2672
            sys.modules['breezy.tests.test_selftest']))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2673
        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
2674
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2675
    def test_condition_id_re(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2676
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2677
            'test_condition_id_re')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2678
        filtered_suite = tests.filter_suite_by_condition(
2679
            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.
2680
        self.assertEqual([test_name], _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2681
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2682
    def test_condition_id_in_list(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2683
        test_names = ['breezy.tests.test_selftest.TestSelftestFiltering.'
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2684
                      'test_condition_id_in_list']
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2685
        id_list = tests.TestIdList(test_names)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2686
        filtered_suite = tests.filter_suite_by_condition(
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2687
            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.
2688
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2689
        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.
2690
        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.
2691
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2692
    def test_condition_id_startswith(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2693
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2694
        start1 = klass + 'test_condition_id_starts'
2695
        start2 = klass + 'test_condition_id_in'
2696
        test_names = [ klass + 'test_condition_id_in_list',
2697
                      klass + 'test_condition_id_startswith',
2698
                     ]
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2699
        filtered_suite = tests.filter_suite_by_condition(
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2700
            self.suite, tests.condition_id_startswith([start1, start2]))
2701
        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.
2702
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
2703
    def test_condition_isinstance(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2704
        filtered_suite = tests.filter_suite_by_condition(
2705
            self.suite, tests.condition_isinstance(self.__class__))
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2706
        class_pattern = 'breezy.tests.test_selftest.TestSelftestFiltering.'
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2707
        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.
2708
        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
2709
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2710
    def test_exclude_tests_by_condition(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2711
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2712
            'test_exclude_tests_by_condition')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2713
        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
2714
            lambda x:x.id() == excluded_name)
2715
        self.assertEqual(len(self.all_names) - 1,
2716
            filtered_suite.countTestCases())
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2717
        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
2718
        remaining_names = list(self.all_names)
2719
        remaining_names.remove(excluded_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2720
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2721
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2722
    def test_exclude_tests_by_re(self):
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2723
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2724
        filtered_suite = tests.exclude_tests_by_re(self.suite,
2725
                                                   'exclude_tests_by_re')
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2726
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2727
            'test_exclude_tests_by_re')
2728
        self.assertEqual(len(self.all_names) - 1,
2729
            filtered_suite.countTestCases())
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2730
        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
2731
        remaining_names = list(self.all_names)
2732
        remaining_names.remove(excluded_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2733
        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
2734
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2735
    def test_filter_suite_by_condition(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2736
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2737
            'test_filter_suite_by_condition')
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2738
        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
2739
            lambda x:x.id() == test_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2740
        self.assertEqual([test_name], _test_ids(filtered_suite))
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2741
2394.2.5 by Ian Clatworthy
list-only working, include test not
2742
    def test_filter_suite_by_re(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2743
        filtered_suite = tests.filter_suite_by_re(self.suite,
2744
                                                  'test_filter_suite_by_r')
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2745
        filtered_names = _test_ids(filtered_suite)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2746
        self.assertEqual(filtered_names, ['breezy.tests.test_selftest.'
2394.2.7 by Ian Clatworthy
Added whitebox tests - filter_suite_by_re and sort_suite_by_re
2747
            '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
2748
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2749
    def test_filter_suite_by_id_list(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2750
        test_list = ['breezy.tests.test_selftest.'
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2751
                     '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.
2752
        filtered_suite = tests.filter_suite_by_id_list(
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2753
            self.suite, tests.TestIdList(test_list))
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2754
        filtered_names = _test_ids(filtered_suite)
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2755
        self.assertEqual(
2756
            filtered_names,
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2757
            ['breezy.tests.test_selftest.'
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2758
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
2759
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2760
    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.
2761
        # 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.
2762
        # begins with one of the start value used.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2763
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2764
        start1 = klass + 'test_filter_suite_by_id_starts'
2765
        start2 = klass + 'test_filter_suite_by_id_li'
2766
        test_list = [klass + 'test_filter_suite_by_id_list',
2767
                     klass + 'test_filter_suite_by_id_startswith',
2768
                     ]
2769
        filtered_suite = tests.filter_suite_by_id_startswith(
2770
            self.suite, [start1, start2])
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2771
        self.assertEqual(
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2772
            test_list,
2773
            _test_ids(filtered_suite),
2774
            )
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
2775
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2776
    def test_preserve_input(self):
2777
        # NB: Surely this is something in the stdlib to do this?
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2778
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
2779
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2780
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
2781
    def test_randomize_suite(self):
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2782
        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.
2783
        # randomizing should not add or remove test names.
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2784
        self.assertEqual(set(_test_ids(self.suite)),
2785
                         set(_test_ids(randomized_suite)))
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
2786
        # Technically, this *can* fail, because random.shuffle(list) can be
2787
        # equal to list. Trying multiple times just pushes the frequency back.
2788
        # As its len(self.all_names)!:1, the failure frequency should be low
2789
        # enough to ignore. RBC 20071021.
2790
        # It should change the order.
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2791
        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
2792
        # But not the length. (Possibly redundant with the set test, but not
2793
        # necessarily.)
3302.7.4 by Vincent Ladeuil
Cosmetic change.
2794
        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
2795
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
2796
    def test_split_suit_by_condition(self):
2797
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2798
        condition = tests.condition_id_re('test_filter_suite_by_r')
2799
        split_suite = tests.split_suite_by_condition(self.suite, condition)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2800
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
2801
            'test_filter_suite_by_re')
2802
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2803
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2804
        remaining_names = list(self.all_names)
2805
        remaining_names.remove(filtered_name)
2806
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2807
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2808
    def test_split_suit_by_re(self):
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2809
        self.all_names = _test_ids(self.suite)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2810
        split_suite = tests.split_suite_by_re(self.suite,
2811
                                              'test_filter_suite_by_r')
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2812
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2813
            'test_filter_suite_by_re')
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2814
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2815
        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
2816
        remaining_names = list(self.all_names)
2817
        remaining_names.remove(filtered_name)
3302.7.1 by Vincent Ladeuil
Extract _test_ids helper for reuse by other test classes.
2818
        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
2819
2545.3.2 by James Westby
Add a test for check_inventory_shape.
2820
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
2821
class TestCheckTreeShape(tests.TestCaseWithTransport):
2545.3.2 by James Westby
Add a test for check_inventory_shape.
2822
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
2823
    def test_check_tree_shape(self):
2561.1.2 by Aaron Bentley
Fix indenting in TestCheckInventoryShape
2824
        files = ['a', 'b/', 'b/c']
2825
        tree = self.make_branch_and_tree('.')
2826
        self.build_tree(files)
2827
        tree.add(files)
2828
        tree.lock_read()
2829
        try:
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
2830
            self.check_tree_shape(tree, files)
2561.1.2 by Aaron Bentley
Fix indenting in TestCheckInventoryShape
2831
        finally:
2832
            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
2833
2834
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2835
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
2836
    """Tests for testsuite blackbox features."""
2837
2838
    def test_run_bzr_failure_not_caught(self):
2839
        # When we run bzr in blackbox mode, we want any unexpected errors to
2840
        # propagate up to the test suite so that it can show the error in the
2841
        # usual way, and we won't get a double traceback.
2842
        e = self.assertRaises(
2843
            AssertionError,
2844
            self.run_bzr, ['assert-fail'])
2845
        # make sure we got the real thing, not an error from somewhere else in
2846
        # the test framework
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2847
        self.assertEqual('always fails', str(e))
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
2848
        # check that there's no traceback in the test log
4794.1.15 by Robert Collins
Review feedback.
2849
        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
2850
2851
    def test_run_bzr_user_error_caught(self):
2852
        # Running bzr in blackbox mode, normal/expected/user errors should be
2853
        # caught in the regular way and turned into an error message plus exit
2854
        # 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.
2855
        transport_server = memory.MemoryServer()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2856
        transport_server.start_server()
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
2857
        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.
2858
        url = transport_server.get_url()
2859
        self.permit_url(url)
2860
        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
2861
        self.assertEqual(out, '')
3146.4.7 by Aaron Bentley
Remove UNIX path assumption
2862
        self.assertContainsRe(err,
6622.1.4 by Jelmer Vernooij
Fix some more tests.
2863
            'brz: ERROR: Not a branch: ".*nonexistantpath/".\n')
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2864
2865
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2866
class TestTestLoader(tests.TestCase):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2867
    """Tests for the test loader."""
2868
2869
    def _get_loader_and_module(self):
2870
        """Gets a TestLoader and a module with one test in it."""
2871
        loader = TestUtil.TestLoader()
2872
        module = {}
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2873
        class Stub(tests.TestCase):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2874
            def test_foo(self):
2875
                pass
2876
        class MyModule(object):
2877
            pass
2878
        MyModule.a_class = Stub
2879
        module = MyModule()
6625.1.5 by Martin
Drop custom load_tests implementation and use unittest signature
2880
        module.__name__ = 'fake_module'
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2881
        return loader, module
2882
2883
    def test_module_no_load_tests_attribute_loads_classes(self):
2884
        loader, module = self._get_loader_and_module()
2885
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2886
2887
    def test_module_load_tests_attribute_gets_called(self):
2888
        loader, module = self._get_loader_and_module()
6625.1.5 by Martin
Drop custom load_tests implementation and use unittest signature
2889
        def load_tests(loader, standard_tests, pattern):
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2890
            result = loader.suiteClass()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2891
            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``
2892
                result.addTests([test, test])
2893
            return result
2894
        # add a load_tests() method which multiplies the tests from the module.
6625.1.5 by Martin
Drop custom load_tests implementation and use unittest signature
2895
        module.__class__.load_tests = staticmethod(load_tests)
2896
        self.assertEqual(
2897
            2 * [str(module.a_class('test_foo'))],
2898
            list(map(str, loader.loadTestsFromModule(module))))
2921.6.13 by Robert Collins
* Modules can now customise their tests by defining a ``load_tests``
2899
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2900
    def test_load_tests_from_module_name_smoke_test(self):
2901
        loader = TestUtil.TestLoader()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2902
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
2903
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2904
                          _test_ids(suite))
2905
3302.7.8 by Vincent Ladeuil
Fix typos.
2906
    def test_load_tests_from_module_name_with_bogus_module_name(self):
3302.7.3 by Vincent Ladeuil
Prepare TestLoader for specialization.
2907
        loader = TestUtil.TestLoader()
2908
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2909
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2910
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2911
class TestTestIdList(tests.TestCase):
2912
2913
    def _create_id_list(self, test_list):
2914
        return tests.TestIdList(test_list)
2915
2916
    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.
2917
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2918
        class Stub(tests.TestCase):
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
2919
            def test_foo(self):
2920
                pass
2921
2922
        def _create_test_id(id):
2923
            return lambda: id
2924
2925
        suite = TestUtil.TestSuite()
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2926
        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.
2927
            t  = Stub('test_foo')
2928
            t.id = _create_test_id(id)
2929
            suite.addTest(t)
2930
        return suite
2931
2932
    def _test_ids(self, test_suite):
2933
        """Get the ids for the tests in a test suite."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2934
        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.
2935
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2936
    def test_empty_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2937
        id_list = self._create_id_list([])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2938
        self.assertEqual({}, id_list.tests)
2939
        self.assertEqual({}, id_list.modules)
3193.1.1 by Vincent Ladeuil
Helper to filter test suite building by module when loading a list.
2940
2941
    def test_valid_list(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2942
        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
2943
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2944
             'mod1.func1', 'mod1.cl2.meth2',
2945
             'mod1.submod1',
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
2946
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2947
             ])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2948
        self.assertTrue(id_list.refers_to('mod1'))
2949
        self.assertTrue(id_list.refers_to('mod1.submod1'))
2950
        self.assertTrue(id_list.refers_to('mod1.submod2'))
2951
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2952
        self.assertTrue(id_list.includes('mod1.submod1'))
2953
        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.
2954
2955
    def test_bad_chars_in_params(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2956
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2957
        self.assertTrue(id_list.refers_to('mod1'))
2958
        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
2959
2960
    def test_module_used(self):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2961
        id_list = self._create_id_list(['mod.class.meth'])
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2962
        self.assertTrue(id_list.refers_to('mod'))
2963
        self.assertTrue(id_list.refers_to('mod.class'))
2964
        self.assertTrue(id_list.refers_to('mod.class.meth'))
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2965
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2966
    def test_test_suite_matches_id_list_with_unknown(self):
2967
        loader = TestUtil.TestLoader()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2968
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
2969
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2970
                     'bogus']
2971
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2972
        self.assertEqual(['bogus'], not_found)
2973
        self.assertEqual([], duplicates)
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2974
2975
    def test_suite_matches_id_list_with_duplicates(self):
2976
        loader = TestUtil.TestLoader()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2977
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2978
        dupes = loader.suiteClass()
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
2979
        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
2980
            dupes.addTest(test)
2981
            dupes.addTest(test) # Add it again
2982
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2983
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',]
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2984
        not_found, duplicates = tests.suite_matches_id_list(
2985
            dupes, test_list)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2986
        self.assertEqual([], not_found)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2987
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2988
                          duplicates)
2989
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2990
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
2991
class TestTestSuite(tests.TestCase):
2992
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
2993
    def test__test_suite_testmod_names(self):
2994
        # Test that a plausible list of test module names are returned
2995
        # by _test_suite_testmod_names.
2996
        test_list = tests._test_suite_testmod_names()
2997
        self.assertSubset([
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2998
            'breezy.tests.blackbox',
2999
            'breezy.tests.per_transport',
3000
            'breezy.tests.test_selftest',
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3001
            ],
3002
            test_list)
3003
3004
    def test__test_suite_modules_to_doctest(self):
3005
        # Test that a plausible list of modules to doctest is returned
3006
        # by _test_suite_modules_to_doctest.
3007
        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
3008
        if __doc__ is None:
3009
            # When docstrings are stripped, there are no modules to doctest
3010
            self.assertEqual([], test_list)
3011
            return
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3012
        self.assertSubset([
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3013
            'breezy.timestamp',
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3014
            ],
3015
            test_list)
3016
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3017
    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.
3018
        # test_suite() loads the entire test suite to operate. To avoid this
3019
        # overhead, and yet still be confident that things are happening,
3020
        # we temporarily replace two functions used by test_suite with 
3021
        # test doubles that supply a few sample tests to load, and check they
3022
        # are loaded.
3023
        calls = []
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
3024
        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.
3025
            calls.append("testmod_names")
3026
            return [
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3027
                'breezy.tests.blackbox.test_branch',
3028
                'breezy.tests.per_transport',
3029
                'breezy.tests.test_selftest',
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3030
                ]
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
3031
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
3032
        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.
3033
            calls.append("modules_to_doctest")
5131.2.6 by Martin
Fix more tests which were failing under -OO that had been missed earlier
3034
            if __doc__ is None:
3035
                return []
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3036
            return ['breezy.timestamp']
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
3037
        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.
3038
        expected_test_list = [
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3039
            # testmod_names
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3040
            'breezy.tests.blackbox.test_branch.TestBranch.test_branch',
3041
            ('breezy.tests.per_transport.TransportTests'
4725.1.1 by Vincent Ladeuil
Mention transport class name in test id.
3042
             '.test_abspath(LocalTransport,LocalURLServer)'),
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3043
            'breezy.tests.test_selftest.TestTestSuite.test_test_suite',
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3044
            # plugins can't be tested that way since selftest may be run with
3045
            # --no-plugins
3046
            ]
5131.2.6 by Martin
Fix more tests which were failing under -OO that had been missed earlier
3047
        if __doc__ is not None:
3048
            expected_test_list.extend([
3049
                # modules_to_doctest
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3050
                'breezy.timestamp.format_highres_date',
5131.2.6 by Martin
Fix more tests which were failing under -OO that had been missed earlier
3051
                ])
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3052
        suite = tests.test_suite()
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
3053
        self.assertEqual({"testmod_names", "modules_to_doctest"},
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3054
            set(calls))
3055
        self.assertSubset(expected_test_list, _test_ids(suite))
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3056
3057
    def test_test_suite_list_and_start(self):
4636.2.5 by Robert Collins
Minor tweaks to clarity in slower selftest tests.
3058
        # 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.
3059
        # to know that starting_with == None works. So a second load is
3060
        # incurred - note that the starting_with parameter causes a partial load
3061
        # rather than a full load so this test should be pretty quick.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3062
        test_list = ['breezy.tests.test_selftest.TestTestSuite.test_test_suite']
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3063
        suite = tests.test_suite(test_list,
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3064
                                 ['breezy.tests.test_selftest.TestTestSuite'])
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3065
        # test_test_suite_list_and_start is not included 
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3066
        self.assertEqual(test_list, _test_ids(suite))
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
3067
3068
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
3069
class TestLoadTestIdList(tests.TestCaseInTempDir):
3070
3071
    def _create_test_list_file(self, file_name, content):
3072
        fl = open(file_name, 'wt')
3073
        fl.write(content)
3074
        fl.close()
3075
3076
    def test_load_unknown(self):
3077
        self.assertRaises(errors.NoSuchFile,
3078
                          tests.load_test_id_list, 'i_do_not_exist')
3079
3080
    def test_load_test_list(self):
3081
        test_list_fname = 'test.list'
3082
        self._create_test_list_file(test_list_fname,
3083
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
3084
        tlist = tests.load_test_id_list(test_list_fname)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3085
        self.assertEqual(2, len(tlist))
3086
        self.assertEqual('mod1.cl1.meth1', tlist[0])
3087
        self.assertEqual('mod2.cl2.meth2', tlist[1])
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
3088
3089
    def test_load_dirty_file(self):
3090
        test_list_fname = 'test.list'
3091
        self._create_test_list_file(test_list_fname,
3092
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
3093
                                    'bar baz\n')
3094
        tlist = tests.load_test_id_list(test_list_fname)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3095
        self.assertEqual(4, len(tlist))
3096
        self.assertEqual('mod1.cl1.meth1', tlist[0])
3097
        self.assertEqual('', tlist[1])
3098
        self.assertEqual('mod2.cl2.meth2', tlist[2])
3099
        self.assertEqual('bar baz', tlist[3])
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
3100
3101
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
3102
class TestFilteredByModuleTestLoader(tests.TestCase):
3103
3104
    def _create_loader(self, test_list):
3105
        id_filter = tests.TestIdList(test_list)
3302.8.4 by Vincent Ladeuil
Cosmetic changes.
3106
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
3107
        return loader
3108
3109
    def test_load_tests(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3110
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
3111
        loader = self._create_loader(test_list)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3112
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3113
        self.assertEqual(test_list, _test_ids(suite))
3302.8.2 by Vincent Ladeuil
New test loader reducing modules imports and tests loaded.
3114
3115
    def test_exclude_tests(self):
3116
        test_list = ['bogus']
3117
        loader = self._create_loader(test_list)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3118
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3119
        self.assertEqual([], _test_ids(suite))
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3120
3121
3122
class TestFilteredByNameStartTestLoader(tests.TestCase):
3123
3124
    def _create_loader(self, name_start):
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
3125
        def needs_module(name):
3126
            return name.startswith(name_start) or name_start.startswith(name)
3127
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3128
        return loader
3129
3130
    def test_load_tests(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3131
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
3132
        loader = self._create_loader('breezy.tests.test_samp')
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
3133
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3134
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3135
        self.assertEqual(test_list, _test_ids(suite))
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
3136
3137
    def test_load_tests_inside_module(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3138
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
3139
        loader = self._create_loader('breezy.tests.test_sampler.Demo')
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3140
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3141
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3142
        self.assertEqual(test_list, _test_ids(suite))
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3143
3144
    def test_exclude_tests(self):
3145
        test_list = ['bogus']
3146
        loader = self._create_loader('bogus')
3147
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3148
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3149
        self.assertEqual([], _test_ids(suite))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3150
3151
3152
class TestTestPrefixRegistry(tests.TestCase):
3153
3154
    def _get_registry(self):
3155
        tp_registry = tests.TestPrefixAliasRegistry()
3156
        return tp_registry
3157
3158
    def test_register_new_prefix(self):
3159
        tpr = self._get_registry()
3160
        tpr.register('foo', 'fff.ooo.ooo')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3161
        self.assertEqual('fff.ooo.ooo', tpr.get('foo'))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3162
3163
    def test_register_existing_prefix(self):
3164
        tpr = self._get_registry()
3165
        tpr.register('bar', 'bbb.aaa.rrr')
3166
        tpr.register('bar', 'bBB.aAA.rRR')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3167
        self.assertEqual('bbb.aaa.rrr', tpr.get('bar'))
4794.1.15 by Robert Collins
Review feedback.
3168
        self.assertThat(self.get_log(),
5574.7.7 by Vincent Ladeuil
Fix test.
3169
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
3170
                           doctest.ELLIPSIS))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3171
3172
    def test_get_unknown_prefix(self):
3173
        tpr = self._get_registry()
3174
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
3175
3176
    def test_resolve_prefix(self):
3177
        tpr = self._get_registry()
3178
        tpr.register('bar', 'bb.aa.rr')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3179
        self.assertEqual('bb.aa.rr', tpr.resolve_alias('bar'))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3180
3181
    def test_resolve_unknown_alias(self):
3182
        tpr = self._get_registry()
3183
        self.assertRaises(errors.BzrCommandError,
3184
                          tpr.resolve_alias, 'I am not a prefix')
3185
3186
    def test_predefined_prefixes(self):
3187
        tpr = tests.test_prefix_alias_registry
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3188
        self.assertEqual('breezy', tpr.resolve_alias('breezy'))
3189
        self.assertEqual('breezy.doc', tpr.resolve_alias('bd'))
3190
        self.assertEqual('breezy.utils', tpr.resolve_alias('bu'))
3191
        self.assertEqual('breezy.tests', tpr.resolve_alias('bt'))
3192
        self.assertEqual('breezy.tests.blackbox', tpr.resolve_alias('bb'))
3193
        self.assertEqual('breezy.plugins', tpr.resolve_alias('bp'))
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3194
3195
5412.1.3 by Martin
Add tests for test case thread leak detection
3196
class TestThreadLeakDetection(tests.TestCase):
3197
    """Ensure when tests leak threads we detect and report it"""
3198
3199
    class LeakRecordingResult(tests.ExtendedTestResult):
3200
        def __init__(self):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3201
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
5412.1.3 by Martin
Add tests for test case thread leak detection
3202
            self.leaks = []
3203
        def _report_thread_leak(self, test, leaks, alive):
3204
            self.leaks.append((test, leaks))
3205
3206
    def test_testcase_without_addCleanups(self):
5412.1.6 by Martin
Document the less obvious code and note future reporting plans, as requested in review by vila
3207
        """Check old TestCase instances don't break with leak detection"""
5412.1.3 by Martin
Add tests for test case thread leak detection
3208
        class Test(unittest.TestCase):
3209
            def runTest(self):
3210
                pass
3211
        result = self.LeakRecordingResult()
3212
        test = Test()
3213
        result.startTestRun()
3214
        test.run(result)
3215
        result.stopTestRun()
3216
        self.assertEqual(result._tests_leaking_threads_count, 0)
3217
        self.assertEqual(result.leaks, [])
3218
        
3219
    def test_thread_leak(self):
5412.1.6 by Martin
Document the less obvious code and note future reporting plans, as requested in review by vila
3220
        """Ensure a thread that outlives the running of a test is reported
3221
3222
        Uses a thread that blocks on an event, and is started by the inner
3223
        test case. As the thread outlives the inner case's run, it should be
3224
        detected as a leak, but the event is then set so that the thread can
3225
        be safely joined in cleanup so it's not leaked for real.
3226
        """
5412.1.3 by Martin
Add tests for test case thread leak detection
3227
        event = threading.Event()
3228
        thread = threading.Thread(name="Leaker", target=event.wait)
3229
        class Test(tests.TestCase):
3230
            def test_leak(self):
3231
                thread.start()
3232
        result = self.LeakRecordingResult()
3233
        test = Test("test_leak")
3234
        self.addCleanup(thread.join)
3235
        self.addCleanup(event.set)
3236
        result.startTestRun()
3237
        test.run(result)
3238
        result.stopTestRun()
3239
        self.assertEqual(result._tests_leaking_threads_count, 1)
3240
        self.assertEqual(result._first_thread_leaker_id, test.id())
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
3241
        self.assertEqual(result.leaks, [(test, {thread})])
5412.1.3 by Martin
Add tests for test case thread leak detection
3242
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3243
3244
    def test_multiple_leaks(self):
5412.1.6 by Martin
Document the less obvious code and note future reporting plans, as requested in review by vila
3245
        """Check multiple leaks are blamed on the test cases at fault
3246
3247
        Same concept as the previous test, but has one inner test method that
3248
        leaks two threads, and one that doesn't leak at all.
3249
        """
5412.1.3 by Martin
Add tests for test case thread leak detection
3250
        event = threading.Event()
3251
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
3252
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
3253
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
3254
        class Test(tests.TestCase):
3255
            def test_first_leak(self):
3256
                thread_b.start()
3257
            def test_second_no_leak(self):
3258
                pass
3259
            def test_third_leak(self):
3260
                thread_c.start()
3261
                thread_a.start()
3262
        result = self.LeakRecordingResult()
3263
        first_test = Test("test_first_leak")
3264
        third_test = Test("test_third_leak")
3265
        self.addCleanup(thread_a.join)
3266
        self.addCleanup(thread_b.join)
3267
        self.addCleanup(thread_c.join)
3268
        self.addCleanup(event.set)
3269
        result.startTestRun()
3270
        unittest.TestSuite(
3271
            [first_test, Test("test_second_no_leak"), third_test]
3272
            ).run(result)
3273
        result.stopTestRun()
3274
        self.assertEqual(result._tests_leaking_threads_count, 2)
3275
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
3276
        self.assertEqual(result.leaks, [
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
3277
            (first_test, {thread_b}),
3278
            (third_test, {thread_a, thread_c})])
5412.1.3 by Martin
Add tests for test case thread leak detection
3279
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
3280
3281
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3282
class TestPostMortemDebugging(tests.TestCase):
3283
    """Check post mortem debugging works when tests fail or error"""
3284
3285
    class TracebackRecordingResult(tests.ExtendedTestResult):
3286
        def __init__(self):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3287
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3288
            self.postcode = None
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
3289
        def _post_mortem(self, tb=None):
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3290
            """Record the code object at the end of the current traceback"""
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
3291
            tb = tb or sys.exc_info()[2]
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3292
            if tb is not None:
3293
                next = tb.tb_next
3294
                while next is not None:
3295
                    tb = next
3296
                    next = next.tb_next
3297
                self.postcode = tb.tb_frame.f_code
3298
        def report_error(self, test, err):
3299
            pass
3300
        def report_failure(self, test, err):
3301
            pass
3302
3303
    def test_location_unittest_error(self):
3304
        """Needs right post mortem traceback with erroring unittest case"""
3305
        class Test(unittest.TestCase):
3306
            def runTest(self):
3307
                raise RuntimeError
3308
        result = self.TracebackRecordingResult()
3309
        Test().run(result)
6619.3.16 by Jelmer Vernooij
Run 2to3 funcattrs fixer.
3310
        self.assertEqual(result.postcode, Test.runTest.__code__)
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3311
3312
    def test_location_unittest_failure(self):
3313
        """Needs right post mortem traceback with failing unittest case"""
3314
        class Test(unittest.TestCase):
3315
            def runTest(self):
3316
                raise self.failureException
3317
        result = self.TracebackRecordingResult()
3318
        Test().run(result)
6619.3.16 by Jelmer Vernooij
Run 2to3 funcattrs fixer.
3319
        self.assertEqual(result.postcode, Test.runTest.__code__)
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3320
3321
    def test_location_bt_error(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3322
        """Needs right post mortem traceback with erroring breezy.tests case"""
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3323
        class Test(tests.TestCase):
3324
            def test_error(self):
3325
                raise RuntimeError
3326
        result = self.TracebackRecordingResult()
3327
        Test("test_error").run(result)
6619.3.16 by Jelmer Vernooij
Run 2to3 funcattrs fixer.
3328
        self.assertEqual(result.postcode, Test.test_error.__code__)
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3329
3330
    def test_location_bt_failure(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3331
        """Needs right post mortem traceback with failing breezy.tests case"""
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3332
        class Test(tests.TestCase):
3333
            def test_failure(self):
3334
                raise self.failureException
3335
        result = self.TracebackRecordingResult()
3336
        Test("test_failure").run(result)
6619.3.16 by Jelmer Vernooij
Run 2to3 funcattrs fixer.
3337
        self.assertEqual(result.postcode, Test.test_failure.__code__)
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3338
5459.5.3 by Martin
Add test for triggering of pdb.post_mortem with BZR_TEST_PDB
3339
    def test_env_var_triggers_post_mortem(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3340
        """Check pdb.post_mortem is called iff BRZ_TEST_PDB is set"""
5459.5.3 by Martin
Add test for triggering of pdb.post_mortem with BZR_TEST_PDB
3341
        import pdb
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3342
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
5459.5.3 by Martin
Add test for triggering of pdb.post_mortem with BZR_TEST_PDB
3343
        post_mortem_calls = []
3344
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3345
        self.overrideEnv('BRZ_TEST_PDB', None)
5459.5.3 by Martin
Add test for triggering of pdb.post_mortem with BZR_TEST_PDB
3346
        result._post_mortem(1)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3347
        self.overrideEnv('BRZ_TEST_PDB', 'on')
5459.5.3 by Martin
Add test for triggering of pdb.post_mortem with BZR_TEST_PDB
3348
        result._post_mortem(2)
3349
        self.assertEqual([2], post_mortem_calls)
3350
5459.5.1 by Martin
Add tests for location of stack when ExtendedTestResult.post_mortem is run
3351
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3352
class TestRunSuite(tests.TestCase):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3353
3354
    def test_runner_class(self):
3355
        """run_suite accepts and uses a runner_class keyword argument."""
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3356
        class Stub(tests.TestCase):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3357
            def test_foo(self):
3358
                pass
3359
        suite = Stub("test_foo")
3360
        calls = []
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3361
        class MyRunner(tests.TextTestRunner):
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3362
            def run(self, test):
3363
                calls.append(test)
4498.1.1 by Vincent Ladeuil
Fix test_selftest.py imports.
3364
                return tests.ExtendedTestResult(self.stream, self.descriptions,
3365
                                                self.verbosity)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3366
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
4573.2.2 by Robert Collins
Fix selftest for TestResult progress changes.
3367
        self.assertLength(1, calls)
5340.12.1 by Martin
Ensure that testcase attributes are deallocated after run
3368
5340.12.13 by Martin
Gut TestDecorator classes, removing iter and instead doing all work on init, also test that decorators don't interfere with collection
3369
6221.1.2 by Martin Packman
Extract parts of uncollected warnings tests for running selftest into seperate objects
3370
class _Selftest(object):
3371
    """Mixin for tests needing full selftest output"""
3372
3373
    def _inject_stream_into_subunit(self, stream):
3374
        """To be overridden by subclasses that run tests out of process"""
3375
3376
    def _run_selftest(self, **kwargs):
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3377
        sio = StringIO()
6221.1.2 by Martin Packman
Extract parts of uncollected warnings tests for running selftest into seperate objects
3378
        self._inject_stream_into_subunit(sio)
3379
        tests.selftest(stream=sio, stop_on_failure=False, **kwargs)
3380
        return sio.getvalue()
3381
3382
3383
class _ForkedSelftest(_Selftest):
3384
    """Mixin for tests needing full selftest output with forked children"""
3385
3386
    _test_needs_features = [features.subunit]
3387
3388
    def _inject_stream_into_subunit(self, stream):
3389
        """Monkey-patch subunit so the extra output goes to stream not stdout
3390
3391
        Some APIs need rewriting so this kind of bogus hackery can be replaced
3392
        by passing the stream param from run_tests down into ProtocolTestCase.
3393
        """
3394
        from subunit import ProtocolTestCase
3395
        _original_init = ProtocolTestCase.__init__
3396
        def _init_with_passthrough(self, *args, **kwargs):
3397
            _original_init(self, *args, **kwargs)
3398
            self._passthrough = stream
3399
        self.overrideAttr(ProtocolTestCase, "__init__", _init_with_passthrough)
3400
3401
    def _run_selftest(self, **kwargs):
3402
        # GZ 2011-05-26: Add a PosixSystem feature so this check can go away
3403
        if getattr(os, "fork", None) is None:
3404
            raise tests.TestNotApplicable("Platform doesn't support forking")
3405
        # Make sure the fork code is actually invoked by claiming two cores
3406
        self.overrideAttr(osutils, "local_concurrency", lambda: 2)
3407
        kwargs.setdefault("suite_decorators", []).append(tests.fork_decorator)
3408
        return super(_ForkedSelftest, self)._run_selftest(**kwargs)
3409
3410
6221.1.3 by Martin Packman
Add failing test for error output from problems during forking children
3411
class TestParallelFork(_ForkedSelftest, tests.TestCase):
3412
    """Check operation of --parallel=fork selftest option"""
3413
3414
    def test_error_in_child_during_fork(self):
3415
        """Error in a forked child during test setup should get reported"""
3416
        class Test(tests.TestCase):
3417
            def testMethod(self):
3418
                pass
3419
        # We don't care what, just break something that a child will run
3420
        self.overrideAttr(tests, "workaround_zealous_crypto_random", None)
3421
        out = self._run_selftest(test_suite_factory=Test)
6245.1.1 by Martin Packman
Weaken test_error_in_child_during_fork to pass with intermingled tracebacks
3422
        # Lines from the tracebacks of the two child processes may be mixed
3423
        # together due to the way subunit parses and forwards the streams,
3424
        # so permit extra lines between each part of the error output.
6221.1.3 by Martin Packman
Add failing test for error output from problems during forking children
3425
        self.assertContainsRe(out,
3426
            "Traceback.*:\n"
6245.1.2 by Martin Packman
Allow any number of intermingled lines rather than just zero or one
3427
            "(?:.*\n)*"
6221.1.3 by Martin Packman
Add failing test for error output from problems during forking children
3428
            ".+ in fork_for_tests\n"
6245.1.2 by Martin Packman
Allow any number of intermingled lines rather than just zero or one
3429
            "(?:.*\n)*"
6798.1.1 by Jelmer Vernooij
Properly escape backslashes.
3430
            "\\s*workaround_zealous_crypto_random\\(\\)\n"
6245.1.2 by Martin Packman
Allow any number of intermingled lines rather than just zero or one
3431
            "(?:.*\n)*"
6221.1.3 by Martin Packman
Add failing test for error output from problems during forking children
3432
            "TypeError:")
3433
3434
6221.1.2 by Martin Packman
Extract parts of uncollected warnings tests for running selftest into seperate objects
3435
class TestUncollectedWarnings(_Selftest, tests.TestCase):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3436
    """Check a test case still alive after being run emits a warning"""
3437
3438
    class Test(tests.TestCase):
3439
        def test_pass(self):
3440
            pass
3441
        def test_self_ref(self):
3442
            self.also_self = self.test_self_ref
3443
        def test_skip(self):
6622.4.1 by Martin
Use skipTest rather than deprecated skip method
3444
            self.skipTest("Don't need")
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3445
3446
    def _get_suite(self):
3447
        return TestUtil.TestSuite([
3448
            self.Test("test_pass"),
3449
            self.Test("test_self_ref"),
3450
            self.Test("test_skip"),
3451
            ])
3452
3453
    def _run_selftest_with_suite(self, **kwargs):
5340.16.4 by Martin
Fix tests to work regardless of flag state
3454
        old_flags = tests.selftest_debug_flags
3455
        tests.selftest_debug_flags = old_flags.union(["uncollected_cases"])
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3456
        gc_on = gc.isenabled()
3457
        if gc_on:
3458
            gc.disable()
3459
        try:
6221.1.2 by Martin Packman
Extract parts of uncollected warnings tests for running selftest into seperate objects
3460
            output = self._run_selftest(test_suite_factory=self._get_suite,
3461
                **kwargs)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3462
        finally:
3463
            if gc_on:
3464
                gc.enable()
5340.16.4 by Martin
Fix tests to work regardless of flag state
3465
            tests.selftest_debug_flags = old_flags
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3466
        self.assertNotContainsRe(output, "Uncollected test case.*test_pass")
3467
        self.assertContainsRe(output, "Uncollected test case.*test_self_ref")
3468
        return output
3469
3470
    def test_testsuite(self):
3471
        self._run_selftest_with_suite()
3472
3473
    def test_pattern(self):
3474
        out = self._run_selftest_with_suite(pattern="test_(?:pass|self_ref)$")
3475
        self.assertNotContainsRe(out, "test_skip")
3476
3477
    def test_exclude_pattern(self):
3478
        out = self._run_selftest_with_suite(exclude_pattern="test_skip$")
3479
        self.assertNotContainsRe(out, "test_skip")
3480
3481
    def test_random_seed(self):
5340.16.20 by Martin Packman
Revert checking of test count in TestUncollectedCases.test_random_seed
3482
        self._run_selftest_with_suite(random_seed="now")
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3483
3484
    def test_matching_tests_first(self):
3485
        self._run_selftest_with_suite(matching_tests_first=True,
3486
            pattern="test_self_ref$")
3487
3488
    def test_starting_with_and_exclude(self):
3489
        out = self._run_selftest_with_suite(starting_with=["bt."],
3490
            exclude_pattern="test_skip$")
3491
        self.assertNotContainsRe(out, "test_skip")
3492
3493
    def test_additonal_decorator(self):
3494
        out = self._run_selftest_with_suite(
3495
            suite_decorators=[tests.TestDecorator])
3496
3497
3498
class TestUncollectedWarningsSubunit(TestUncollectedWarnings):
3499
    """Check warnings from tests staying alive are emitted with subunit"""
3500
3501
    _test_needs_features = [features.subunit]
3502
3503
    def _run_selftest_with_suite(self, **kwargs):
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
3504
        return TestUncollectedWarnings._run_selftest_with_suite(
3505
            self, runner_class=tests.SubUnitBzrRunnerv1, **kwargs)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3506
3507
6221.1.2 by Martin Packman
Extract parts of uncollected warnings tests for running selftest into seperate objects
3508
class TestUncollectedWarningsForked(_ForkedSelftest, TestUncollectedWarnings):
5340.16.5 by Martin
Add test subclass for collection of cases under --parallel=fork
3509
    """Check warnings from tests staying alive are emitted when forking"""
3510
3511
5570.3.1 by Vincent Ladeuil
Demonstrate that test._captureVar() is dangerous.
3512
class TestEnvironHandling(tests.TestCase):
3513
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
3514
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
3515
        self.assertFalse('MYVAR' in os.environ)
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
3516
        self.overrideEnv('MYVAR', '42')
3517
        # We use an embedded test to make sure we fix the _captureVar bug
3518
        class Test(tests.TestCase):
3519
            def test_me(self):
3520
                # The first call save the 42 value
3521
                self.overrideEnv('MYVAR', None)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3522
                self.assertEqual(None, os.environ.get('MYVAR'))
5570.3.4 by Vincent Ladeuil
Simplify overrideEnv, fix the related tests, make them more dev-friendly too.
3523
                # Make sure we can call it twice
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
3524
                self.overrideEnv('MYVAR', None)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3525
                self.assertEqual(None, os.environ.get('MYVAR'))
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3526
        output = StringIO()
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
3527
        result = tests.TextTestResult(output, 0, 1)
3528
        Test('test_me').run(result)
5570.3.4 by Vincent Ladeuil
Simplify overrideEnv, fix the related tests, make them more dev-friendly too.
3529
        if not result.wasStrictlySuccessful():
3530
            self.fail(output.getvalue())
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
3531
        # We get our value back
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3532
        self.assertEqual('42', os.environ.get('MYVAR'))
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3533
3534
3535
class TestIsolatedEnv(tests.TestCase):
3536
    """Test isolating tests from os.environ.
3537
5574.6.8 by Vincent Ladeuil
Fix typo, rename BzrDocTestSuite to IsolatedDocTestSuite to dodge the name space controversy and make the intent clearer, add an indirection for setUp/tearDown to prepare more isolation for doctests.
3538
    Since we use tests that are already isolated from os.environ a bit of care
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3539
    should be taken when designing the tests to avoid bootstrap side-effects.
3540
    The tests start an already clean os.environ which allow doing valid
3541
    assertions about which variables are present or not and design tests around
3542
    these assertions.
3543
    """
3544
3545
    class ScratchMonkey(tests.TestCase):
3546
3547
        def test_me(self):
3548
            pass
3549
3550
    def test_basics(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3551
        # Make sure we know the definition of BRZ_HOME: not part of os.environ
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3552
        # for tests.TestCase.
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3553
        self.assertTrue('BRZ_HOME' in tests.isolated_environ)
3554
        self.assertEqual(None, tests.isolated_environ['BRZ_HOME'])
3555
        # Being part of isolated_environ, BRZ_HOME should not appear here
3556
        self.assertFalse('BRZ_HOME' in os.environ)
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3557
        # Make sure we know the definition of LINES: part of os.environ for
3558
        # tests.TestCase
3559
        self.assertTrue('LINES' in tests.isolated_environ)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3560
        self.assertEqual('25', tests.isolated_environ['LINES'])
3561
        self.assertEqual('25', os.environ['LINES'])
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3562
3563
    def test_injecting_unknown_variable(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3564
        # BRZ_HOME is known to be absent from os.environ
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3565
        test = self.ScratchMonkey('test_me')
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3566
        tests.override_os_environ(test, {'BRZ_HOME': 'foo'})
3567
        self.assertEqual('foo', os.environ['BRZ_HOME'])
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3568
        tests.restore_os_environ(test)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
3569
        self.assertFalse('BRZ_HOME' in os.environ)
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3570
3571
    def test_injecting_known_variable(self):
3572
        test = self.ScratchMonkey('test_me')
3573
        # LINES is known to be present in os.environ
3574
        tests.override_os_environ(test, {'LINES': '42'})
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3575
        self.assertEqual('42', os.environ['LINES'])
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3576
        tests.restore_os_environ(test)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3577
        self.assertEqual('25', os.environ['LINES'])
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
3578
3579
    def test_deleting_variable(self):
3580
        test = self.ScratchMonkey('test_me')
3581
        # LINES is known to be present in os.environ
3582
        tests.override_os_environ(test, {'LINES': None})
3583
        self.assertTrue('LINES' not in os.environ)
3584
        tests.restore_os_environ(test)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3585
        self.assertEqual('25', os.environ['LINES'])
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3586
3587
3588
class TestDocTestSuiteIsolation(tests.TestCase):
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3589
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
3590
3591
    Since tests.TestCase alreay provides an isolation from os.environ, we use
3592
    the clean environment as a base for testing. To precisely capture the
3593
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
3594
    compare against.
3595
3596
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
3597
    not `os.environ` so each test overrides it to suit its needs.
3598
3599
    """
3600
3601
    def get_doctest_suite_for_string(self, klass, string):
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3602
        class Finder(doctest.DocTestFinder):
3603
3604
            def find(*args, **kwargs):
3605
                test = doctest.DocTestParser().get_doctest(
3606
                    string, {}, 'foo', 'foo.py', 0)
3607
                return [test]
3608
3609
        suite = klass(test_finder=Finder())
3610
        return suite
3611
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3612
    def run_doctest_suite_for_string(self, klass, string):
3613
        suite = self.get_doctest_suite_for_string(klass, string)
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
3614
        output = StringIO()
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3615
        result = tests.TextTestResult(output, 0, 1)
3616
        suite.run(result)
3617
        return result, output
3618
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3619
    def assertDocTestStringSucceds(self, klass, string):
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3620
        result, output = self.run_doctest_suite_for_string(klass, string)
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3621
        if not result.wasStrictlySuccessful():
3622
            self.fail(output.getvalue())
3623
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3624
    def assertDocTestStringFails(self, klass, string):
3625
        result, output = self.run_doctest_suite_for_string(klass, string)
3626
        if result.wasStrictlySuccessful():
3627
            self.fail(output.getvalue())
3628
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3629
    def test_injected_variable(self):
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3630
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
3631
        test = """
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3632
            >>> import os
3633
            >>> os.environ['LINES']
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3634
            '42'
3635
            """
3636
        # doctest.DocTestSuite fails as it sees '25'
3637
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3638
        # tests.DocTestSuite sees '42'
5574.6.8 by Vincent Ladeuil
Fix typo, rename BzrDocTestSuite to IsolatedDocTestSuite to dodge the name space controversy and make the intent clearer, add an indirection for setUp/tearDown to prepare more isolation for doctests.
3639
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3640
3641
    def test_deleted_variable(self):
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3642
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
3643
        test = """
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
3644
            >>> import os
5574.7.4 by Vincent Ladeuil
Test tests.DocTestSuite, using doctest.DocTestSuite as a reference point.
3645
            >>> os.environ.get('LINES')
3646
            """
3647
        # doctest.DocTestSuite fails as it sees '25'
3648
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
3649
        # tests.DocTestSuite sees None
5574.6.8 by Vincent Ladeuil
Fix typo, rename BzrDocTestSuite to IsolatedDocTestSuite to dodge the name space controversy and make the intent clearer, add an indirection for setUp/tearDown to prepare more isolation for doctests.
3650
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
5924.1.1 by Vincent Ladeuil
Add a failing test.
3651
3652
3653
class TestSelftestExcludePatterns(tests.TestCase):
3654
3655
    def setUp(self):
3656
        super(TestSelftestExcludePatterns, self).setUp()
3657
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
3658
3659
    def suite_factory(self, keep_only=None, starting_with=None):
3660
        """A test suite factory with only a few tests."""
3661
        class Test(tests.TestCase):
3662
            def id(self):
3663
                # We don't need the full class path
3664
                return self._testMethodName
3665
            def a(self):
3666
                pass
3667
            def b(self):
3668
                pass
3669
            def c(self):
3670
                pass
3671
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
3672
3673
    def assertTestList(self, expected, *selftest_args):
3674
        # We rely on setUp installing the right test suite factory so we can
3675
        # test at the command level without loading the whole test suite
3676
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3677
        actual = out.splitlines()
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3678
        self.assertEqual(expected, actual)
5924.1.1 by Vincent Ladeuil
Add a failing test.
3679
3680
    def test_full_list(self):
3681
        self.assertTestList(['a', 'b', 'c'])
3682
3683
    def test_single_exclude(self):
3684
        self.assertTestList(['b', 'c'], '-x', 'a')
3685
3686
    def test_mutiple_excludes(self):
3687
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
3688
3689
3690
class TestCounterHooks(tests.TestCase, SelfTestHelper):
3691
3692
    _test_needs_features = [features.subunit]
3693
3694
    def setUp(self):
3695
        super(TestCounterHooks, self).setUp()
3696
        class Test(tests.TestCase):
3697
3698
            def setUp(self):
3699
                super(Test, self).setUp()
3700
                self.hooks = hooks.Hooks()
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
3701
                self.hooks.add_hook('myhook', 'Foo bar blah', (2, 4))
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
3702
                self.install_counter_hook(self.hooks, 'myhook')
3703
3704
            def no_hook(self):
3705
                pass
3706
3707
            def run_hook_once(self):
3708
                for hook in self.hooks['myhook']:
3709
                    hook(self)
5743.14.16 by Vincent Ladeuil
Missing blank line.
3710
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
3711
        self.test_class = Test
3712
3713
    def assertHookCalls(self, expected_calls, test_name):
3714
        test = self.test_class(test_name)
3715
        result = unittest.TestResult()
3716
        test.run(result)
3717
        self.assertTrue(hasattr(test, '_counters'))
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
3718
        self.assertTrue('myhook' in test._counters)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
3719
        self.assertEqual(expected_calls, test._counters['myhook'])
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
3720
3721
    def test_no_hook(self):
3722
        self.assertHookCalls(0, 'no_hook')
3723
3724
    def test_run_hook_once(self):
5743.14.17 by Vincent Ladeuil
Fix pqm failure by requiring the right version of testtools :-/
3725
        tt = features.testtools
3726
        if tt.module.__version__ < (0, 9, 8):
3727
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
3728
        self.assertHookCalls(1, 'run_hook_once')