/brz/remove-bazaar

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