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