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