/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, 2015, 2016 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
608 by Martin Pool
- Split selftests out into a new module and start changing them
3
# This program is free software; you can redistribute it and/or modify
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
608 by Martin Pool
- Split selftests out into a new module and start changing them
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
608 by Martin Pool
- Split selftests out into a new module and start changing them
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
608 by Martin Pool
- Split selftests out into a new module and start changing them
16
5131.2.5 by Martin
Add module docstring to bzrlib.tests
17
"""Testing framework extensions"""
609 by Martin Pool
- cleanup test code
18
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
19
from __future__ import absolute_import
20
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
21
# NOTE: Some classes in here use camelCaseNaming() rather than
22
# underscore_naming().  That's for consistency with unittest; it's not the
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
23
# general style of breezy.  Please continue that consistency when adding e.g.
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
24
# new assertFoo() methods.
25
2485.6.6 by Martin Pool
Put test root directory (containing per-test directories) in TMPDIR
26
import atexit
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
27
import codecs
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
28
import copy
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
29
import difflib
1740.6.1 by Martin Pool
Remove Scratch objects used by doctests
30
import doctest
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
31
import errno
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
32
import functools
5365.3.1 by Andrew Bennetts
Better (and simpler) algorithm for partition_tests.
33
import itertools
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
34
import logging
6606.1.1 by Jelmer Vernooij
Add local copy of _delta_to_float from testtools, rather than
35
import math
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
36
import os
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
37
import platform
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
38
import pprint
2394.2.2 by Ian Clatworthy
Add --randomize and update help
39
import random
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
40
import re
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
41
import shlex
6331.4.1 by Martin Packman
Set before starting a test subprocess to compute the same sys.path
42
import site
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
43
import stat
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
44
import subprocess
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
45
import sys
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
46
import tempfile
3406.1.2 by Vincent Ladeuil
Fix as per Robert's review.
47
import threading
3084.1.1 by Andrew Bennetts
Add a --coverage option to selftest.
48
import time
4794.1.8 by Robert Collins
Move the passing of test logs to the result to be via the getDetails API and remove all public use of TestCase._get_log.
49
import traceback
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
50
import unittest
2485.6.5 by Martin Pool
Remove keep_output option
51
import warnings
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
52
4794.1.1 by Robert Collins
Derive bzr's TestCase from testtools.testcase.TestCase.
53
import testtools
4922.1.2 by Martin Pool
Better guards on checks of testtools versions
54
# nb: check this before importing anything else from within it
55
_testtools_version = getattr(testtools, '__version__', ())
5418.5.1 by Martin
Change the minimum version of testtools required for selftest to 0.9.5
56
if _testtools_version < (0, 9, 5):
57
    raise ImportError("need at least testtools 0.9.5: %s is %r"
4922.1.2 by Martin Pool
Better guards on checks of testtools versions
58
        % (testtools.__file__, _testtools_version))
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]).
59
from testtools import content
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
60
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
61
import breezy
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
62
from .. import (
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
63
    branchbuilder,
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
64
    controldir,
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
65
    commands as _mod_commands,
4695.3.2 by Vincent Ladeuil
Simplified and claried as per Robert's review.
66
    config,
6131.1.1 by Jonathan Riddell
do not use i18n in tests
67
    i18n,
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
68
    debug,
69
    errors,
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
70
    hooks,
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
71
    lock as _mod_lock,
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
72
    lockdir,
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
73
    memorytree,
74
    osutils,
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
75
    plugin as _mod_plugin,
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
76
    pyutils,
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
77
    ui,
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
78
    urlutils,
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
79
    registry,
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
80
    symbol_versioning,
81
    trace,
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
82
    transport as _mod_transport,
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
83
    workingtree,
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
84
    )
6670.4.1 by Jelmer Vernooij
Update imports.
85
from breezy.bzr import (
86
    chk_map,
87
    )
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
88
try:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
89
    import breezy.lsprof
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
90
except ImportError:
91
    # lsprof not available
92
    pass
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
93
from ..sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
94
    BytesIO,
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
95
    PY3,
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
96
    string_types,
97
    text_type,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
98
    )
6670.4.16 by Jelmer Vernooij
Move smart to breezy.bzr.
99
from ..bzr.smart import client, request
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
100
from ..transport import (
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
101
    memory,
102
    pathfilter,
103
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
104
from ..tests import (
6319.1.1 by Martin Pool
Add selftest.timeout option, defaulting to 600
105
    fixtures,
5017.3.6 by Vincent Ladeuil
Fix some fallouts of moving test servers around.
106
    test_server,
107
    TestUtil,
5200.2.3 by Robert Collins
Make 'pydoc bzrlib.tests.build_tree_shape' useful.
108
    treeshape,
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
109
    ui_testing,
5017.3.6 by Vincent Ladeuil
Fix some fallouts of moving test servers around.
110
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
111
from ..tests.features import _CompatabilityThunkFeature
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
112
2387.2.1 by Robert Collins
Mark bzrlib.tests as providing assertFOO helper functions by adding a __unittest global attribute. (Robert Collins, Andrew Bennetts, Martin Pool, Jonathan Lange)
113
# Mark this python module as being part of the implementation
114
# of unittest: this gives us better tracebacks where the last
115
# shown frame is the test code, not our assertXYZ.
6677.1.3 by Martin
Small corrections on top of the mass changes
116
__unittest = 1
2387.2.1 by Robert Collins
Mark bzrlib.tests as providing assertFOO helper functions by adding a __unittest global attribute. (Robert Collins, Andrew Bennetts, Martin Pool, Jonathan Lange)
117
5017.3.6 by Vincent Ladeuil
Fix some fallouts of moving test servers around.
118
default_transport = test_server.LocalURLServer
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
119
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
120
121
_unitialized_attr = object()
122
"""A sentinel needed to act as a default value in a method signature."""
123
124
4573.2.3 by Robert Collins
Support python 2.4.
125
# Subunit result codes, defined here to prevent a hard dependency on subunit.
126
SUBUNIT_SEEK_SET = 0
127
SUBUNIT_SEEK_CUR = 1
128
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
129
# These are intentionally brought into this namespace. That way plugins, etc
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
130
# can just "from breezy.tests import TestCase, TestLoader, etc"
5404.2.1 by John Arbash Meinel
Fix bug #627438 by restoring TestSuite and TestLoader.
131
TestSuite = TestUtil.TestSuite
132
TestLoader = TestUtil.TestLoader
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
133
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
134
# Tests should run in a clean and clearly defined environment. The goal is to
135
# keep them isolated from the running environment as mush as possible. The test
136
# framework ensures the variables defined below are set (or deleted if the
137
# value is None) before a test is run and reset to their original value after
138
# the test is run. Generally if some code depends on an environment variable,
139
# the tests should start without this variable in the environment. There are a
140
# few exceptions but you shouldn't violate this rule lightly.
141
isolated_environ = {
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
142
    'BRZ_HOME': None,
5574.6.7 by Vincent Ladeuil
Set HOME to None in isolated_environ and rename DocTestSuite to BzrDocTestSuite to reduce confusion (I still think it's a bad name space usage :)
143
    'HOME': None,
6770.2.5 by Jelmer Vernooij
Set GNUPGHOME in tests.
144
    'GNUPGHOME': None,
6437.58.1 by Wouter van Heyst
Properly isolate all tests from XDG_CONFIG_HOME.
145
    'XDG_CONFIG_HOME': None,
6622.1.30 by Jelmer Vernooij
Some more test fixes.
146
    # brz now uses the Win32 API and doesn't rely on APPDATA, but the
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
147
    # tests do check our impls match APPDATA
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
148
    'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
149
    'VISUAL': None,
150
    'EDITOR': None,
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
151
    'BRZ_EMAIL': None,
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
152
    'BZREMAIL': None, # may still be present in the environment
6622.1.30 by Jelmer Vernooij
Some more test fixes.
153
    'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
154
    'BRZ_PROGRESS_BAR': None,
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
155
    # This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
156
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
157
    # TestCase should not use disk resources, BRZ_LOG is one.
158
    'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
6651.4.1 by Martin
Rewrite of the plugin module for Python 3 compat and general sanity
159
    'BRZ_PLUGIN_PATH': '-site',
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
160
    'BRZ_DISABLE_PLUGINS': None,
161
    'BRZ_PLUGINS_AT': None,
162
    'BRZ_CONCURRENCY': None,
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
163
    # Make sure that any text ui tests are consistent regardless of
164
    # the environment the test case is run in; you may want tests that
165
    # test other combinations.  'dumb' is a reasonable guess for tests
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
166
    # going to a pipe or a BytesIO.
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
167
    'TERM': 'dumb',
168
    'LINES': '25',
169
    'COLUMNS': '80',
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
170
    'BRZ_COLUMNS': '80',
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
171
    # Disable SSH Agent
172
    'SSH_AUTH_SOCK': None,
173
    # Proxies
174
    'http_proxy': None,
175
    'HTTP_PROXY': None,
176
    'https_proxy': None,
177
    'HTTPS_PROXY': None,
178
    'no_proxy': None,
179
    'NO_PROXY': None,
180
    'all_proxy': None,
181
    'ALL_PROXY': None,
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
182
    'BZR_REMOTE_PATH': None,
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
183
    # Generally speaking, we don't want apport reporting on crashes in
184
    # the test envirnoment unless we're specifically testing apport,
185
    # so that it doesn't leak into the real system environment.  We
186
    # use an env var so it propagates to subprocesses.
187
    'APPORT_DISABLE': '1',
188
    }
189
190
191
def override_os_environ(test, env=None):
192
    """Modify os.environ keeping a copy.
6793.3.1 by Jelmer Vernooij
Prevent leaking of BRZ_HOME into doctests.
193
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
194
    :param test: A test instance
195
196
    :param env: A dict containing variable definitions to be installed
197
    """
198
    if env is None:
199
        env = isolated_environ
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
200
    test._original_os_environ = dict(**os.environ)
201
    for var in env:
202
        osutils.set_or_unset_env(var, env[var])
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
203
        if var not in test._original_os_environ:
204
            # The var is new, add it with a value of None, so
205
            # restore_os_environ will delete it
206
            test._original_os_environ[var] = None
207
208
209
def restore_os_environ(test):
210
    """Restore os.environ to its original state.
211
212
    :param test: A test instance previously passed to override_os_environ.
213
    """
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
214
    for var, value in test._original_os_environ.items():
5574.7.1 by Vincent Ladeuil
Implement a fixture for isolating tests from ``os.environ``.
215
        # Restore the original value (or delete it if the value has been set to
216
        # None in override_os_environ).
217
        osutils.set_or_unset_env(var, value)
218
219
5340.16.14 by Martin
Factor out _type_equality_funcs to a new function
220
def _clear__type_equality_funcs(test):
221
    """Cleanup bound methods stored on TestCase instances
222
223
    Clear the dict breaking a few (mostly) harmless cycles in the affected
224
    unittests released with Python 2.6 and initial Python 2.7 versions.
225
226
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
227
    shipped in Oneiric, an object with no clear method was used, hence the
228
    extra complications, see bug 809048 for details.
229
    """
230
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
231
    if type_equality_funcs is not None:
232
        tef_clear = getattr(type_equality_funcs, "clear", None)
233
        if tef_clear is None:
234
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
235
            if tef_instance_dict is not None:
236
                tef_clear = tef_instance_dict.clear
237
        if tef_clear is not None:
238
            tef_clear()
239
240
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
241
class ExtendedTestResult(testtools.TextTestResult):
2095.4.1 by Martin Pool
Better progress bars during tests
242
    """Accepts, reports and accumulates the results of running tests.
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
243
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
244
    Compared to the unittest version this class adds support for
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
245
    profiling, benchmarking, stopping as soon as a test fails,  and
246
    skipping tests.  There are further-specialized subclasses for
247
    different types of display.
248
249
    When a test finishes, in whatever way, it calls one of the addSuccess,
5690.1.1 by Samuel Bronson
Fix an obvious typo in ExtendedTestResult's docstring.
250
    addFailure or addError methods.  These in turn may redirect to a more
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
251
    specific case for the special test results supported by our extended
252
    tests.
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
253
254
    Note that just one of these objects is fed the results from many tests.
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
255
    """
2095.4.1 by Martin Pool
Better progress bars during tests
256
1185.62.21 by John Arbash Meinel
Allow bzr selftest --one to continue, even if we have a Skipped test.
257
    stop_early = False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
258
2095.4.1 by Martin Pool
Better progress bars during tests
259
    def __init__(self, stream, descriptions, verbosity,
260
                 bench_history=None,
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
261
                 strict=False,
2095.4.1 by Martin Pool
Better progress bars during tests
262
                 ):
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
263
        """Construct new TestResult.
264
265
        :param bench_history: Optionally, a writable file object to accumulate
266
            benchmark results.
267
        """
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
268
        testtools.TextTestResult.__init__(self, stream)
1819.1.1 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Give the test result object an optional benchmark
269
        if bench_history is not None:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
270
            from breezy.version import _get_bzr_source_tree
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
271
            src_tree = _get_bzr_source_tree()
272
            if src_tree:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
273
                try:
274
                    revision_id = src_tree.get_parent_ids()[0]
275
                except IndexError:
276
                    # XXX: if this is a brand new tree, do the same as if there
277
                    # is no branch.
278
                    revision_id = ''
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
279
            else:
280
                # XXX: If there's no branch, what should we do?
281
                revision_id = ''
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
282
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
283
        self._bench_history = bench_history
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
284
        self.ui = ui.ui_factory
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
285
        self.num_tests = 0
2095.4.1 by Martin Pool
Better progress bars during tests
286
        self.error_count = 0
287
        self.failure_count = 0
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
288
        self.known_failure_count = 0
2095.4.1 by Martin Pool
Better progress bars during tests
289
        self.skip_count = 0
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
290
        self.not_applicable_count = 0
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
291
        self.unsupported = {}
2095.4.1 by Martin Pool
Better progress bars during tests
292
        self.count = 0
293
        self._overall_start_time = time.time()
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
294
        self._strict = strict
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
295
        self._first_thread_leaker_id = None
296
        self._tests_leaking_threads_count = 0
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
297
        self._traceback_from_test = None
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
298
4650.1.6 by Robert Collins
Fix interface skew between bzr selftest and python unittest - use stopTestRun not done to end test runs.
299
    def stopTestRun(self):
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
300
        run = self.testsRun
301
        actionTaken = "Ran"
302
        stopTime = time.time()
303
        timeTaken = stopTime - self.startTime
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
304
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
305
        #                the parent class method is similar have to duplicate
306
        self._show_list('ERROR', self.errors)
307
        self._show_list('FAIL', self.failures)
308
        self.stream.write(self.sep2)
309
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
310
                            run, run != 1 and "s" or "", timeTaken))
311
        if not self.wasSuccessful():
312
            self.stream.write("FAILED (")
313
            failed, errored = map(len, (self.failures, self.errors))
314
            if failed:
315
                self.stream.write("failures=%d" % failed)
316
            if errored:
317
                if failed: self.stream.write(", ")
318
                self.stream.write("errors=%d" % errored)
319
            if self.known_failure_count:
320
                if failed or errored: self.stream.write(", ")
321
                self.stream.write("known_failure_count=%d" %
322
                    self.known_failure_count)
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
323
            self.stream.write(")\n")
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
324
        else:
325
            if self.known_failure_count:
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
326
                self.stream.write("OK (known_failures=%d)\n" %
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
327
                    self.known_failure_count)
328
            else:
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
329
                self.stream.write("OK\n")
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
330
        if self.skip_count > 0:
331
            skipped = self.skip_count
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
332
            self.stream.write('%d test%s skipped\n' %
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
333
                                (skipped, skipped != 1 and "s" or ""))
334
        if self.unsupported:
335
            for feature, count in sorted(self.unsupported.items()):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
336
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
337
                    (feature, count))
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
338
        if self._strict:
339
            ok = self.wasStrictlySuccessful()
340
        else:
341
            ok = self.wasSuccessful()
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
342
        if self._first_thread_leaker_id:
4271.2.2 by Robert Collins
Move thread leak reporting to ExtendedTestResult.
343
            self.stream.write(
344
                '%s is leaking threads among %d leaking tests.\n' % (
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
345
                self._first_thread_leaker_id,
346
                self._tests_leaking_threads_count))
4731.2.8 by Vincent Ladeuil
Collect and shutdown clients for SmartTCPServer_for_testing.
347
            # We don't report the main thread as an active one.
4732.2.1 by Vincent Ladeuil
Clearer thread leaks reports.
348
            self.stream.write(
349
                '%d non-main threads were left active in the end.\n'
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
350
                % (len(self._active_threads) - 1))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
351
4789.29.1 by Robert Collins
Show test ids not descriptions when reporting error/failures in tests.
352
    def getDescription(self, test):
353
        return test.id()
354
4794.1.10 by Robert Collins
Add benchmark time details object.
355
    def _extractBenchmarkTime(self, testCase, details=None):
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
356
        """Add a benchmark time for the current test case."""
4794.1.10 by Robert Collins
Add benchmark time details object.
357
        if details and 'benchtime' in details:
358
            return float(''.join(details['benchtime'].iter_bytes()))
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
359
        return getattr(testCase, "_benchtime", None)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
360
6606.1.1 by Jelmer Vernooij
Add local copy of _delta_to_float from testtools, rather than
361
    def _delta_to_float(self, a_timedelta, precision):
362
        # This calls ceiling to ensure that the most pessimistic view of time
363
        # taken is shown (rather than leaving it to the Python %f operator
364
        # to decide whether to round/floor/ceiling. This was added when we
365
        # had pyp3 test failures that suggest a floor was happening.
366
        shift = 10 ** precision
367
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
368
            a_timedelta.microseconds / 1000000.0) * shift) / shift
369
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
370
    def _elapsedTestTimeString(self):
371
        """Return a time string for the overall time the current test has taken."""
5445.1.1 by Martin
Use times from testtools for individual test case timings
372
        return self._formatTime(self._delta_to_float(
6606.1.2 by Jelmer Vernooij
Fix arguments.
373
            self._now() - self._start_datetime, 3))
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
374
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
375
    def _testTimeString(self, testCase):
376
        benchmark_time = self._extractBenchmarkTime(testCase)
377
        if benchmark_time is not None:
4536.5.2 by Martin Pool
Reserve less space for test elapsed time; more space for test name
378
            return self._formatTime(benchmark_time) + "*"
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
379
        else:
4536.5.5 by Martin Pool
More selftest display test tweaks
380
            return self._elapsedTestTimeString()
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
381
382
    def _formatTime(self, seconds):
383
        """Format seconds as milliseconds with leading spaces."""
2196.1.1 by Martin Pool
better formatting of benchmark output so it doesn't wrap
384
        # some benchmarks can take thousands of seconds to run, so we need 8
385
        # places
386
        return "%8dms" % (1000 * seconds)
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
387
2095.4.1 by Martin Pool
Better progress bars during tests
388
    def _shortened_test_description(self, test):
389
        what = test.id()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
390
        what = re.sub(r'^breezy\.tests\.', '', what)
2095.4.1 by Martin Pool
Better progress bars during tests
391
        return what
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
392
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
393
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
394
    #                multiple times in a row, because the handler is added for
395
    #                each test but the container list is shared between cases.
396
    #                See lp:498869 lp:625574 and lp:637725 for background.
397
    def _record_traceback_from_test(self, exc_info):
398
        """Store the traceback from passed exc_info tuple till"""
399
        self._traceback_from_test = exc_info[2]
400
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
401
    def startTest(self, test):
5340.6.2 by Martin
Replace remaining to unittest.TestResult methods with super
402
        super(ExtendedTestResult, self).startTest(test)
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
403
        if self.count == 0:
404
            self.startTests()
5412.1.5 by Martin
Move test count addition into startTest from report methods in subclasses
405
        self.count += 1
2095.4.1 by Martin Pool
Better progress bars during tests
406
        self.report_test_start(test)
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
407
        test.number = self.count
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
408
        self._recordTestStartTime()
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
409
        # Make testtools cases give us the real traceback on failure
410
        addOnException = getattr(test, "addOnException", None)
411
        if addOnException is not None:
412
            addOnException(self._record_traceback_from_test)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
413
        # Only check for thread leaks on breezy derived test cases
5580.2.1 by Martin
Do thread leak detection on bzrlib TestCase instances only rather than anything with addCleanup
414
        if isinstance(test, TestCase):
415
            test.addCleanup(self._check_leaked_threads, test)
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
416
5340.15.1 by John Arbash Meinel
supersede exc-info branch
417
    def stopTest(self, test):
418
        super(ExtendedTestResult, self).stopTest(test)
419
        # Manually break cycles, means touching various private things but hey
420
        getDetails = getattr(test, "getDetails", None)
421
        if getDetails is not None:
422
            getDetails().clear()
5340.16.14 by Martin
Factor out _type_equality_funcs to a new function
423
        _clear__type_equality_funcs(test)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
424
        self._traceback_from_test = None
425
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
426
    def startTests(self):
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
427
        self.report_tests_starting()
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
428
        self._active_threads = threading.enumerate()
429
430
    def _check_leaked_threads(self, test):
5412.1.6 by Martin
Document the less obvious code and note future reporting plans, as requested in review by vila
431
        """See if any threads have leaked since last call
432
433
        A sample of live threads is stored in the _active_threads attribute,
434
        when this method runs it compares the current live threads and any not
435
        in the previous sample are treated as having leaked.
436
        """
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
437
        now_active_threads = set(threading.enumerate())
438
        threads_leaked = now_active_threads.difference(self._active_threads)
439
        if threads_leaked:
440
            self._report_thread_leak(test, threads_leaked, now_active_threads)
441
            self._tests_leaking_threads_count += 1
442
            if self._first_thread_leaker_id is None:
443
                self._first_thread_leaker_id = test.id()
444
            self._active_threads = now_active_threads
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
445
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
446
    def _recordTestStartTime(self):
447
        """Record that a test has started."""
5445.1.1 by Martin
Use times from testtools for individual test case timings
448
        self._start_datetime = self._now()
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
449
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
450
    def addError(self, test, err):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
451
        """Tell result that test finished with an error.
452
453
        Called from the TestCase run() method when the test
454
        fails with an unexpected error.
455
        """
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
456
        self._post_mortem(self._traceback_from_test)
5340.6.2 by Martin
Replace remaining to unittest.TestResult methods with super
457
        super(ExtendedTestResult, self).addError(test, err)
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
458
        self.error_count += 1
459
        self.report_error(test, err)
460
        if self.stop_early:
461
            self.stop()
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
462
463
    def addFailure(self, test, err):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
464
        """Tell result that test failed.
465
466
        Called from the TestCase run() method when the test
467
        fails because e.g. an assert() method failed.
468
        """
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
469
        self._post_mortem(self._traceback_from_test)
5340.6.2 by Martin
Replace remaining to unittest.TestResult methods with super
470
        super(ExtendedTestResult, self).addFailure(test, err)
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
471
        self.failure_count += 1
472
        self.report_failure(test, err)
473
        if self.stop_early:
474
            self.stop()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
475
4794.1.10 by Robert Collins
Add benchmark time details object.
476
    def addSuccess(self, test, details=None):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
477
        """Tell result that test completed successfully.
478
479
        Called from the TestCase run()
480
        """
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
481
        if self._bench_history is not None:
4794.1.10 by Robert Collins
Add benchmark time details object.
482
            benchmark_time = self._extractBenchmarkTime(test, details)
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
483
            if benchmark_time is not None:
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
484
                self._bench_history.write("%s %s\n" % (
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
485
                    self._formatTime(benchmark_time),
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
486
                    test.id()))
2095.4.1 by Martin Pool
Better progress bars during tests
487
        self.report_success(test)
5340.6.2 by Martin
Replace remaining to unittest.TestResult methods with super
488
        super(ExtendedTestResult, self).addSuccess(test)
3224.4.4 by Andrew Bennetts
Tweak clearing of _log_contents (idea from John).
489
        test._log_contents = ''
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
490
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
491
    def addExpectedFailure(self, test, err):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
492
        self.known_failure_count += 1
493
        self.report_known_failure(test, err)
494
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
495
    def addUnexpectedSuccess(self, test, details=None):
496
        """Tell result the test unexpectedly passed, counting as a failure
497
498
        When the minimum version of testtools required becomes 0.9.8 this
499
        can be updated to use the new handling there.
500
        """
501
        super(ExtendedTestResult, self).addFailure(test, details=details)
502
        self.failure_count += 1
503
        self.report_unexpected_success(test,
504
            "".join(details["reason"].iter_text()))
505
        if self.stop_early:
506
            self.stop()
507
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
508
    def addNotSupported(self, test, feature):
509
        """The test will not be run because of a missing feature.
510
        """
511
        # this can be called in two different ways: it may be that the
4780.1.1 by Robert Collins
Make addUnsupported more compatible with other TestResults.
512
        # test started running, and then raised (through requireFeature)
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
513
        # UnavailableFeature.  Alternatively this method can be called
4780.1.1 by Robert Collins
Make addUnsupported more compatible with other TestResults.
514
        # while probing for features before running the test code proper; in
515
        # that case we will see startTest and stopTest, but the test will
516
        # never actually run.
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
517
        self.unsupported.setdefault(str(feature), 0)
518
        self.unsupported[str(feature)] += 1
519
        self.report_unsupported(test, feature)
520
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
521
    def addSkip(self, test, reason):
522
        """A test has not run for 'reason'."""
523
        self.skip_count += 1
524
        self.report_skip(test, reason)
525
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
526
    def addNotApplicable(self, test, reason):
527
        self.not_applicable_count += 1
528
        self.report_not_applicable(test, reason)
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
529
5340.15.1 by John Arbash Meinel
supersede exc-info branch
530
    def _count_stored_tests(self):
531
        """Count of tests instances kept alive due to not succeeding"""
532
        return self.error_count + self.failure_count + self.known_failure_count
533
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
534
    def _post_mortem(self, tb=None):
4685.1.1 by Robert Collins
Use BZR_TEST_PDB=1 to trigger post_mortems in test failures.
535
        """Start a PDB post mortem session."""
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
536
        if os.environ.get('BRZ_TEST_PDB', None):
5459.5.2 by Martin
Add handler to record the traceback from testtools cases to get BZR_TEST_PDB working again
537
            import pdb
538
            pdb.post_mortem(tb)
4685.1.1 by Robert Collins
Use BZR_TEST_PDB=1 to trigger post_mortems in test failures.
539
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
540
    def progress(self, offset, whence):
541
        """The test is adjusting the count of tests to run."""
4573.2.3 by Robert Collins
Support python 2.4.
542
        if whence == SUBUNIT_SEEK_SET:
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
543
            self.num_tests = offset
4573.2.3 by Robert Collins
Support python 2.4.
544
        elif whence == SUBUNIT_SEEK_CUR:
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
545
            self.num_tests += offset
546
        else:
547
            raise errors.BzrError("Unknown whence %r" % whence)
548
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
549
    def report_tests_starting(self):
550
        """Display information before the test run begins"""
551
        if getattr(sys, 'frozen', None) is None:
552
            bzr_path = osutils.realpath(sys.argv[0])
553
        else:
554
            bzr_path = sys.executable
555
        self.stream.write(
6622.1.30 by Jelmer Vernooij
Some more test fixes.
556
            'brz selftest: %s\n' % (bzr_path,))
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
557
        self.stream.write(
558
            '   %s\n' % (
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
559
                    breezy.__path__[0],))
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
560
        self.stream.write(
561
            '   bzr-%s python-%s %s\n' % (
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
562
                    breezy.version_string,
563
                    breezy._format_version_tuple(sys.version_info),
5412.1.4 by Martin
Fix errors on three selftest tests by splitting report_tests_starting out of startTests
564
                    platform.platform(aliased=1),
565
                    ))
566
        self.stream.write('\n')
567
5412.1.3 by Martin
Add tests for test case thread leak detection
568
    def report_test_start(self, test):
569
        """Display information on the test just about to be run"""
570
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
571
    def _report_thread_leak(self, test, leaked_threads, active_threads):
572
        """Display information on a test that leaked one or more threads"""
5412.1.6 by Martin
Document the less obvious code and note future reporting plans, as requested in review by vila
573
        # GZ 2010-09-09: A leak summary reported separately from the general
574
        #                thread debugging would be nice. Tests under subunit
575
        #                need something not using stream, perhaps adding a
576
        #                testtools details object would be fitting.
5412.1.1 by Martin
Move leak detection code from TestCase to ExtendedTestResult and clean up
577
        if 'threads' in selftest_debug_flags:
578
            self.stream.write('%s is leaking, active is now %d\n' %
579
                (test.id(), len(active_threads)))
580
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
581
    def startTestRun(self):
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
582
        self.startTime = time.time()
583
2095.4.1 by Martin Pool
Better progress bars during tests
584
    def report_success(self, test):
585
        pass
586
2658.3.1 by Daniel Watkins
Added ExtendedTestResult.wasStrictlySuccessful.
587
    def wasStrictlySuccessful(self):
588
        if self.unsupported or self.known_failure_count:
589
            return False
590
        return self.wasSuccessful()
591
592
2095.4.1 by Martin Pool
Better progress bars during tests
593
class TextTestResult(ExtendedTestResult):
594
    """Displays progress and results of tests in text form"""
595
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
596
    def __init__(self, stream, descriptions, verbosity,
597
                 bench_history=None,
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
598
                 strict=None,
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
599
                 ):
600
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
601
            bench_history, strict)
4580.3.2 by Martin Pool
TextTestResult now clears off the pb when the tests are done
602
        self.pb = self.ui.nested_progress_bar()
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
603
        self.pb.show_pct = False
604
        self.pb.show_spinner = False
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
605
        self.pb.show_eta = False,
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
606
        self.pb.show_count = False
607
        self.pb.show_bar = False
4580.3.3 by Martin Pool
Test progress bar has zero latency so it's more accurate
608
        self.pb.update_latency = 0
4580.3.5 by Martin Pool
selftest sets ProgressTask.show_transport_activity off
609
        self.pb.show_transport_activity = False
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
610
4650.1.6 by Robert Collins
Fix interface skew between bzr selftest and python unittest - use stopTestRun not done to end test runs.
611
    def stopTestRun(self):
4580.3.6 by Martin Pool
TextTestResult should also clear pb before done()
612
        # called when the tests that are going to run have run
613
        self.pb.clear()
4650.1.7 by Robert Collins
Push result reporting thoroughly into TestResult.
614
        self.pb.finished()
4650.1.6 by Robert Collins
Fix interface skew between bzr selftest and python unittest - use stopTestRun not done to end test runs.
615
        super(TextTestResult, self).stopTestRun()
4580.3.6 by Martin Pool
TextTestResult should also clear pb before done()
616
5425.3.2 by Martin
Delay writing test start reports to inside first test run
617
    def report_tests_starting(self):
618
        super(TextTestResult, self).report_tests_starting()
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
619
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
2095.4.1 by Martin Pool
Better progress bars during tests
620
621
    def _progress_prefix_text(self):
3297.1.1 by Martin Pool
More concise display of test progress bar
622
        # the longer this text, the less space we have to show the test
623
        # name...
624
        a = '[%d' % self.count              # total that have been run
625
        # tests skipped as known not to be relevant are not important enough
626
        # to show here
627
        ## if self.skip_count:
628
        ##     a += ', %d skip' % self.skip_count
629
        ## if self.known_failure_count:
630
        ##     a += '+%dX' % self.known_failure_count
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
631
        if self.num_tests:
2095.4.1 by Martin Pool
Better progress bars during tests
632
            a +='/%d' % self.num_tests
3297.1.1 by Martin Pool
More concise display of test progress bar
633
        a += ' in '
634
        runtime = time.time() - self._overall_start_time
635
        if runtime >= 60:
636
            a += '%dm%ds' % (runtime / 60, runtime % 60)
637
        else:
638
            a += '%ds' % runtime
4917.1.1 by Martin Pool
Test progress bar now lumps together tests that error and those that fail
639
        total_fail_count = self.error_count + self.failure_count
640
        if total_fail_count:
641
            a += ', %d failed' % total_fail_count
4721.1.1 by Martin Pool
Stop showing the number of tests due to missing features in the test progress bar.
642
        # if self.unsupported:
643
        #     a += ', %d missing' % len(self.unsupported)
2095.4.3 by Martin Pool
Tweak test display a bit more
644
        a += ']'
2095.4.1 by Martin Pool
Better progress bars during tests
645
        return a
646
647
    def report_test_start(self, test):
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
648
        self.pb.update(
2095.4.1 by Martin Pool
Better progress bars during tests
649
                self._progress_prefix_text()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
650
                + ' '
2095.4.1 by Martin Pool
Better progress bars during tests
651
                + self._shortened_test_description(test))
652
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
653
    def _test_description(self, test):
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
654
        return self._shortened_test_description(test)
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
655
2095.4.3 by Martin Pool
Tweak test display a bit more
656
    def report_error(self, test, err):
5159.2.1 by Vincent Ladeuil
bzrlib.tests.TextTestResult should use self.stream not ui.note.
657
        self.stream.write('ERROR: %s\n    %s\n' % (
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
658
            self._test_description(test),
2095.4.3 by Martin Pool
Tweak test display a bit more
659
            err[1],
4471.2.2 by Martin Pool
Deprecate ProgressTask.note
660
            ))
2095.4.1 by Martin Pool
Better progress bars during tests
661
2095.4.3 by Martin Pool
Tweak test display a bit more
662
    def report_failure(self, test, err):
5159.2.1 by Vincent Ladeuil
bzrlib.tests.TextTestResult should use self.stream not ui.note.
663
        self.stream.write('FAIL: %s\n    %s\n' % (
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
664
            self._test_description(test),
2095.4.3 by Martin Pool
Tweak test display a bit more
665
            err[1],
4471.2.2 by Martin Pool
Deprecate ProgressTask.note
666
            ))
2095.4.1 by Martin Pool
Better progress bars during tests
667
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
668
    def report_known_failure(self, test, err):
4794.1.15 by Robert Collins
Review feedback.
669
        pass
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
670
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
671
    def report_unexpected_success(self, test, reason):
672
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
673
            self._test_description(test),
674
            "Unexpected success. Should have failed",
675
            reason,
676
            ))
677
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
678
    def report_skip(self, test, reason):
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
679
        pass
680
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
681
    def report_not_applicable(self, test, reason):
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
682
        pass
2095.4.1 by Martin Pool
Better progress bars during tests
683
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
684
    def report_unsupported(self, test, feature):
685
        """test cannot be run because feature is missing."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
686
2095.4.1 by Martin Pool
Better progress bars during tests
687
688
class VerboseTestResult(ExtendedTestResult):
689
    """Produce long output, with one line per test run plus times"""
690
691
    def _ellipsize_to_right(self, a_string, final_width):
692
        """Truncate and pad a string, keeping the right hand side"""
693
        if len(a_string) > final_width:
694
            result = '...' + a_string[3-final_width:]
695
        else:
696
            result = a_string
697
        return result.ljust(final_width)
698
5425.3.2 by Martin
Delay writing test start reports to inside first test run
699
    def report_tests_starting(self):
2095.4.1 by Martin Pool
Better progress bars during tests
700
        self.stream.write('running %d tests...\n' % self.num_tests)
5425.3.2 by Martin
Delay writing test start reports to inside first test run
701
        super(VerboseTestResult, self).report_tests_starting()
2095.4.1 by Martin Pool
Better progress bars during tests
702
703
    def report_test_start(self, test):
704
        name = self._shortened_test_description(test)
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
705
        width = osutils.terminal_width()
706
        if width is not None:
707
            # width needs space for 6 char status, plus 1 for slash, plus an
708
            # 11-char time string, plus a trailing blank
709
            # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
710
            # space
711
            self.stream.write(self._ellipsize_to_right(name, width-18))
712
        else:
713
            self.stream.write(name)
2095.4.1 by Martin Pool
Better progress bars during tests
714
        self.stream.flush()
715
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
716
    def _error_summary(self, err):
717
        indent = ' ' * 4
718
        return '%s%s' % (indent, err[1])
719
2095.4.3 by Martin Pool
Tweak test display a bit more
720
    def report_error(self, test, err):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
721
        self.stream.write('ERROR %s\n%s\n'
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
722
                % (self._testTimeString(test),
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
723
                   self._error_summary(err)))
2095.4.1 by Martin Pool
Better progress bars during tests
724
2095.4.3 by Martin Pool
Tweak test display a bit more
725
    def report_failure(self, test, err):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
726
        self.stream.write(' FAIL %s\n%s\n'
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
727
                % (self._testTimeString(test),
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
728
                   self._error_summary(err)))
2095.4.1 by Martin Pool
Better progress bars during tests
729
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
730
    def report_known_failure(self, test, err):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
731
        self.stream.write('XFAIL %s\n%s\n'
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
732
                % (self._testTimeString(test),
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
733
                   self._error_summary(err)))
734
5868.1.2 by Martin
Treat unexpected successes as failures in bzrlib test code
735
    def report_unexpected_success(self, test, reason):
736
        self.stream.write(' FAIL %s\n%s: %s\n'
737
                % (self._testTimeString(test),
738
                   "Unexpected success. Should have failed",
739
                   reason))
740
2095.4.1 by Martin Pool
Better progress bars during tests
741
    def report_success(self, test):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
742
        self.stream.write('   OK %s\n' % self._testTimeString(test))
2095.4.1 by Martin Pool
Better progress bars during tests
743
        for bench_called, stats in getattr(test, '_benchcalls', []):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
744
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
2095.4.1 by Martin Pool
Better progress bars during tests
745
            stats.pprint(file=self.stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
746
        # flush the stream so that we get smooth output. This verbose mode is
747
        # used to show the output in PQM.
2095.4.1 by Martin Pool
Better progress bars during tests
748
        self.stream.flush()
749
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
750
    def report_skip(self, test, reason):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
751
        self.stream.write(' SKIP %s\n%s\n'
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
752
                % (self._testTimeString(test), reason))
2095.4.1 by Martin Pool
Better progress bars during tests
753
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
754
    def report_not_applicable(self, test, reason):
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
755
        self.stream.write('  N/A %s\n    %s\n'
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
756
                % (self._testTimeString(test), reason))
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
757
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
758
    def report_unsupported(self, test, feature):
759
        """test cannot be run because feature is missing."""
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
760
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
761
                %(self._testTimeString(test), feature))
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
762
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
763
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
764
class TextTestRunner(object):
1185.16.58 by mbp at sourcefrog
- run all selftests by default
765
    stop_on_failure = False
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
766
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
767
    def __init__(self,
768
                 stream=sys.stderr,
769
                 descriptions=0,
770
                 verbosity=1,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
771
                 bench_history=None,
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
772
                 strict=False,
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
773
                 result_decorators=None,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
774
                 ):
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
775
        """Create a TextTestRunner.
776
777
        :param result_decorators: An optional list of decorators to apply
778
            to the result object being used by the runner. Decorators are
779
            applied left to right - the first element in the list is the 
780
            innermost decorator.
781
        """
4794.1.8 by Robert Collins
Move the passing of test logs to the result to be via the getDetails API and remove all public use of TestCase._get_log.
782
        # stream may know claim to know to write unicode strings, but in older
783
        # pythons this goes sufficiently wrong that it is a bad idea. (
784
        # specifically a built in file with encoding 'UTF-8' will still try
785
        # to encode using ascii.
786
        new_encoding = osutils.get_terminal_encoding()
4794.1.12 by Robert Collins
Create a StreamWriter helper that doesn't trigger implicit decode('ascii') on write(a_str).
787
        codec = codecs.lookup(new_encoding)
6691.1.3 by Jelmer Vernooij
Drop python2.4 compatibility for encoding in selftest.
788
        encode = codec.encode
5410.2.1 by Martin
Escape unprintable test result output rather than aborting selftest
789
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
790
        #                so should swap to the plain codecs.StreamWriter
791
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
792
            "backslashreplace")
4794.1.8 by Robert Collins
Move the passing of test logs to the result to be via the getDetails API and remove all public use of TestCase._get_log.
793
        stream.encoding = new_encoding
5340.6.1 by Martin
Avoid Python 2.7 unittest incompatibilites
794
        self.stream = stream
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
795
        self.descriptions = descriptions
796
        self.verbosity = verbosity
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
797
        self._bench_history = bench_history
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
798
        self._strict = strict
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
799
        self._result_decorators = result_decorators or []
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
800
801
    def run(self, test):
802
        "Run the given test case or test suite."
2095.4.1 by Martin Pool
Better progress bars during tests
803
        if self.verbosity == 1:
804
            result_class = TextTestResult
805
        elif self.verbosity >= 2:
806
            result_class = VerboseTestResult
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
807
        original_result = result_class(self.stream,
2095.4.1 by Martin Pool
Better progress bars during tests
808
                              self.descriptions,
809
                              self.verbosity,
810
                              bench_history=self._bench_history,
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
811
                              strict=self._strict,
2095.4.1 by Martin Pool
Better progress bars during tests
812
                              )
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
813
        # Signal to result objects that look at stop early policy to stop,
814
        original_result.stop_early = self.stop_on_failure
815
        result = original_result
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
816
        for decorator in self._result_decorators:
4650.1.8 by Robert Collins
Push all starting up reporting down into startTestRun.
817
            result = decorator(result)
818
            result.stop_early = self.stop_on_failure
819
        result.startTestRun()
820
        try:
821
            test.run(result)
822
        finally:
823
            result.stopTestRun()
824
        # higher level code uses our extended protocol to determine
825
        # what exit code to give.
826
        return original_result
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
827
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
828
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
829
def iter_suite_tests(suite):
830
    """Return all tests in a suite, recursing through nested suites"""
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
831
    if isinstance(suite, unittest.TestCase):
832
        yield suite
833
    elif isinstance(suite, unittest.TestSuite):
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
834
        for item in suite:
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
835
            for r in iter_suite_tests(item):
836
                yield r
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
837
    else:
838
        raise Exception('unknown type %r for object %r'
839
                        % (type(suite), suite))
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
840
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
841
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).
842
TestSkipped = testtools.testcase.TestSkipped
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
843
844
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
845
class TestNotApplicable(TestSkipped):
846
    """A test is not applicable to the situation where it was run.
847
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
848
    This is only normally raised by parameterized tests, if they find that
849
    the instance they're constructed upon does not support one aspect
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
850
    of its interface.
851
    """
852
853
4794.1.8 by Robert Collins
Move the passing of test logs to the result to be via the getDetails API and remove all public use of TestCase._get_log.
854
# traceback._some_str fails to format exceptions that have the default
855
# __str__ which does an implicit ascii conversion. However, repr() on those
856
# objects works, for all that its not quite what the doctor may have ordered.
857
def _clever_some_str(value):
858
    try:
859
        return str(value)
860
    except:
861
        try:
862
            return repr(value).replace('\\n', '\n')
863
        except:
864
            return '<unprintable %s object>' % type(value).__name__
865
866
traceback._some_str = _clever_some_str
867
868
4794.1.16 by Robert Collins
Clearer comment on KnownFailure deprecation.
869
# deprecated - use self.knownFailure(), or self.expectFailure.
4794.1.15 by Robert Collins
Review feedback.
870
KnownFailure = testtools.testcase._ExpectedFailure
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
871
872
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
873
class UnavailableFeature(Exception):
874
    """A feature required for this test was not available.
875
4780.1.1 by Robert Collins
Make addUnsupported more compatible with other TestResults.
876
    This can be considered a specialised form of SkippedTest.
877
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
878
    The feature should be used to construct the exception.
879
    """
880
881
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
882
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
883
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
884
    @symbol_versioning.deprecated_method(
885
        symbol_versioning.deprecated_in((3, 0)))
1185.85.8 by John Arbash Meinel
Adding wrapper for sys.stdout so we can set the output encoding. Adding tests that 'bzr log' handles multiple encodings properly
886
    def __init__(self, s=None):
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
887
        super(StringIOWrapper, self).__init__(s)
888
889
890
TestUIFactory = ui_testing.TestUIFactory
4463.1.2 by Martin Pool
merge trunk
891
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
892
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.
893
def isolated_doctest_setUp(test):
894
    override_os_environ(test)
6793.3.1 by Jelmer Vernooij
Prevent leaking of BRZ_HOME into doctests.
895
    osutils.set_or_unset_env('BRZ_HOME', '/nonexistent')
6621.19.1 by Martin
Isolate bd. tests properly to prevent test progress kipple
896
    test._orig_ui_factory = ui.ui_factory
897
    ui.ui_factory = ui.SilentUIFactory()
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.
898
899
900
def isolated_doctest_tearDown(test):
901
    restore_os_environ(test)
6621.19.1 by Martin
Isolate bd. tests properly to prevent test progress kipple
902
    ui.ui_factory = test._orig_ui_factory
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.
903
904
905
def IsolatedDocTestSuite(*args, **kwargs):
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
906
    """Overrides doctest.DocTestSuite to handle isolation.
907
908
    The method is really a factory and users are expected to use it as such.
909
    """
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
910
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.
911
    kwargs['setUp'] = isolated_doctest_setUp
912
    kwargs['tearDown'] = isolated_doctest_tearDown
5574.7.3 by Vincent Ladeuil
Some test infrastructure for tests.DocTestSuite.
913
    return doctest.DocTestSuite(*args, **kwargs)
914
915
4794.1.1 by Robert Collins
Derive bzr's TestCase from testtools.testcase.TestCase.
916
class TestCase(testtools.TestCase):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
917
    """Base class for brz unit tests.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
918
919
    Tests that need access to disk resources should subclass
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
920
    TestCaseInTempDir not TestCase.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
921
922
    Error and debug log messages are redirected from their usual
923
    location into a temporary file, the contents of which can be
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
924
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
925
    so that it can also capture file IO.  When the test completes this file
926
    is read into memory and removed from disk.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
927
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
928
    There are also convenience functions to invoke bzr's command-line
6622.1.30 by Jelmer Vernooij
Some more test fixes.
929
    routine, and to build and check brz trees.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
930
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
931
    In addition to the usual method of overriding tearDown(), this class also
5425.2.2 by Andrew Bennetts
Remove addCleanup (testtools implements this for us), remove some unused imports.
932
    allows subclasses to register cleanup functions via addCleanup, which are
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
933
    run in order as the object is torn down.  It's less likely this will be
934
    accidentally overlooked.
935
    """
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
936
5404.1.1 by Andrew Bennetts
Use StringIO rather than real files on disk for log files in tests.
937
    _log_file = None
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
938
    # record lsprof data when performing benchmark calls.
939
    _gather_lsprof_in_benchmarks = False
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
940
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
941
    def __init__(self, methodName='testMethod'):
942
        super(TestCase, self).__init__(methodName)
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.
943
        self._directory_isolation = True
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).
944
        self.exception_handlers.insert(0,
945
            (UnavailableFeature, self._do_unsupported_or_skip))
946
        self.exception_handlers.insert(0,
947
            (TestNotApplicable, self._do_not_applicable))
4794.1.8 by Robert Collins
Move the passing of test logs to the result to be via the getDetails API and remove all public use of TestCase._get_log.
948
949
    def setUp(self):
950
        super(TestCase, self).setUp()
6319.1.1 by Martin Pool
Add selftest.timeout option, defaulting to 600
951
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
952
        # At this point we're still accessing the config files in $BRZ_HOME (as
6499.3.9 by Vincent Ladeuil
Provide fresh config stores for tests.
953
        # set by the user running selftest).
6319.1.3 by Martin Pool
Cope if no selftest.timeout is set
954
        timeout = config.GlobalStack().get('selftest.timeout')
955
        if timeout:
956
            timeout_fixture = fixtures.TimeoutFixture(timeout)
957
            timeout_fixture.setUp()
958
            self.addCleanup(timeout_fixture.cleanUp)
6319.1.1 by Martin Pool
Add selftest.timeout option, defaulting to 600
959
6319.1.4 by Martin Pool
Set up test timeouts before configuring features
960
        for feature in getattr(self, '_test_needs_features', []):
961
            self.requireFeature(feature)
962
        self._cleanEnvironment()
963
6759.4.2 by Jelmer Vernooij
Use get_global_state>
964
        self.overrideAttr(breezy.get_global_state(), 'cmdline_overrides',
965
                          config.CommandLineStore())
6319.1.1 by Martin Pool
Add selftest.timeout option, defaulting to 600
966
2095.4.1 by Martin Pool
Better progress bars during tests
967
        self._silenceUI()
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
968
        self._startLogFile()
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
969
        self._benchcalls = []
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)
970
        self._benchtime = None
2423.1.1 by Martin Pool
fix import order dependency that broke benchmarks
971
        self._clear_hooks()
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.
972
        self._track_transports()
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
973
        self._track_locks()
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
974
        self._clear_debug_flags()
5463.1.1 by Martin Pool
Isolate bzrlib.trace._verbosity_level per test case
975
        # Isolate global verbosity level, to make sure it's reproducible
976
        # between tests.  We should get rid of this altogether: bug 656694. --
977
        # mbp 20101008
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
978
        self.overrideAttr(breezy.trace, '_verbosity_level', 0)
5923.2.3 by Andrew Bennetts
Make a nice helper method rather than using a closure, cope better with multiple subprocesses, and add a release-notes entry.
979
        self._log_files = set()
5743.14.13 by Vincent Ladeuil
Some more doc and tests.
980
        # Each key in the ``_counters`` dict holds a value for a different
5743.14.19 by Vincent Ladeuil
Cleanup.
981
        # counter. When the test ends, addDetail() should be used to output the
982
        # counter values. This happens in install_counter_hook().
5743.15.1 by Martin
Poke machinery of counter stats in selftest
983
        self._counters = {}
5743.14.2 by Vincent Ladeuil
Rough implementation to output config stats via the subunit AddDetail API.
984
        if 'config_stats' in selftest_debug_flags:
985
            self._install_config_stats_hooks()
6131.1.1 by Jonathan Riddell
do not use i18n in tests
986
        # Do not use i18n for tests (unless the test reverses this)
6133.3.13 by Jonathan Riddell
vila sorts it out, fix disable_i18n() and use it in tests.__init__
987
        i18n.disable_i18n()
3406.1.2 by Vincent Ladeuil
Fix as per Robert's review.
988
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
989
    def debug(self):
990
        # debug a frame up.
991
        import pdb
6082.3.2 by Vincent Ladeuil
Simplify and fix test.debug too.
992
        # The sys preserved stdin/stdout should allow blackbox tests debugging
993
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
994
                ).set_trace(sys._getframe().f_back)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
995
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
996
    def discardDetail(self, name):
997
        """Extend the addDetail, getDetails api so we can remove a detail.
998
6622.1.30 by Jelmer Vernooij
Some more test fixes.
999
        eg. brz always adds the 'log' detail at startup, but we don't want to
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1000
        include it for skipped, xfail, etc tests.
1001
1002
        It is safe to call this for a detail that doesn't exist, in case this
1003
        gets called multiple times.
1004
        """
1005
        # We cheat. details is stored in __details which means we shouldn't
1006
        # touch it. but getDetails() returns the dict directly, so we can
1007
        # mutate it.
1008
        details = self.getDetails()
1009
        if name in details:
1010
            del details[name]
1011
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1012
    def install_counter_hook(self, hooks, name, counter_name=None):
1013
        """Install a counting hook.
1014
1015
        Any hook can be counted as long as it doesn't need to return a value.
1016
1017
        :param hooks: Where the hook should be installed.
1018
1019
        :param name: The hook name that will be counted.
1020
1021
        :param counter_name: The counter identifier in ``_counters``, defaults
1022
            to ``name``.
1023
        """
5743.15.1 by Martin
Poke machinery of counter stats in selftest
1024
        _counters = self._counters # Avoid closing over self
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1025
        if counter_name is None:
1026
            counter_name = name
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
1027
        if counter_name in _counters:
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1028
            raise AssertionError('%s is already used as a counter name'
1029
                                  % (counter_name,))
5743.15.1 by Martin
Poke machinery of counter stats in selftest
1030
        _counters[counter_name] = 0
1031
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
6724.1.1 by Martin
Make adding numbers to test details work on Python 3
1032
            lambda: [b'%d' % (_counters[counter_name],)]))
5743.15.1 by Martin
Poke machinery of counter stats in selftest
1033
        def increment_counter(*args, **kwargs):
1034
            _counters[counter_name] += 1
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1035
        label = 'count %s calls' % (counter_name,)
5743.15.1 by Martin
Poke machinery of counter stats in selftest
1036
        hooks.install_named_hook(name, increment_counter, label)
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1037
        self.addCleanup(hooks.uninstall_named_hook, name, label)
1038
5743.14.2 by Vincent Ladeuil
Rough implementation to output config stats via the subunit AddDetail API.
1039
    def _install_config_stats_hooks(self):
1040
        """Install config hooks to count hook calls.
1041
1042
        """
5743.14.8 by Vincent Ladeuil
Catch-up with separate hooks for old and new config
1043
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1044
            self.install_counter_hook(config.ConfigHooks, hook_name,
1045
                                       'config.%s' % (hook_name,))
5743.14.8 by Vincent Ladeuil
Catch-up with separate hooks for old and new config
1046
1047
        # The OldConfigHooks are private and need special handling to protect
1048
        # against recursive tests (tests that run other tests), so we just do
1049
        # manually what registering them into _builtin_known_hooks will provide
1050
        # us.
1051
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
1052
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
5743.14.10 by Vincent Ladeuil
Extract install_counter_hook for clarity and possible reuse
1053
            self.install_counter_hook(config.OldConfigHooks, hook_name,
1054
                                      'old_config.%s' % (hook_name,))
5743.14.2 by Vincent Ladeuil
Rough implementation to output config stats via the subunit AddDetail API.
1055
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1056
    def _clear_debug_flags(self):
1057
        """Prevent externally set debug flags affecting tests.
3882.6.20 by John Arbash Meinel
Clear out the InventoryEntry caches as part of the test suite.
1058
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1059
        Tests that want to use debug flags can just set them in the
1060
        debug_flags set during setup/teardown.
1061
        """
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1062
        # Start with a copy of the current debug flags we can safely modify.
1063
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
1064
        if 'allow_debug' not in selftest_debug_flags:
3302.2.1 by Andrew Bennetts
Add -Dselftest_debug debug flag.
1065
            debug.debug_flags.clear()
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1066
        if 'disable_lock_checks' not in selftest_debug_flags:
1067
            debug.debug_flags.add('strict_locks')
2423.1.1 by Martin Pool
fix import order dependency that broke benchmarks
1068
1069
    def _clear_hooks(self):
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1070
        # prevent hooks affecting tests
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
1071
        known_hooks = hooks.known_hooks
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
1072
        self._preserved_hooks = {}
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
1073
        for key, (parent, name) in known_hooks.iter_parent_objects():
1074
            current_hooks = getattr(parent, name)
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
1075
            self._preserved_hooks[parent] = (name, current_hooks)
5622.3.4 by Jelmer Vernooij
clear/store lazy hooks during tests too.
1076
        self._preserved_lazy_hooks = hooks._lazy_hooks
1077
        hooks._lazy_hooks = {}
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1078
        self.addCleanup(self._restoreHooks)
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
1079
        for key, (parent, name) in known_hooks.iter_parent_objects():
1080
            factory = known_hooks.get(key)
5622.3.9 by Jelmer Vernooij
Revert unnecessary changes.
1081
            setattr(parent, name, factory())
4160.2.4 by Andrew Bennetts
Use BzrDir pre_open hook to jail request code from accessing transports other than the backing transport.
1082
        # this hook should always be installed
1083
        request._install_hook()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1084
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.
1085
    def disable_directory_isolation(self):
1086
        """Turn off directory isolation checks."""
1087
        self._directory_isolation = False
1088
1089
    def enable_directory_isolation(self):
1090
        """Enable directory isolation checks."""
1091
        self._directory_isolation = True
1092
2095.4.1 by Martin Pool
Better progress bars during tests
1093
    def _silenceUI(self):
1094
        """Turn off UI for duration of test"""
1095
        # by default the UI is off; tests can turn it on if they want it.
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1096
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
2095.4.1 by Martin Pool
Better progress bars during tests
1097
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1098
    def _check_locks(self):
1099
        """Check that all lock take/release actions have been paired."""
4523.4.9 by John Arbash Meinel
Change the flags around a bit.
1100
        # We always check for mismatched locks. If a mismatch is found, we
1101
        # fail unless -Edisable_lock_checks is supplied to selftest, in which
1102
        # case we just print a warning.
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1103
        # unhook:
1104
        acquired_locks = [lock for action, lock in self._lock_actions
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
1105
                          if action == 'acquired']
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1106
        released_locks = [lock for action, lock in self._lock_actions
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
1107
                          if action == 'released']
1108
        broken_locks = [lock for action, lock in self._lock_actions
1109
                        if action == 'broken']
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1110
        # trivially, given the tests for lock acquistion and release, if we
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
1111
        # have as many in each list, it should be ok. Some lock tests also
1112
        # break some locks on purpose and should be taken into account by
1113
        # considering that breaking a lock is just a dirty way of releasing it.
1114
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
5425.4.12 by Martin Pool
More readable message about mismatched locks in tests
1115
            message = (
1116
                'Different number of acquired and '
1117
                'released or broken locks.\n'
1118
                'acquired=%s\n'
1119
                'released=%s\n'
1120
                'broken=%s\n' %
1121
                (acquired_locks, released_locks, broken_locks))
4523.4.9 by John Arbash Meinel
Change the flags around a bit.
1122
            if not self._lock_check_thorough:
1123
                # Rather than fail, just warn
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
1124
                print("Broken test %s: %s" % (self, message))
4523.4.9 by John Arbash Meinel
Change the flags around a bit.
1125
                return
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1126
            self.fail(message)
1127
1128
    def _track_locks(self):
1129
        """Track lock activity during tests."""
1130
        self._lock_actions = []
4523.4.9 by John Arbash Meinel
Change the flags around a bit.
1131
        if 'disable_lock_checks' in selftest_debug_flags:
1132
            self._lock_check_thorough = False
1133
        else:
1134
            self._lock_check_thorough = True
4985.2.1 by Vincent Ladeuil
Deploy addAttrCleanup on the whole test suite.
1135
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1136
        self.addCleanup(self._check_locks)
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
1137
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
1138
                                                self._lock_acquired, None)
1139
        _mod_lock.Lock.hooks.install_named_hook('lock_released',
1140
                                                self._lock_released, None)
1141
        _mod_lock.Lock.hooks.install_named_hook('lock_broken',
1142
                                                self._lock_broken, None)
3331.4.1 by Robert Collins
* -Dlock when passed to the selftest (e.g. ``bzr -Dlock selftest``) will
1143
1144
    def _lock_acquired(self, result):
1145
        self._lock_actions.append(('acquired', result))
1146
1147
    def _lock_released(self, result):
1148
        self._lock_actions.append(('released', result))
1149
4327.1.4 by Vincent Ladeuil
Fix lock test failures by taking lock breaking into account.
1150
    def _lock_broken(self, result):
1151
        self._lock_actions.append(('broken', result))
1152
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.
1153
    def permit_dir(self, name):
1154
        """Permit a directory to be used by this test. See permit_url."""
6039.1.5 by Jelmer Vernooij
Add get_transport_from_url and get_transport_from_path functions.
1155
        name_transport = _mod_transport.get_transport_from_path(name)
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.
1156
        self.permit_url(name)
1157
        self.permit_url(name_transport.base)
1158
1159
    def permit_url(self, url):
1160
        """Declare that url is an ok url to use in this test.
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1161
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.
1162
        Do this for memory transports, temporary test directory etc.
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1163
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.
1164
        Do not do this for the current working directory, /tmp, or any other
1165
        preexisting non isolated url.
1166
        """
1167
        if not url.endswith('/'):
1168
            url += '/'
1169
        self._bzr_selftest_roots.append(url)
1170
1171
    def permit_source_tree_branch_repo(self):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1172
        """Permit the source tree brz is running from to be opened.
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.
1173
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1174
        Some code such as breezy.version attempts to read from the brz branch
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1175
        that brz is executing from (if any). This method permits that directory
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.
1176
        to be used in the test suite.
1177
        """
1178
        path = self.get_source_path()
4691.2.5 by Robert Collins
Handle attempted directory access to the source tree by tracing rather than post-success inspection.
1179
        self.record_directory_isolation()
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.
1180
        try:
1181
            try:
4691.2.5 by Robert Collins
Handle attempted directory access to the source tree by tracing rather than post-success inspection.
1182
                workingtree.WorkingTree.open(path)
4691.2.4 by Robert Collins
Handle NotBranchError when looking up source tree.
1183
            except (errors.NotBranchError, errors.NoWorkingTree):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1184
                raise TestSkipped('Needs a working tree of brz sources')
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.
1185
        finally:
1186
            self.enable_directory_isolation()
1187
1188
    def _preopen_isolate_transport(self, transport):
1189
        """Check that all transport openings are done in the test work area."""
4634.43.20 by Andrew Bennetts
Merge from bzr.dev, resolving conflicts.
1190
        while isinstance(transport, pathfilter.PathFilteringTransport):
1191
            # Unwrap pathfiltered transports
1192
            transport = transport.server.backing_transport.clone(
1193
                transport._filter('.'))
1194
        url = transport.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.
1195
        # ReadonlySmartTCPServer_for_testing decorates the backing transport
1196
        # urls it is given by prepending readonly+. This is appropriate as the
1197
        # client shouldn't know that the server is readonly (or not readonly).
1198
        # We could register all servers twice, with readonly+ prepending, but
1199
        # that makes for a long list; this is about the same but easier to
1200
        # read.
1201
        if url.startswith('readonly+'):
1202
            url = url[len('readonly+'):]
1203
        self._preopen_isolate_url(url)
1204
1205
    def _preopen_isolate_url(self, url):
1206
        if not self._directory_isolation:
1207
            return
4691.2.5 by Robert Collins
Handle attempted directory access to the source tree by tracing rather than post-success inspection.
1208
        if self._directory_isolation == 'record':
1209
            self._bzr_selftest_roots.append(url)
1210
            return
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.
1211
        # This prevents all transports, including e.g. sftp ones backed on disk
1212
        # from working unless they are explicitly granted permission. We then
1213
        # depend on the code that sets up test transports to check that they are
1214
        # appropriately isolated and enable their use by calling
1215
        # self.permit_transport()
1216
        if not osutils.is_inside_any(self._bzr_selftest_roots, url):
1217
            raise errors.BzrError("Attempt to escape test isolation: %r %r"
1218
                % (url, self._bzr_selftest_roots))
1219
4691.2.5 by Robert Collins
Handle attempted directory access to the source tree by tracing rather than post-success inspection.
1220
    def record_directory_isolation(self):
1221
        """Gather accessed directories to permit later access.
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1222
1223
        This is used for tests that access the branch brz is running from.
4691.2.5 by Robert Collins
Handle attempted directory access to the source tree by tracing rather than post-success inspection.
1224
        """
1225
        self._directory_isolation = "record"
1226
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
1227
    def start_server(self, transport_server, backing_server=None):
1228
        """Start transport_server for this test.
1229
1230
        This starts the server, registers a cleanup for it and permits the
1231
        server's urls to be used.
1232
        """
1233
        if backing_server is None:
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
1234
            transport_server.start_server()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
1235
        else:
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
1236
            transport_server.start_server(backing_server)
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
1237
        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.
1238
        # Obtain a real transport because if the server supplies a password, it
1239
        # will be hidden from the base on the client side.
6039.1.5 by Jelmer Vernooij
Add get_transport_from_url and get_transport_from_path functions.
1240
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
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.
1241
        # Some transport servers effectively chroot the backing transport;
1242
        # others like SFTPServer don't - users of the transport can walk up the
1243
        # transport to read the entire backing transport. This wouldn't matter
1244
        # except that the workdir tests are given - and that they expect the
1245
        # server's url to point at - is one directory under the safety net. So
1246
        # Branch operations into the transport will attempt to walk up one
1247
        # directory. Chrooting all servers would avoid this but also mean that
1248
        # we wouldn't be testing directly against non-root urls. Alternatively
1249
        # getting the test framework to start the server with a backing server
1250
        # at the actual safety net directory would work too, but this then
1251
        # means that the self.get_url/self.get_transport methods would need
1252
        # to transform all their results. On balance its cleaner to handle it
1253
        # here, and permit a higher url when we have one of these transports.
1254
        if t.base.endswith('/work/'):
1255
            # we have safety net/test root/work
1256
            t = t.clone('../..')
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
1257
        elif isinstance(transport_server,
1258
                        test_server.SmartTCPServer_for_testing):
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.
1259
            # The smart server adds a path similar to work, which is traversed
1260
            # up from by the client. But the server is chrooted - the actual
1261
            # backing transport is not escaped from, and VFS requests to the
1262
            # root will error (because they try to escape the chroot).
1263
            t2 = t.clone('..')
1264
            while t2.base != t.base:
1265
                t = t2
1266
                t2 = t.clone('..')
1267
        self.permit_url(t.base)
1268
1269
    def _track_transports(self):
1270
        """Install checks for transport usage."""
1271
        # TestCase has no safe place it can write to.
1272
        self._bzr_selftest_roots = []
1273
        # Currently the easiest way to be sure that nothing is going on is to
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1274
        # hook into brz dir opening. This leaves a small window of error for
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.
1275
        # transport tests, but they are well known, and we can improve on this
1276
        # step.
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
1277
        controldir.ControlDir.hooks.install_named_hook("pre_open",
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1278
            self._preopen_isolate_transport, "Check brz directories are safe.")
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
1279
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
1280
    def _ndiff_strings(self, a, b):
1185.16.67 by Martin Pool
- assertEqualDiff handles strings without trailing newline
1281
        """Return ndiff between two strings containing lines.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1282
1185.16.67 by Martin Pool
- assertEqualDiff handles strings without trailing newline
1283
        A trailing newline is added if missing to make the strings
1284
        print properly."""
1285
        if b and b[-1] != '\n':
1286
            b += '\n'
1287
        if a and a[-1] != '\n':
1288
            a += '\n'
1185.16.21 by Martin Pool
- tweak diff shown by assertEqualDiff
1289
        difflines = difflib.ndiff(a.splitlines(True),
1290
                                  b.splitlines(True),
1291
                                  linejunk=lambda x: False,
1292
                                  charjunk=lambda x: False)
1293
        return ''.join(difflines)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1294
2255.2.190 by Martin Pool
assertEqual can take an option message
1295
    def assertEqual(self, a, b, message=''):
2360.1.2 by John Arbash Meinel
Add an overzealous test, for Unicode support of _iter_changes.
1296
        try:
1297
            if a == b:
1298
                return
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1299
        except UnicodeError as e:
2360.1.2 by John Arbash Meinel
Add an overzealous test, for Unicode support of _iter_changes.
1300
            # If we can't compare without getting a UnicodeError, then
1301
            # obviously they are different
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
1302
            trace.mutter('UnicodeError: %s', e)
2255.2.190 by Martin Pool
assertEqual can take an option message
1303
        if message:
1304
            message += '\n'
1305
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1306
            % (message,
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
1307
               pprint.pformat(a), pprint.pformat(b)))
2255.2.185 by Martin Pool
assertEqual uses pformat to show results
1308
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1309
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
1310
    # need a deprecation period for them -- vila 2016-02-01
2255.2.185 by Martin Pool
assertEqual uses pformat to show results
1311
    assertEquals = assertEqual
1312
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1313
    def assertEqualDiff(self, a, b, message=None):
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
1314
        """Assert two texts are equal, if not raise an exception.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1315
1316
        This is intended for use with multi-line strings where it can
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
1317
        be hard to find the differences by eye.
1318
        """
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1319
        # TODO: perhaps override assertEqual to call this for strings?
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
1320
        if a == b:
1321
            return
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1322
        if message is None:
1323
            message = "texts not equal:\n"
4680.1.1 by Vincent Ladeuil
Surprisingly, assertEqualDiff was wrong.
1324
        if a + '\n' == b:
1325
            message = 'first string is missing a final newline.\n'
3468.2.2 by Martin Pool
Better message re final newlines from assertEqualDiff
1326
        if a == b + '\n':
4680.1.2 by Vincent Ladeuil
Blessed be the tests that protect the imprudent :)
1327
            message = 'second string is missing a final newline.\n'
2555.3.3 by Martin Pool
Simple lock tracing in LockDir
1328
        raise AssertionError(message +
1329
                             self._ndiff_strings(a, b))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1330
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1331
    def assertEqualMode(self, mode, mode_test):
1332
        self.assertEqual(mode, mode_test,
1333
                         'mode mismatch %o != %o' % (mode, mode_test))
1334
4807.2.2 by John Arbash Meinel
Move all the stat comparison and platform checkning code to assertEqualStat.
1335
    def assertEqualStat(self, expected, actual):
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
1336
        """assert that expected and actual are the same stat result.
1337
1338
        :param expected: A stat result.
1339
        :param actual: A stat result.
1340
        :raises AssertionError: If the expected and actual stat values differ
1341
            other than by atime.
1342
        """
4789.24.1 by John Arbash Meinel
os.lstat() != os.fstat() for the st_ino field on windows
1343
        self.assertEqual(expected.st_size, actual.st_size,
1344
                         'st_size did not match')
1345
        self.assertEqual(expected.st_mtime, actual.st_mtime,
1346
                         'st_mtime did not match')
1347
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1348
                         'st_ctime did not match')
5609.29.6 by John Arbash Meinel
Change the stat assertions to be sure that we are catching the callers correctly.
1349
        if sys.platform == 'win32':
4807.2.2 by John Arbash Meinel
Move all the stat comparison and platform checkning code to assertEqualStat.
1350
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1351
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
5609.29.6 by John Arbash Meinel
Change the stat assertions to be sure that we are catching the callers correctly.
1352
            # odd. We just force it to always be 0 to avoid any problems.
1353
            self.assertEqual(0, expected.st_dev)
1354
            self.assertEqual(0, actual.st_dev)
1355
            self.assertEqual(0, expected.st_ino)
1356
            self.assertEqual(0, actual.st_ino)
1357
        else:
4807.2.2 by John Arbash Meinel
Move all the stat comparison and platform checkning code to assertEqualStat.
1358
            self.assertEqual(expected.st_dev, actual.st_dev,
1359
                             'st_dev did not match')
4789.24.1 by John Arbash Meinel
os.lstat() != os.fstat() for the st_ino field on windows
1360
            self.assertEqual(expected.st_ino, actual.st_ino,
1361
                             'st_ino did not match')
1362
        self.assertEqual(expected.st_mode, actual.st_mode,
1363
                         'st_mode did not match')
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
1364
4144.1.1 by Robert Collins
New assertLength method based on one Martin has squirreled away somewhere.
1365
    def assertLength(self, length, obj_with_len):
1366
        """Assert that obj_with_len is of length length."""
1367
        if len(obj_with_len) != length:
1368
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
1369
                length, len(obj_with_len), obj_with_len))
1370
4634.85.11 by Andrew Bennetts
Suppress most errors from Branch.unlock too.
1371
    def assertLogsError(self, exception_class, func, *args, **kwargs):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1372
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
4634.85.11 by Andrew Bennetts
Suppress most errors from Branch.unlock too.
1373
        """
1374
        captured = []
1375
        orig_log_exception_quietly = trace.log_exception_quietly
1376
        try:
1377
            def capture():
1378
                orig_log_exception_quietly()
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1379
                captured.append(sys.exc_info()[1])
4634.85.11 by Andrew Bennetts
Suppress most errors from Branch.unlock too.
1380
            trace.log_exception_quietly = capture
1381
            func(*args, **kwargs)
1382
        finally:
1383
            trace.log_exception_quietly = orig_log_exception_quietly
1384
        self.assertLength(1, captured)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1385
        err = captured[0]
4634.85.11 by Andrew Bennetts
Suppress most errors from Branch.unlock too.
1386
        self.assertIsInstance(err, exception_class)
1387
        return err
1388
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
1389
    def assertPositive(self, val):
1390
        """Assert that val is greater than 0."""
1391
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1392
1393
    def assertNegative(self, val):
1394
        """Assert that val is less than 0."""
1395
        self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
1396
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
1397
    def assertStartsWith(self, s, prefix):
1398
        if not s.startswith(prefix):
1399
            raise AssertionError('string %r does not start with %r' % (s, prefix))
1400
1401
    def assertEndsWith(self, s, suffix):
1692.3.1 by Robert Collins
Fix push to work with just a branch, no need for a working tree.
1402
        """Asserts that s ends with suffix."""
1403
        if not s.endswith(suffix):
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
1404
            raise AssertionError('string %r does not end with %r' % (s, suffix))
1185.16.42 by Martin Pool
- Add assertContainsRe
1405
3940.1.1 by Ian Clatworthy
support flags when asserting re's in tests
1406
    def assertContainsRe(self, haystack, needle_re, flags=0):
1185.16.42 by Martin Pool
- Add assertContainsRe
1407
        """Assert that a contains something matching a regular expression."""
3940.1.1 by Ian Clatworthy
support flags when asserting re's in tests
1408
        if not re.search(needle_re, haystack, flags):
2555.3.1 by Martin Pool
Better messages from assertContainsRe
1409
            if '\n' in haystack or len(haystack) > 60:
1410
                # a long string, format it in a more readable way
1411
                raise AssertionError(
1412
                        'pattern "%s" not found in\n"""\\\n%s"""\n'
1413
                        % (needle_re, haystack))
1414
            else:
1415
                raise AssertionError('pattern "%s" not found in "%s"'
1416
                        % (needle_re, haystack))
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
1417
3940.1.1 by Ian Clatworthy
support flags when asserting re's in tests
1418
    def assertNotContainsRe(self, haystack, needle_re, flags=0):
1185.84.3 by Aaron Bentley
Hide diffs for old revisions in bundles
1419
        """Assert that a does not match a regular expression"""
3940.1.1 by Ian Clatworthy
support flags when asserting re's in tests
1420
        if re.search(needle_re, haystack, flags):
1185.84.3 by Aaron Bentley
Hide diffs for old revisions in bundles
1421
            raise AssertionError('pattern "%s" found in "%s"'
1422
                    % (needle_re, haystack))
1423
5017.2.1 by Martin Pool
Add assertContainsString
1424
    def assertContainsString(self, haystack, needle):
1425
        if haystack.find(needle) == -1:
1426
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1427
5598.1.1 by Soren Hansen
Fix PEP-8 violation in PythonVersionInfoBuilder's output
1428
    def assertNotContainsString(self, haystack, needle):
1429
        if haystack.find(needle) != -1:
1430
            self.fail("string %r found in '''%s'''" % (needle, haystack))
1431
1553.5.3 by Martin Pool
[patch] Rename TestCase.AssertSubset to assertSubset for consistency (Jan Hudec)
1432
    def assertSubset(self, sublist, superlist):
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
1433
        """Assert that every entry in sublist is present in superlist."""
2695.1.4 by Martin Pool
Much faster assertSubset using sets, not O(n**2)
1434
        missing = set(sublist) - set(superlist)
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
1435
        if len(missing) > 0:
2695.1.4 by Martin Pool
Much faster assertSubset using sets, not O(n**2)
1436
            raise AssertionError("value(s) %r not present in container %r" %
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
1437
                                 (missing, superlist))
1438
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
1439
    def assertListRaises(self, excClass, func, *args, **kwargs):
1440
        """Fail unless excClass is raised when the iterator from func is used.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1441
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
1442
        Many functions can return generators this makes sure
1443
        to wrap them in a list() call to make sure the whole generator
1444
        is run, and that the proper exception is raised.
1445
        """
1446
        try:
1447
            list(func(*args, **kwargs))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1448
        except excClass as e:
3287.20.1 by John Arbash Meinel
Update assertListRaises so that it returns the exception.
1449
            return e
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
1450
        else:
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1451
            if getattr(excClass, '__name__', None) is not None:
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
1452
                excName = excClass.__name__
1453
            else:
1454
                excName = str(excClass)
6619.3.11 by Jelmer Vernooij
Use modern exceptions.
1455
            raise self.failureException("%s not raised" % excName)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
1456
2399.1.7 by John Arbash Meinel
Cleanup bzrlib/benchmarks/* so that everything at least has a valid doc string.
1457
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
1458
        """Assert that a callable raises a particular exception.
1459
2323.5.9 by Martin Pool
Clear up assertRaises (r=robert)
1460
        :param excClass: As for the except statement, this may be either an
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1461
            exception class, or a tuple of classes.
2399.1.7 by John Arbash Meinel
Cleanup bzrlib/benchmarks/* so that everything at least has a valid doc string.
1462
        :param callableObj: A callable, will be passed ``*args`` and
1463
            ``**kwargs``.
2323.5.9 by Martin Pool
Clear up assertRaises (r=robert)
1464
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
1465
        Returns the exception so that you can examine it.
1466
        """
1467
        try:
2399.1.10 by John Arbash Meinel
fix assertRaises to use the right parameter...
1468
            callableObj(*args, **kwargs)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1469
        except excClass as e:
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
1470
            return e
1471
        else:
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1472
            if getattr(excClass, '__name__', None) is not None:
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
1473
                excName = excClass.__name__
1474
            else:
2323.5.9 by Martin Pool
Clear up assertRaises (r=robert)
1475
                # probably a tuple
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
1476
                excName = str(excClass)
6619.3.11 by Jelmer Vernooij
Use modern exceptions.
1477
            raise self.failureException("%s not raised" % excName)
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
1478
2220.1.13 by Marius Kruger
Remove assertNone
1479
    def assertIs(self, left, right, message=None):
1185.68.1 by Aaron Bentley
test transactions
1480
        if not (left is right):
2220.1.13 by Marius Kruger
Remove assertNone
1481
            if message is not None:
1482
                raise AssertionError(message)
1483
            else:
1484
                raise AssertionError("%r is not %r." % (left, right))
1485
1486
    def assertIsNot(self, left, right, message=None):
1487
        if (left is right):
1488
            if message is not None:
1489
                raise AssertionError(message)
1490
            else:
1491
                raise AssertionError("%r is %r." % (left, right))
2220.1.4 by Marius Kruger
* bzrlib/tests/__init__
1492
1530.1.21 by Robert Collins
Review feedback fixes.
1493
    def assertTransportMode(self, transport, path, mode):
4031.3.1 by Frank Aspell
Fixing various typos
1494
        """Fail if a path does not have mode "mode".
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1495
1651.1.3 by Martin Pool
Use transport._can_roundtrip_unix_modebits to decide whether to check transport results
1496
        If modes are not supported on this transport, the assertion is ignored.
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
1497
        """
1651.1.3 by Martin Pool
Use transport._can_roundtrip_unix_modebits to decide whether to check transport results
1498
        if not transport._can_roundtrip_unix_modebits():
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
1499
            return
1500
        path_stat = transport.stat(path)
1501
        actual_mode = stat.S_IMODE(path_stat.st_mode)
3508.1.22 by Vincent Ladeuil
Fix python2.4 failures.
1502
        self.assertEqual(mode, actual_mode,
3508.1.15 by Vincent Ladeuil
Tweak chmod bits output for easier debug.
1503
                         'mode of %r incorrect (%s != %s)'
1504
                         % (path, oct(mode), oct(actual_mode)))
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
1505
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
1506
    def assertIsSameRealPath(self, path1, path2):
1507
        """Fail if path1 and path2 points to different files"""
2823.1.11 by Vincent Ladeuil
Review feedback.
1508
        self.assertEqual(osutils.realpath(path1),
1509
                         osutils.realpath(path2),
1510
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
1511
4449.3.12 by Martin Pool
assertIsInstance can take an extra message
1512
    def assertIsInstance(self, obj, kls, msg=None):
1513
        """Fail if obj is not an instance of kls
1514
        
1515
        :param msg: Supplementary message to show if the assertion fails.
1516
        """
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1517
        if not isinstance(obj, kls):
4449.3.12 by Martin Pool
assertIsInstance can take an extra message
1518
            m = "%r is an instance of %s rather than %s" % (
1519
                obj, obj.__class__, kls)
1520
            if msg:
1521
                m += ": " + msg
1522
            self.fail(m)
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1523
3173.1.10 by Martin Pool
Move assertFileEqual to TestCase base class as it's generally usable
1524
    def assertFileEqual(self, content, path):
1525
        """Fail if path does not contain 'content'."""
5784.1.2 by Martin Pool
Deprecate, and test, failIfExists and failUnlessExists
1526
        self.assertPathExists(path)
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
1527
        with open(path, 'rb') as f:
3173.1.10 by Martin Pool
Move assertFileEqual to TestCase base class as it's generally usable
1528
            s = f.read()
1529
        self.assertEqualDiff(content, s)
1530
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1531
    def assertDocstring(self, expected_docstring, obj):
1532
        """Fail if obj does not have expected_docstring"""
1533
        if __doc__ is None:
1534
            # With -OO the docstring should be None instead
1535
            self.assertIs(obj.__doc__, None)
1536
        else:
1537
            self.assertEqual(expected_docstring, obj.__doc__)
1538
5784.1.2 by Martin Pool
Deprecate, and test, failIfExists and failUnlessExists
1539
    def assertPathExists(self, path):
3173.1.12 by Martin Pool
Add test_push_log_file
1540
        """Fail unless path or paths, which may be abs or relative, exist."""
6973.5.13 by Jelmer Vernooij
Add notes about cleanups.
1541
        # TODO(jelmer): Clean this up for pad.lv/1696545
6973.5.10 by Jelmer Vernooij
Random bunch of python3 bee-improvements.
1542
        if not isinstance(path, (bytes, str, text_type)):
3173.1.12 by Martin Pool
Add test_push_log_file
1543
            for p in path:
5784.1.2 by Martin Pool
Deprecate, and test, failIfExists and failUnlessExists
1544
                self.assertPathExists(p)
3173.1.12 by Martin Pool
Add test_push_log_file
1545
        else:
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1546
            self.assertTrue(osutils.lexists(path),
1547
                path + " does not exist")
3173.1.12 by Martin Pool
Add test_push_log_file
1548
5784.1.2 by Martin Pool
Deprecate, and test, failIfExists and failUnlessExists
1549
    def assertPathDoesNotExist(self, path):
3173.1.12 by Martin Pool
Add test_push_log_file
1550
        """Fail if path or paths, which may be abs or relative, exist."""
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
1551
        if not isinstance(path, (str, text_type)):
3173.1.12 by Martin Pool
Add test_push_log_file
1552
            for p in path:
5784.1.2 by Martin Pool
Deprecate, and test, failIfExists and failUnlessExists
1553
                self.assertPathDoesNotExist(p)
3173.1.12 by Martin Pool
Add test_push_log_file
1554
        else:
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1555
            self.assertFalse(osutils.lexists(path),
1556
                path + " exists")
3173.1.12 by Martin Pool
Add test_push_log_file
1557
2592.3.243 by Martin Pool
Rename TestCase._capture_warnings
1558
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1559
        """A helper for callDeprecated and applyDeprecated.
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1560
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1561
        :param a_callable: A callable to call.
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1562
        :param args: The positional arguments for the callable
1563
        :param kwargs: The keyword arguments for the callable
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1564
        :return: A tuple (warnings, result). result is the result of calling
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1565
            a_callable(``*args``, ``**kwargs``).
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1566
        """
1567
        local_warnings = []
2067.3.3 by Martin Pool
merge bzr.dev and reconcile several changes, also some test fixes
1568
        def capture_warnings(msg, cls=None, stacklevel=None):
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1569
            # we've hooked into a deprecation specific callpath,
1570
            # only deprecations should getting sent via it.
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1571
            self.assertEqual(cls, DeprecationWarning)
1572
            local_warnings.append(msg)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1573
        original_warning_method = symbol_versioning.warn
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1574
        symbol_versioning.set_warning_method(capture_warnings)
1575
        try:
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1576
            result = a_callable(*args, **kwargs)
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1577
        finally:
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1578
            symbol_versioning.set_warning_method(original_warning_method)
1579
        return (local_warnings, result)
1580
1581
    def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1582
        """Call a deprecated callable without warning the user.
1583
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1584
        Note that this only captures warnings raised by symbol_versioning.warn,
1585
        not other callers that go direct to the warning module.
1586
2697.2.2 by Martin Pool
deprecate Branch.append_revision
1587
        To test that a deprecated method raises an error, do something like
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
1588
        this (remember that both assertRaises and applyDeprecated delays *args
1589
        and **kwargs passing)::
2697.2.2 by Martin Pool
deprecate Branch.append_revision
1590
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
1591
            self.assertRaises(errors.ReservedId,
1592
                self.applyDeprecated,
1593
                deprecated_in((1, 5, 0)),
1594
                br.append_revision,
1595
                'current:')
2697.2.2 by Martin Pool
deprecate Branch.append_revision
1596
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1597
        :param deprecation_format: The deprecation format that the callable
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1598
            should have been deprecated with. This is the same type as the
1599
            parameter to deprecated_method/deprecated_function. If the
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1600
            callable is not deprecated with this format, an assertion error
1601
            will be raised.
1602
        :param a_callable: A callable to call. This may be a bound method or
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1603
            a regular function. It will be called with ``*args`` and
1604
            ``**kwargs``.
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1605
        :param args: The positional arguments for the callable
1606
        :param kwargs: The keyword arguments for the callable
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1607
        :return: The result of a_callable(``*args``, ``**kwargs``)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1608
        """
2592.3.243 by Martin Pool
Rename TestCase._capture_warnings
1609
        call_warnings, result = self._capture_deprecation_warnings(a_callable,
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1610
            *args, **kwargs)
1611
        expected_first_warning = symbol_versioning.deprecation_string(
1612
            a_callable, deprecation_format)
1613
        if len(call_warnings) == 0:
2255.7.47 by Robert Collins
Improve applyDeprecated warning message.
1614
            self.fail("No deprecation warning generated by call to %s" %
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1615
                a_callable)
1616
        self.assertEqual(expected_first_warning, call_warnings[0])
1617
        return result
1618
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1619
    def callCatchWarnings(self, fn, *args, **kw):
1620
        """Call a callable that raises python warnings.
1621
1622
        The caller's responsible for examining the returned warnings.
1623
1624
        If the callable raises an exception, the exception is not
1625
        caught and propagates up to the caller.  In that case, the list
1626
        of warnings is not available.
1627
1628
        :returns: ([warning_object, ...], fn_result)
1629
        """
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1630
        # XXX: This is not perfect, because it completely overrides the
1631
        # warnings filters, and some code may depend on suppressing particular
1632
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
1633
        # though.  -- Andrew, 20071062
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1634
        wlist = []
3734.5.3 by Vincent Ladeuil
Martin's review feedback.
1635
        def _catcher(message, category, filename, lineno, file=None, line=None):
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1636
            # despite the name, 'message' is normally(?) a Warning subclass
1637
            # instance
1638
            wlist.append(message)
1639
        saved_showwarning = warnings.showwarning
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1640
        saved_filters = warnings.filters
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1641
        try:
1642
            warnings.showwarning = _catcher
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1643
            warnings.filters = []
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1644
            result = fn(*args, **kw)
1645
        finally:
1646
            warnings.showwarning = saved_showwarning
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1647
            warnings.filters = saved_filters
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1648
        return wlist, result
1649
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1650
    def callDeprecated(self, expected, callable, *args, **kwargs):
1651
        """Assert that a callable is deprecated in a particular way.
1652
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1653
        This is a very precise test for unusual requirements. The
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1654
        applyDeprecated helper function is probably more suited for most tests
1655
        as it allows you to simply specify the deprecation format being used
1656
        and will ensure that that is issued for the function being called.
1657
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1658
        Note that this only captures warnings raised by symbol_versioning.warn,
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1659
        not other callers that go direct to the warning module.  To catch
1660
        general warnings, use callCatchWarnings.
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1661
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1662
        :param expected: a list of the deprecation warnings expected, in order
1663
        :param callable: The callable to call
1664
        :param args: The positional arguments for the callable
1665
        :param kwargs: The keyword arguments for the callable
1666
        """
2592.3.243 by Martin Pool
Rename TestCase._capture_warnings
1667
        call_warnings, result = self._capture_deprecation_warnings(callable,
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1668
            *args, **kwargs)
1669
        self.assertEqual(expected, call_warnings)
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1670
        return result
1671
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
1672
    def _startLogFile(self):
6220.1.2 by Martin Packman
Update docstrings on TestCase logging functions to reflect current reality
1673
        """Setup a in-memory target for bzr and testcase log messages"""
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1674
        pseudo_log_file = BytesIO()
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1675
        def _get_log_contents_for_weird_testtools_api():
1676
            return [pseudo_log_file.getvalue().decode(
5923.2.1 by Andrew Bennetts
Rough version of including start_bzr_subprocess's log files in test details.
1677
                "utf-8", "replace").encode("utf-8")]
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1678
        self.addDetail("log", content.Content(content.ContentType("text",
1679
            "plain", {"charset": "utf8"}),
1680
            _get_log_contents_for_weird_testtools_api))
1681
        self._log_file = pseudo_log_file
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
1682
        self._log_memento = trace.push_log_file(self._log_file)
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
1683
        self.addCleanup(self._finishLogFile)
1684
1685
    def _finishLogFile(self):
6220.1.2 by Martin Packman
Update docstrings on TestCase logging functions to reflect current reality
1686
        """Flush and dereference the in-memory log for this testcase"""
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
1687
        if trace._trace_file:
4794.1.9 by Robert Collins
Double \n was deliberate for RandomDecorator.
1688
            # flush the log file, to get all content
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
1689
            trace._trace_file.flush()
1690
        trace.pop_log_file(self._log_memento)
6220.1.1 by Martin Packman
Make triple sure logging cleanup behaves by deleting each _log_memento on TestCase
1691
        # The logging module now tracks references for cleanup so discard ours
1692
        del self._log_memento
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1693
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1694
    def thisFailsStrictLockCheck(self):
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1695
        """It is known that this test would fail with -Dstrict_locks.
1696
1697
        By default, all tests are run with strict lock checking unless
1698
        -Edisable_lock_checks is supplied. However there are some tests which
1699
        we know fail strict locks at this point that have not been fixed.
1700
        They should call this function to disable the strict checking.
4523.4.12 by John Arbash Meinel
Update the test_selftest tests so that they pass again.
1701
1702
        This should be used sparingly, it is much better to fix the locking
1703
        issues rather than papering over the problem by calling this function.
4523.4.11 by John Arbash Meinel
Update the tests, adding a test for -Edisable_lock_checks.
1704
        """
1705
        debug.debug_flags.discard('strict_locks')
1706
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1707
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1708
        """Overrides an object attribute restoring it after the test.
1709
6006.4.10 by Martin Pool
Add caution to overrideAttr docstring
1710
        :note: This should be used with discretion; you should think about
1711
        whether it's better to make the code testable without monkey-patching.
1712
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1713
        :param obj: The object that will be mutated.
1714
1715
        :param attr_name: The attribute name we want to preserve/override in
1716
            the object.
1717
1718
        :param new: The optional value we want to set the attribute to.
4955.6.1 by Vincent Ladeuil
Implement test.addAttrCleanup.
1719
1720
        :returns: The actual attr value.
1721
        """
1722
        # The actual value is captured by the call below
6015.60.1 by John Arbash Meinel
Teach TestCase.overrideAttr how to handle attributes that don't exist yet.
1723
        value = getattr(obj, attr_name, _unitialized_attr)
1724
        if value is _unitialized_attr:
1725
            # When the test completes, the attribute should not exist, but if
1726
            # we aren't setting a value, we don't need to do anything.
1727
            if new is not _unitialized_attr:
1728
                self.addCleanup(delattr, obj, attr_name)
1729
        else:
1730
            self.addCleanup(setattr, obj, attr_name, value)
4985.1.3 by Vincent Ladeuil
Change it to a more usable form.
1731
        if new is not _unitialized_attr:
1732
            setattr(obj, attr_name, new)
4955.6.1 by Vincent Ladeuil
Implement test.addAttrCleanup.
1733
        return value
1734
5570.3.11 by Vincent Ladeuil
Make overrideEnv returns the value to make it even closer to overrideAttr.
1735
    def overrideEnv(self, name, new):
5574.3.2 by Vincent Ladeuil
Fix typo, the test is thinner when the overrideEnv is cleaned up ;0)
1736
        """Set an environment variable, and reset it after the test.
5570.3.17 by Vincent Ladeuil
Final tweaks and doc.
1737
1738
        :param name: The environment variable name.
1739
5570.3.11 by Vincent Ladeuil
Make overrideEnv returns the value to make it even closer to overrideAttr.
1740
        :param new: The value to set the variable to. If None, the 
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
1741
            variable is deleted from the environment.
5570.3.11 by Vincent Ladeuil
Make overrideEnv returns the value to make it even closer to overrideAttr.
1742
1743
        :returns: The actual variable value.
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
1744
        """
5570.3.11 by Vincent Ladeuil
Make overrideEnv returns the value to make it even closer to overrideAttr.
1745
        value = osutils.set_or_unset_env(name, new)
1746
        self.addCleanup(osutils.set_or_unset_env, name, value)
1747
        return value
5570.3.3 by Vincent Ladeuil
Introduce a more robust way to override environment variables (not deployed yet).
1748
6006.4.1 by Martin Pool
Add recordCalls test helper
1749
    def recordCalls(self, obj, attr_name):
1750
        """Monkeypatch in a wrapper that will record calls.
1751
1752
        The monkeypatch is automatically removed when the test concludes.
1753
1754
        :param obj: The namespace holding the reference to be replaced;
1755
            typically a module, class, or object.
1756
        :param attr_name: A string for the name of the attribute to 
1757
            patch.
1758
        :returns: A list that will be extended with one item every time the
1759
            function is called, with a tuple of (args, kwargs).
1760
        """
1761
        calls = []
1762
1763
        def decorator(*args, **kwargs):
6006.4.2 by Martin Pool
Record calls as a list of tuples, not a flattened list
1764
            calls.append((args, kwargs))
6006.4.1 by Martin Pool
Add recordCalls test helper
1765
            return orig(*args, **kwargs)
1766
        orig = self.overrideAttr(obj, attr_name, decorator)
1767
        return calls
1768
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
1769
    def _cleanEnvironment(self):
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1770
        for name, value in isolated_environ.items():
5570.3.5 by Vincent Ladeuil
_cleanEnvironment can use overrideEnv, this prepare future cleanups.
1771
            self.overrideEnv(name, value)
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
1772
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1773
    def _restoreHooks(self):
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
1774
        for klass, (name, hooks) in self._preserved_hooks.items():
1775
            setattr(klass, name, hooks)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1776
        self._preserved_hooks.clear()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1777
        breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
5340.15.1 by John Arbash Meinel
supersede exc-info branch
1778
        self._preserved_lazy_hooks.clear()
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1779
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1780
    def knownFailure(self, reason):
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
1781
        """Declare that this test fails for a known reason
1782
1783
        Tests that are known to fail should generally be using expectedFailure
1784
        with an appropriate reverse assertion if a change could cause the test
1785
        to start passing. Conversely if the test has no immediate prospect of
1786
        succeeding then using skip is more suitable.
1787
1788
        When this method is called while an exception is being handled, that
1789
        traceback will be used, otherwise a new exception will be thrown to
6048.1.2 by Martin
Minor wording nits and add release notes
1790
        provide one but won't be reported.
6048.1.1 by Martin
Adapt TestCase.knownFailure method to the testtools style so unittest changes don't break it
1791
        """
1792
        self._add_reason(reason)
1793
        try:
1794
            exc_info = sys.exc_info()
1795
            if exc_info != (None, None, None):
1796
                self._report_traceback(exc_info)
1797
            else:
1798
                try:
1799
                    raise self.failureException(reason)
1800
                except self.failureException:
1801
                    exc_info = sys.exc_info()
1802
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
1803
            raise testtools.testcase._ExpectedFailure(exc_info)
1804
        finally:
1805
            del exc_info
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1806
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1807
    def _suppress_log(self):
1808
        """Remove the log info from details."""
1809
        self.discardDetail('log')
1810
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1811
    def _do_skip(self, result, reason):
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1812
        self._suppress_log()
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1813
        addSkip = getattr(result, 'addSkip', None)
1814
        if not callable(addSkip):
4780.1.1 by Robert Collins
Make addUnsupported more compatible with other TestResults.
1815
            result.addSuccess(result)
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1816
        else:
6765.1.2 by Jelmer Vernooij
Fix compatibility.
1817
            addSkip(self, str(reason))
4063.1.1 by Robert Collins
Move skipped test detection to TestCase, and make reporting use an addSkip method as per testtools.
1818
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).
1819
    @staticmethod
1820
    def _do_known_failure(self, result, e):
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1821
        self._suppress_log()
4780.1.4 by Robert Collins
Switch reporting of KnownFailure to be Python2.7 compatible.
1822
        err = sys.exc_info()
1823
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1824
        if addExpectedFailure is not None:
1825
            addExpectedFailure(self, err)
1826
        else:
1827
            result.addSuccess(self)
1828
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).
1829
    @staticmethod
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
1830
    def _do_not_applicable(self, result, e):
4780.1.5 by Robert Collins
Fix fallback of NotApplicable to Skip.
1831
        if not e.args:
1832
            reason = 'No reason given'
1833
        else:
1834
            reason = e.args[0]
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1835
        self._suppress_log ()
4780.1.3 by Robert Collins
TestNotApplicable handling improved for compatibility with stdlib TestResult objects.
1836
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1837
        if addNotApplicable is not None:
1838
            result.addNotApplicable(self, reason)
1839
        else:
1840
            self._do_skip(result, reason)
1841
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).
1842
    @staticmethod
5387.2.4 by John Arbash Meinel
Add tests for when we should and shouldn't get a 'log' in the details.
1843
    def _report_skip(self, result, err):
1844
        """Override the default _report_skip.
1845
1846
        We want to strip the 'log' detail. If we waint until _do_skip, it has
1847
        already been formatted into the 'reason' string, and we can't pull it
1848
        out again.
1849
        """
1850
        self._suppress_log()
1851
        super(TestCase, self)._report_skip(self, result, err)
1852
1853
    @staticmethod
1854
    def _report_expected_failure(self, result, err):
1855
        """Strip the log.
1856
1857
        See _report_skip for motivation.
1858
        """
1859
        self._suppress_log()
1860
        super(TestCase, self)._report_expected_failure(self, result, err)
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1861
1862
    @staticmethod
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).
1863
    def _do_unsupported_or_skip(self, result, e):
1864
        reason = e.args[0]
5387.2.1 by John Arbash Meinel
Filter out the 'log' information for skipped, xfail, and n/a.
1865
        self._suppress_log()
4780.1.1 by Robert Collins
Make addUnsupported more compatible with other TestResults.
1866
        addNotSupported = getattr(result, 'addNotSupported', None)
1867
        if addNotSupported is not None:
1868
            result.addNotSupported(self, reason)
1869
        else:
1870
            self._do_skip(result, reason)
1871
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)
1872
    def time(self, callable, *args, **kwargs):
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1873
        """Run callable and accrue the time it takes to the benchmark time.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1874
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1875
        If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1876
        this will cause lsprofile statistics to be gathered and stored in
1877
        self._benchcalls.
1878
        """
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)
1879
        if self._benchtime is None:
6724.1.1 by Martin
Make adding numbers to test details work on Python 3
1880
            self.addDetail('benchtime', content.Content(content.UTF8_TEXT,
1881
                lambda:[str(self._benchtime).encode('utf-8')]))
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)
1882
            self._benchtime = 0
1883
        start = time.time()
1884
        try:
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1885
            if not self._gather_lsprof_in_benchmarks:
1886
                return callable(*args, **kwargs)
1887
            else:
1888
                # record this benchmark
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1889
                ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1890
                stats.sort()
1891
                self._benchcalls.append(((callable, args, kwargs), stats))
1892
                return ret
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)
1893
        finally:
1894
            self._benchtime += time.time() - start
1895
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1896
    def log(self, *args):
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
1897
        trace.mutter(*args)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1898
4794.1.15 by Robert Collins
Review feedback.
1899
    def get_log(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1900
        """Get a unicode string containing the log from breezy.trace.
4794.1.15 by Robert Collins
Review feedback.
1901
1902
        Undecodable characters are replaced.
1903
        """
1904
        return u"".join(self.getDetails()['log'].iter_text())
1905
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1906
    def requireFeature(self, feature):
1907
        """This test requires a specific feature is available.
1908
1909
        :raises UnavailableFeature: When feature is not available.
1910
        """
1911
        if not feature.available():
1912
            raise UnavailableFeature(feature)
1913
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1914
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1915
            working_dir):
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1916
        """Run bazaar command line, splitting up a string command line."""
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1917
        if isinstance(args, string_types):
1918
            args = shlex.split(args)
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1919
        return self._run_bzr_core(args, retcode=retcode,
1920
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1921
                )
1922
1923
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1924
            working_dir):
4634.90.2 by Andrew Bennetts
Clear chk_map page cache in TestCase._run_bzr_core, causes blackbox.test_log to fail without fix in previous revision.
1925
        # Clear chk_map page cache, because the contents are likely to mask
1926
        # locking errors.
1927
        chk_map.clear_cache()
1185.85.8 by John Arbash Meinel
Adding wrapper for sys.stdout so we can set the output encoding. Adding tests that 'bzr log' handles multiple encodings properly
1928
        if encoding is None:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1929
            encoding = osutils.get_user_encoding()
1185.85.8 by John Arbash Meinel
Adding wrapper for sys.stdout so we can set the output encoding. Adding tests that 'bzr log' handles multiple encodings properly
1930
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
1931
        self.log('run brz: %r', args)
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
1932
1933
        stdout = ui_testing.BytesIOWithEncoding()
1934
        stderr = ui_testing.BytesIOWithEncoding()
1935
        stdout.encoding = stderr.encoding = encoding
1936
1185.43.5 by Martin Pool
Update log message quoting
1937
        # FIXME: don't call into logging here
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
1938
        handler = trace.EncodedStreamHandler(
1939
            stderr, errors="replace", level=logging.INFO)
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
1940
        logger = logging.getLogger('')
1941
        logger.addHandler(handler)
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
1942
1943
        self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
1944
        self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
1945
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
1946
        old_ui_factory = ui.ui_factory
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
1947
        ui.ui_factory = ui_testing.TestUIFactory(
1948
            stdin=stdin,
1949
            stdout=self._last_cmd_stdout,
1950
            stderr=self._last_cmd_stderr)
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
1951
1952
        cwd = None
1953
        if working_dir is not None:
1954
            cwd = osutils.getcwd()
1955
            os.chdir(working_dir)
1956
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
1957
        try:
6910.3.1 by Martin
Delay stream wrapping and fix choose in char based mode
1958
            with ui.ui_factory:
1959
                result = self.apply_redirected(
1960
                    ui.ui_factory.stdin,
1961
                    stdout, stderr,
1962
                    _mod_commands.run_bzr_catch_user_errors,
1963
                    args)
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
1964
        finally:
1965
            logger.removeHandler(handler)
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
1966
            ui.ui_factory = old_ui_factory
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
1967
            if cwd is not None:
1968
                os.chdir(cwd)
1685.1.69 by Wouter van Heyst
merge bzr.dev 1740
1969
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1970
        out = stdout.getvalue()
1971
        err = stderr.getvalue()
1972
        if out:
1185.85.72 by John Arbash Meinel
Fix some of the tests.
1973
            self.log('output:\n%r', out)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1974
        if err:
1185.85.72 by John Arbash Meinel
Fix some of the tests.
1975
            self.log('errors:\n%r', err)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1976
        if retcode is not None:
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1977
            self.assertEqual(retcode, result,
2292.1.32 by Marius Kruger
* tests/__init__.run_bzr
1978
                              message='Unexpected return code')
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
1979
        return result, out, err
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1980
6621.22.1 by Martin
Refactor bzrlib.ui to be based on unicode streams
1981
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
1982
                working_dir=None, error_regexes=[]):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1983
        """Invoke brz, as if it were run from the command line.
1119 by Martin Pool
doc
1984
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1985
        The argument list should not include the brz program name - the
1986
        first argument is normally the brz command.  Arguments may be
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1987
        passed in three ways:
1988
1989
        1- A list of strings, eg ["commit", "a"].  This is recommended
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1990
        when the command contains whitespace or metacharacters, or
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1991
        is built up at run time.
1992
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1993
        2- A single string, eg "add a".  This is the most convenient
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1994
        for hardcoded commands.
1995
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1996
        This runs brz through the interface that catches and reports
2530.3.4 by Martin Pool
Deprecate run_bzr_captured in favour of just run_bzr
1997
        errors, and with logging set to something approximating the
1998
        default, so that error reporting can be checked.
1999
1119 by Martin Pool
doc
2000
        This should be the main method for tests that want to exercise the
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2001
        overall behavior of the brz application (rather than a unit test
1119 by Martin Pool
doc
2002
        or a functional test of the library.)
2003
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
2004
        This sends the stdout/stderr results into the test's log,
2005
        where it may be useful for debugging.  See also run_captured.
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
2006
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2007
        :keyword stdin: A string to be used as stdin for the command.
2399.1.17 by John Arbash Meinel
[merge] bzr.dev 2562
2008
        :keyword retcode: The status code the command should return;
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
2009
            default 0.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2010
        :keyword working_dir: The directory to run the command in
2399.1.17 by John Arbash Meinel
[merge] bzr.dev 2562
2011
        :keyword error_regexes: A list of expected error messages.  If
2012
            specified they must be seen in the error output of the command.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2013
        """
4665.5.15 by Vincent Ladeuil
Catch the retcode for all commands.
2014
        retcode, out, err = self._run_bzr_autosplit(
2830.2.5 by Martin Pool
Deprecated ``run_bzr_decode``; use the new ``output_encoding`` parameter to
2015
            args=args,
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
2016
            retcode=retcode,
2830.2.5 by Martin Pool
Deprecated ``run_bzr_decode``; use the new ``output_encoding`` parameter to
2017
            encoding=encoding,
2018
            stdin=stdin,
2019
            working_dir=working_dir,
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
2020
            )
4325.4.6 by Vincent Ladeuil
Fixed as per John's and Markus reviews.
2021
        self.assertIsInstance(error_regexes, (list, tuple))
2292.1.27 by Marius Kruger
* tests/__init__.TestCase.run_bzr_captured
2022
        for regex in error_regexes:
2023
            self.assertContainsRe(err, regex)
2024
        return out, err
2025
1711.2.70 by John Arbash Meinel
Add run_bzr_errors alongside run_bzr, to make it easy to check the right error is occurring.
2026
    def run_bzr_error(self, error_regexes, *args, **kwargs):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2027
        """Run brz, and check that stderr contains the supplied regexes
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2028
2029
        :param error_regexes: Sequence of regular expressions which
1711.7.11 by John Arbash Meinel
Clean up the documentation for run_bzr_error on Martin's suggestion.
2030
            must each be found in the error output. The relative ordering
2031
            is not enforced.
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2032
        :param args: command-line arguments for brz
2033
        :param kwargs: Keyword arguments which are interpreted by run_brz
1711.7.11 by John Arbash Meinel
Clean up the documentation for run_bzr_error on Martin's suggestion.
2034
            This function changes the default value of retcode to be 3,
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2035
            since in most cases this is run when you expect brz to fail.
2581.1.1 by Martin Pool
Merge more runbzr cleanups
2036
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2037
        :return: (out, err) The actual output of running the command (in case
2038
            you want to do more inspection)
2039
2040
        Examples of use::
2041
1711.7.11 by John Arbash Meinel
Clean up the documentation for run_bzr_error on Martin's suggestion.
2042
            # Make sure that commit is failing because there is nothing to do
2043
            self.run_bzr_error(['no changes to commit'],
2665.1.1 by Michael Hudson
make run_bzr stricter about the keyword arguments it takes.
2044
                               ['commit', '-m', 'my commit comment'])
1711.7.11 by John Arbash Meinel
Clean up the documentation for run_bzr_error on Martin's suggestion.
2045
            # Make sure --strict is handling an unknown file, rather than
2046
            # giving us the 'nothing to do' error
2047
            self.build_tree(['unknown'])
2048
            self.run_bzr_error(['Commit refused because there are unknown files'],
2665.1.1 by Michael Hudson
make run_bzr stricter about the keyword arguments it takes.
2049
                               ['commit', --strict', '-m', 'my commit comment'])
1711.2.71 by John Arbash Meinel
Default to retcode=3, and add a test for run_bzr_error
2050
        """
2051
        kwargs.setdefault('retcode', 3)
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
2052
        kwargs['error_regexes'] = error_regexes
2053
        out, err = self.run_bzr(*args, **kwargs)
1711.2.71 by John Arbash Meinel
Default to retcode=3, and add a test for run_bzr_error
2054
        return out, err
1711.2.70 by John Arbash Meinel
Add run_bzr_errors alongside run_bzr, to make it easy to check the right error is occurring.
2055
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
2056
    def run_bzr_subprocess(self, *args, **kwargs):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2057
        """Run brz in a subprocess for testing.
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
2058
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2059
        This starts a new Python interpreter and runs brz in there.
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
2060
        This should only be used for tests that have a justifiable need for
2061
        this isolation: e.g. they are testing startup time, or signal
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2062
        handling, or early startup code, etc.  Subprocess code can't be
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
2063
        profiled or debugged so easily.
1752.1.7 by Aaron Bentley
Stop using shlex in run_bzr_subprocess
2064
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2065
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
2066
            None is supplied, the status code is not checked.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2067
        :keyword env_changes: A dictionary which lists changes to environment
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
2068
            variables. A value of None will unset the env variable.
2069
            The values must be strings. The change will only occur in the
2070
            child, so you don't need to fix the environment after running.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2071
        :keyword universal_newlines: Convert CRLF => LF
2072
        :keyword allow_plugins: By default the subprocess is run with
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2073
            --no-plugins to ensure test reproducibility. Also, it is possible
2067.2.2 by John Arbash Meinel
Review comments from Robert
2074
            for system-wide plugins to create unexpected output on stderr,
2075
            which can cause unnecessary test failures.
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
2076
        """
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
2077
        env_changes = kwargs.get('env_changes', {})
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
2078
        working_dir = kwargs.get('working_dir', None)
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2079
        allow_plugins = kwargs.get('allow_plugins', False)
2665.4.1 by Aaron Bentley
teach run_bzr_subprocess to accept either a list of strings or a string
2080
        if len(args) == 1:
2081
            if isinstance(args[0], list):
2082
                args = args[0]
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2083
            elif isinstance(args[0], (str, text_type)):
2665.4.1 by Aaron Bentley
teach run_bzr_subprocess to accept either a list of strings or a string
2084
                args = list(shlex.split(args[0]))
2085
        else:
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
2086
            raise ValueError("passing varargs to run_bzr_subprocess")
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
2087
        process = self.start_bzr_subprocess(args, env_changes=env_changes,
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2088
                                            working_dir=working_dir,
2089
                                            allow_plugins=allow_plugins)
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2090
        # We distinguish between retcode=None and retcode not passed.
2091
        supplied_retcode = kwargs.get('retcode', 0)
2092
        return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
2093
            universal_newlines=kwargs.get('universal_newlines', False),
2094
            process_args=args)
2095
1910.17.9 by Andrew Bennetts
Add skip_if_plan_to_signal flag to start_bzr_subprocess.
2096
    def start_bzr_subprocess(self, process_args, env_changes=None,
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
2097
                             skip_if_plan_to_signal=False,
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2098
                             working_dir=None,
5898.2.1 by Andrew Bennetts
Fix deadlock in TestImportTariffs.test_simple_serve.
2099
                             allow_plugins=False, stderr=subprocess.PIPE):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2100
        """Start brz in a subprocess for testing.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2101
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2102
        This starts a new Python interpreter and runs brz in there.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2103
        This should only be used for tests that have a justifiable need for
2104
        this isolation: e.g. they are testing startup time, or signal
2105
        handling, or early startup code, etc.  Subprocess code can't be
2106
        profiled or debugged so easily.
2107
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2108
        :param process_args: a list of arguments to pass to the brz executable,
2399.1.7 by John Arbash Meinel
Cleanup bzrlib/benchmarks/* so that everything at least has a valid doc string.
2109
            for example ``['--version']``.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2110
        :param env_changes: A dictionary which lists changes to environment
2111
            variables. A value of None will unset the env variable.
2112
            The values must be strings. The change will only occur in the
2113
            child, so you don't need to fix the environment after running.
5340.10.1 by Martin
Correct check on whether signalling subprocess is supported
2114
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
2115
            doesn't support signalling subprocesses.
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2116
        :param allow_plugins: If False (default) pass --no-plugins to brz.
5898.2.2 by Andrew Bennetts
Document new 'stderr' param of start_bzr_subprocess.
2117
        :param stderr: file to use for the subprocess's stderr.  Valid values
2118
            are those valid for the stderr argument of `subprocess.Popen`.
2119
            Default value is ``subprocess.PIPE``.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2120
2121
        :returns: Popen object for the started process.
2122
        """
1910.17.9 by Andrew Bennetts
Add skip_if_plan_to_signal flag to start_bzr_subprocess.
2123
        if skip_if_plan_to_signal:
5340.10.1 by Martin
Correct check on whether signalling subprocess is supported
2124
            if os.name != "posix":
2125
                raise TestSkipped("Sending signals not supported")
1910.17.9 by Andrew Bennetts
Add skip_if_plan_to_signal flag to start_bzr_subprocess.
2126
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2127
        if env_changes is None:
2128
            env_changes = {}
6331.4.1 by Martin Packman
Set before starting a test subprocess to compute the same sys.path
2129
        # Because $HOME is set to a tempdir for the context of a test, modules
2130
        # installed in the user dir will not be found unless $PYTHONUSERBASE
2131
        # gets set to the computed directory of this parent process.
2132
        if site.USER_BASE is not None:
2133
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
2134
        old_env = {}
2135
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
2136
        def cleanup_environment():
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2137
            for env_var, value in env_changes.items():
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
2138
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
2139
2140
        def restore_environment():
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2141
            for env_var, value in old_env.items():
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
2142
                osutils.set_or_unset_env(env_var, value)
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
2143
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
2144
        bzr_path = self.get_brz_path()
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
2145
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
2146
        cwd = None
2147
        if working_dir is not None:
2148
            cwd = osutils.getcwd()
2149
            os.chdir(working_dir)
2150
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
2151
        try:
2152
            # win32 subprocess doesn't support preexec_fn
2153
            # so we will avoid using it on all platforms, just to
2154
            # make sure the code path is used, and we don't break on win32
2155
            cleanup_environment()
5923.2.3 by Andrew Bennetts
Make a nice helper method rather than using a closure, cope better with multiple subprocesses, and add a release-notes entry.
2156
            # Include the subprocess's log file in the test details, in case
2157
            # the test fails due to an error in the subprocess.
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
2158
            self._add_subprocess_log(trace._get_brz_log_filename())
3616.2.1 by Mark Hammond
Fix how blackbox tests start bzr from frozen executables.
2159
            command = [sys.executable]
2160
            # frozen executables don't need the path to bzr
3616.2.7 by Mark Hammond
prefer getattr() over hasattr()
2161
            if getattr(sys, "frozen", None) is None:
3616.2.1 by Mark Hammond
Fix how blackbox tests start bzr from frozen executables.
2162
                command.append(bzr_path)
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2163
            if not allow_plugins:
2164
                command.append('--no-plugins')
2165
            command.extend(process_args)
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
2166
            process = self._popen(command, stdin=subprocess.PIPE,
2167
                                  stdout=subprocess.PIPE,
5898.2.1 by Andrew Bennetts
Fix deadlock in TestImportTariffs.test_simple_serve.
2168
                                  stderr=stderr)
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
2169
        finally:
2170
            restore_environment()
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
2171
            if cwd is not None:
2172
                os.chdir(cwd)
2173
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
2174
        return process
2175
5923.2.3 by Andrew Bennetts
Make a nice helper method rather than using a closure, cope better with multiple subprocesses, and add a release-notes entry.
2176
    def _add_subprocess_log(self, log_file_path):
2177
        if len(self._log_files) == 0:
2178
            # Register an addCleanup func.  We do this on the first call to
2179
            # _add_subprocess_log rather than in TestCase.setUp so that this
2180
            # addCleanup is registered after any cleanups for tempdirs that
2181
            # subclasses might create, which will probably remove the log file
2182
            # we want to read.
2183
            self.addCleanup(self._subprocess_log_cleanup)
2184
        # self._log_files is a set, so if a log file is reused we won't grab it
2185
        # twice.
2186
        self._log_files.add(log_file_path)
2187
2188
    def _subprocess_log_cleanup(self):
2189
        for count, log_file_path in enumerate(self._log_files):
2190
            # We use buffer_now=True to avoid holding the file open beyond
2191
            # the life of this function, which might interfere with e.g.
2192
            # cleaning tempdirs on Windows.
5923.2.5 by Andrew Bennetts
testtools 0.9.5 doesn't have content_from_file, so do it by hand.
2193
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
2194
            #detail_content = content.content_from_file(
2195
            #    log_file_path, buffer_now=True)
2196
            with open(log_file_path, 'rb') as log_file:
2197
                log_file_bytes = log_file.read()
2198
            detail_content = content.Content(content.ContentType("text",
2199
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
5923.2.3 by Andrew Bennetts
Make a nice helper method rather than using a closure, cope better with multiple subprocesses, and add a release-notes entry.
2200
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
5923.2.5 by Andrew Bennetts
testtools 0.9.5 doesn't have content_from_file, so do it by hand.
2201
                detail_content)
5923.2.3 by Andrew Bennetts
Make a nice helper method rather than using a closure, cope better with multiple subprocesses, and add a release-notes entry.
2202
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2203
    def _popen(self, *args, **kwargs):
2204
        """Place a call to Popen.
2067.2.2 by John Arbash Meinel
Review comments from Robert
2205
2206
        Allows tests to override this method to intercept the calls made to
2207
        Popen for introspection.
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2208
        """
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
2209
        return subprocess.Popen(*args, **kwargs)
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
2210
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.
2211
    def get_source_path(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2212
        """Return the path of the directory containing breezy."""
2213
        return os.path.dirname(os.path.dirname(breezy.__file__))
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.
2214
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
2215
    def get_brz_path(self):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2216
        """Return the path of the 'brz' executable for this test suite."""
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
2217
        brz_path = os.path.join(self.get_source_path(), "brz")
2218
        if not os.path.isfile(brz_path):
2018.1.1 by Andrew Bennetts
Make bzr+ssh:// actually work (at least with absolute paths).
2219
            # We are probably installed. Assume sys.argv is the right file
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
2220
            brz_path = sys.argv[0]
2221
        return brz_path
2018.1.1 by Andrew Bennetts
Make bzr+ssh:// actually work (at least with absolute paths).
2222
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2223
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2224
                              universal_newlines=False, process_args=None):
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
2225
        """Finish the execution of process.
2226
2227
        :param process: the Popen object returned from start_bzr_subprocess.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2228
        :param retcode: The status code that is expected.  Defaults to 0.  If
2229
            None is supplied, the status code is not checked.
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
2230
        :param send_signal: an optional signal to send to the process.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2231
        :param universal_newlines: Convert CRLF => LF
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
2232
        :returns: (stdout, stderr)
2233
        """
2234
        if send_signal is not None:
2235
            os.kill(process.pid, send_signal)
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2236
        out, err = process.communicate()
2237
2238
        if universal_newlines:
2239
            out = out.replace('\r\n', '\n')
2240
            err = err.replace('\r\n', '\n')
2241
2242
        if retcode is not None and retcode != process.returncode:
2243
            if process_args is None:
2244
                process_args = "(unknown args)"
6690.4.1 by Martin
Fix test trace so test_utf8_default_fs_enc fails cleaner
2245
            trace.mutter('Output of brz %r:\n%s', process_args, out)
2246
            trace.mutter('Error for brz %r:\n%s', process_args, err)
2247
            self.fail('Command brz %r failed with retcode %d != %d'
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
2248
                      % (process_args, retcode, process.returncode))
2249
        return [out, err]
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
2250
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
2251
    def check_tree_shape(self, tree, shape):
2252
        """Compare a tree to a list of expected names.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2253
2254
        Fail if they are not precisely equal.
2255
        """
2256
        extras = []
2257
        shape = list(shape)             # copy
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
2258
        for path, ie in tree.iter_entries_by_dir():
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2259
            name = path.replace('\\', '/')
2545.3.1 by James Westby
Fix detection of directory entries in the inventory.
2260
            if ie.kind == 'directory':
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2261
                name = name + '/'
5807.1.8 by Jelmer Vernooij
Fix some tests.
2262
            if name == "/":
2263
                pass # ignore root entry
2264
            elif name in shape:
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2265
                shape.remove(name)
2266
            else:
2267
                extras.append(name)
2268
        if shape:
2269
            self.fail("expected paths not found in inventory: %r" % shape)
2270
        if extras:
2271
            self.fail("unexpected paths found in inventory: %r" % extras)
2272
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
2273
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2274
                         a_callable=None, *args, **kwargs):
2275
        """Call callable with redirected std io pipes.
2276
2277
        Returns the return code."""
2278
        if not callable(a_callable):
2279
            raise ValueError("a_callable must be callable.")
2280
        if stdin is None:
6695.1.1 by Martin
Make ui package pass tests on Python 3
2281
            stdin = BytesIO(b"")
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
2282
        if stdout is None:
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
2283
            if getattr(self, "_log_file", None) is not None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
2284
                stdout = self._log_file
2285
            else:
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2286
                stdout = BytesIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
2287
        if stderr is None:
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
2288
            if getattr(self, "_log_file", None is not None):
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
2289
                stderr = self._log_file
2290
            else:
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2291
                stderr = BytesIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
2292
        real_stdin = sys.stdin
2293
        real_stdout = sys.stdout
2294
        real_stderr = sys.stderr
2295
        try:
2296
            sys.stdout = stdout
2297
            sys.stderr = stderr
2298
            sys.stdin = stdin
1160 by Martin Pool
- tiny refactoring
2299
            return a_callable(*args, **kwargs)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
2300
        finally:
2301
            sys.stdout = real_stdout
2302
            sys.stderr = real_stderr
2303
            sys.stdin = real_stdin
2304
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2305
    def reduceLockdirTimeout(self):
2306
        """Reduce the default lock timeout for the duration of the test, so that
2307
        if LockContention occurs during a test, it does so quickly.
2308
2309
        Tests that expect to provoke LockContention errors should call this.
2310
        """
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
2311
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
2312
2717.1.1 by Lukáš Lalinsky
Use UTF-8 encoded StringIO for log tests to avoid failures on non-ASCII committer names.
2313
    def make_utf8_encoded_stringio(self, encoding_type=None):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2314
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
2717.1.1 by Lukáš Lalinsky
Use UTF-8 encoded StringIO for log tests to avoid failures on non-ASCII committer names.
2315
        if encoding_type is None:
2316
            encoding_type = 'strict'
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2317
        bio = BytesIO()
2717.1.1 by Lukáš Lalinsky
Use UTF-8 encoded StringIO for log tests to avoid failures on non-ASCII committer names.
2318
        output_encoding = 'utf-8'
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2319
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
2717.1.1 by Lukáš Lalinsky
Use UTF-8 encoded StringIO for log tests to avoid failures on non-ASCII committer names.
2320
        sio.encoding = output_encoding
2321
        return sio
2322
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2323
    def disable_verb(self, verb):
2324
        """Disable a smart server verb for one test."""
6670.4.16 by Jelmer Vernooij
Move smart to breezy.bzr.
2325
        from breezy.bzr.smart import request
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2326
        request_handlers = request.request_handlers
2327
        orig_method = request_handlers.get(verb)
6206.1.11 by Jelmer Vernooij
Preserve info when restoring verbs after disabling/overriding.
2328
        orig_info = request_handlers.get_info(verb)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2329
        request_handlers.remove(verb)
6206.1.11 by Jelmer Vernooij
Preserve info when restoring verbs after disabling/overriding.
2330
        self.addCleanup(request_handlers.register, verb, orig_method,
2331
            info=orig_info)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2332
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2333
    def __hash__(self):
2334
        return id(self)
2335
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2336
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
2337
class CapturedCall(object):
2338
    """A helper for capturing smart server calls for easy debug analysis."""
2339
2340
    def __init__(self, params, prefix_length):
2341
        """Capture the call with params and skip prefix_length stack frames."""
2342
        self.call = params
2343
        import traceback
2344
        # The last 5 frames are the __init__, the hook frame, and 3 smart
2345
        # client frames. Beyond this we could get more clever, but this is good
2346
        # enough for now.
2347
        stack = traceback.extract_stack()[prefix_length:-5]
2348
        self.stack = ''.join(traceback.format_list(stack))
2349
2350
    def __str__(self):
2351
        return self.call.method
2352
2353
    def __repr__(self):
2354
        return self.call.method
2355
2356
    def stack(self):
2357
        return self.stack
2358
2359
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2360
class TestCaseWithMemoryTransport(TestCase):
2361
    """Common test class for tests that do not need disk resources.
2362
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
2363
    Tests that need disk resources should derive from TestCaseInTempDir
2364
    orTestCaseWithTransport.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2365
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2366
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2367
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
2368
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2369
    a directory which does not exist. This serves to help ensure test isolation
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
2370
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
2371
    must exist. However, TestCaseWithMemoryTransport does not offer local file
2372
    defaults for the transport in tests, nor does it obey the command line
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2373
    override, so tests that accidentally write to the common directory should
2374
    be rare.
2485.6.6 by Martin Pool
Put test root directory (containing per-test directories) in TMPDIR
2375
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
2376
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
2377
        ``.bzr`` directory that stops us ascending higher into the filesystem.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2378
    """
2379
2380
    TEST_ROOT = None
2381
    _TEST_NAME = 'test'
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2382
1986.2.5 by Robert Collins
Unbreak transport tests.
2383
    def __init__(self, methodName='runTest'):
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
2384
        # allow test parameterization after test construction and before test
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2385
        # execution. Variables that the parameterizer sets need to be
1986.2.5 by Robert Collins
Unbreak transport tests.
2386
        # ones that are not set by setUp, or setUp will trash them.
2387
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2388
        self.vfs_transport_factory = default_transport
2389
        self.transport_server = None
1986.2.5 by Robert Collins
Unbreak transport tests.
2390
        self.transport_readonly_server = None
2018.5.44 by Andrew Bennetts
Small changes to help a couple more tests pass.
2391
        self.__vfs_server = None
1986.2.5 by Robert Collins
Unbreak transport tests.
2392
6499.3.9 by Vincent Ladeuil
Provide fresh config stores for tests.
2393
    def setUp(self):
2394
        super(TestCaseWithMemoryTransport, self).setUp()
2395
2396
        def _add_disconnect_cleanup(transport):
2397
            """Schedule disconnection of given transport at test cleanup
2398
2399
            This needs to happen for all connected transports or leaks occur.
2400
2401
            Note reconnections may mean we call disconnect multiple times per
2402
            transport which is suboptimal but seems harmless.
2403
            """
2404
            self.addCleanup(transport.disconnect)
2405
2406
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
2407
            _add_disconnect_cleanup, None)
2408
2409
        self._make_test_root()
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
2410
        self.addCleanup(os.chdir, osutils.getcwd())
6499.3.9 by Vincent Ladeuil
Provide fresh config stores for tests.
2411
        self.makeAndChdirToTestDir()
2412
        self.overrideEnvironmentForTesting()
2413
        self.__readonly_server = None
2414
        self.__server = None
2415
        self.reduceLockdirTimeout()
2416
        # Each test may use its own config files even if the local config files
2417
        # don't actually exist. They'll rightly fail if they try to create them
2418
        # though.
2419
        self.overrideAttr(config, '_shared_stores', {})
2420
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
2421
    def get_transport(self, relpath=None):
2422
        """Return a writeable transport.
2423
2424
        This transport is for the test scratch space relative to
2592.2.5 by Jonathan Lange
Make UnicodeFilename feature less insane. Add a simple test for it too.
2425
        "self._test_root"
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2426
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
2427
        :param relpath: a path relative to the base url.
2428
        """
6039.1.5 by Jelmer Vernooij
Add get_transport_from_url and get_transport_from_path functions.
2429
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2430
        self.assertFalse(t.is_readonly())
2431
        return t
2432
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
2433
    def get_readonly_transport(self, relpath=None):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2434
        """Return a readonly transport for the test scratch space
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2435
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2436
        This can be used to test that operations which should only need
2437
        readonly access in fact do not try to write.
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
2438
2439
        :param relpath: a path relative to the base url.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2440
        """
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
2441
        t = _mod_transport.get_transport_from_url(
2442
            self.get_readonly_url(relpath))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2443
        self.assertTrue(t.is_readonly())
2444
        return t
2445
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
2446
    def create_transport_readonly_server(self):
2447
        """Create a transport server from class defined at init.
2448
2145.1.1 by mbp at sourcefrog
merge urllib keepalive etc
2449
        This is mostly a hook for daughter classes.
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
2450
        """
2451
        return self.transport_readonly_server()
2452
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2453
    def get_readonly_server(self):
2454
        """Get the server instance for the readonly transport
2455
2456
        This is useful for some tests with specific servers to do diagnostics.
2457
        """
2458
        if self.__readonly_server is None:
2459
            if self.transport_readonly_server is None:
2460
                # readonly decorator requested
5017.3.23 by Vincent Ladeuil
selftest -s bt.test_bzrdir passing
2461
                self.__readonly_server = test_server.ReadonlyServer()
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2462
            else:
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2463
                # explicit readonly transport.
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
2464
                self.__readonly_server = self.create_transport_readonly_server()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2465
            self.start_server(self.__readonly_server,
2466
                self.get_vfs_only_server())
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2467
        return self.__readonly_server
2468
2469
    def get_readonly_url(self, relpath=None):
2470
        """Get a URL for the readonly transport.
2471
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2472
        This will either be backed by '.' or a decorator to the transport
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2473
        used by self.get_url()
2474
        relpath provides for clients to get a path relative to the base url.
2475
        These should only be downwards relative, not upwards.
2476
        """
2477
        base = self.get_readonly_server().get_url()
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
2478
        return self._adjust_url(base, relpath)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2479
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2480
    def get_vfs_only_server(self):
2018.5.44 by Andrew Bennetts
Small changes to help a couple more tests pass.
2481
        """Get the vfs only read/write server instance.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2482
2483
        This is useful for some tests with specific servers that need
2484
        diagnostics.
2485
2486
        For TestCaseWithMemoryTransport this is always a MemoryServer, and there
2487
        is no means to override it.
2488
        """
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2489
        if self.__vfs_server is None:
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.
2490
            self.__vfs_server = memory.MemoryServer()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2491
            self.start_server(self.__vfs_server)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2492
        return self.__vfs_server
2493
2494
    def get_server(self):
2495
        """Get the read/write server instance.
2496
2497
        This is useful for some tests with specific servers that need
2498
        diagnostics.
2499
2500
        This is built from the self.transport_server factory. If that is None,
2501
        then the self.get_vfs_server is returned.
2502
        """
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2503
        if self.__server is None:
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2504
            if (self.transport_server is None or self.transport_server is
2505
                self.vfs_transport_factory):
2506
                self.__server = self.get_vfs_only_server()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2507
            else:
2508
                # bring up a decorated means of access to the vfs only server.
2509
                self.__server = self.transport_server()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2510
                self.start_server(self.__server, self.get_vfs_only_server())
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2511
        return self.__server
2512
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2513
    def _adjust_url(self, base, relpath):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2514
        """Get a URL (or maybe a path) for the readwrite transport.
2515
2516
        This will either be backed by '.' or to an equivalent non-file based
2517
        facility.
2518
        relpath provides for clients to get a path relative to the base url.
2519
        These should only be downwards relative, not upwards.
2520
        """
2521
        if relpath is not None and relpath != '.':
2522
            if not base.endswith('/'):
2523
                base = base + '/'
2524
            # XXX: Really base should be a url; we did after all call
2525
            # get_url()!  But sometimes it's just a path (from
2526
            # LocalAbspathServer), and it'd be wrong to append urlescaped data
2527
            # to a non-escaped local path.
2528
            if base.startswith('./') or base.startswith('/'):
2529
                base += relpath
2530
            else:
2531
                base += urlutils.escape(relpath)
2532
        return base
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2533
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2534
    def get_url(self, relpath=None):
2535
        """Get a URL (or maybe a path) for the readwrite transport.
2536
2537
        This will either be backed by '.' or to an equivalent non-file based
2538
        facility.
2539
        relpath provides for clients to get a path relative to the base url.
2540
        These should only be downwards relative, not upwards.
2541
        """
2542
        base = self.get_server().get_url()
2543
        return self._adjust_url(base, relpath)
2544
2545
    def get_vfs_only_url(self, relpath=None):
2546
        """Get a URL (or maybe a path for the plain old vfs transport.
2547
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2548
        This will never be a smart protocol.  It always has all the
2549
        capabilities of the local filesystem, but it might actually be a
2550
        MemoryTransport or some other similar virtual filesystem.
2551
2399.1.16 by John Arbash Meinel
[merge] bzr.dev 2466
2552
        This is the backing transport (if any) of the server returned by
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2553
        get_url and get_readonly_url.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2554
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2555
        :param relpath: provides for clients to get a path relative to the base
2556
            url.  These should only be downwards relative, not upwards.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2557
        :return: A URL
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2558
        """
2559
        base = self.get_vfs_only_server().get_url()
2560
        return self._adjust_url(base, relpath)
2561
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2562
    def _create_safety_net(self):
2563
        """Make a fake bzr directory.
2564
2875.1.1 by Vincent Ladeuil
Fix #147986 by monitoring a safety .bzr directory.
2565
        This prevents any tests propagating up onto the TEST_ROOT directory's
2566
        real branch.
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2567
        """
2568
        root = TestCaseWithMemoryTransport.TEST_ROOT
6551.1.1 by Vincent Ladeuil
Restore safety net home check lost some time ago.
2569
        try:
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
2570
            # Make sure we get a readable and accessible home for .brz.log
6551.1.1 by Vincent Ladeuil
Restore safety net home check lost some time ago.
2571
            # and/or config files, and not fallback to weird defaults (see
2572
            # http://pad.lv/825027).
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2573
            self.assertIs(None, os.environ.get('BRZ_HOME', None))
2574
            os.environ['BRZ_HOME'] = root
6551.1.1 by Vincent Ladeuil
Restore safety net home check lost some time ago.
2575
            wt = controldir.ControlDir.create_standalone_workingtree(root)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2576
            del os.environ['BRZ_HOME']
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2577
        except Exception as e:
6551.1.2 by Vincent Ladeuil
Fix typo.
2578
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
6017.1.1 by Andrew Bennetts
Quick hack to make _check_safety_net much faster: check raw bytes of the safety net's dirstate against the known pristine state, rather than using WorkingTree.open(root).last_revision().
2579
        # Hack for speed: remember the raw bytes of the dirstate file so that
2580
        # we don't need to re-open the wt to check it hasn't changed.
2581
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
2582
            wt.control_transport.get_bytes('dirstate'))
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2583
2584
    def _check_safety_net(self):
2585
        """Check that the safety .bzr directory have not been touched.
2586
2587
        _make_test_root have created a .bzr directory to prevent tests from
2588
        propagating. This method ensures than a test did not leaked.
2589
        """
2590
        root = TestCaseWithMemoryTransport.TEST_ROOT
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
2591
        t = _mod_transport.get_transport_from_path(root)
6017.1.1 by Andrew Bennetts
Quick hack to make _check_safety_net much faster: check raw bytes of the safety net's dirstate against the known pristine state, rather than using WorkingTree.open(root).last_revision().
2592
        self.permit_url(t.base)
2593
        if (t.get_bytes('.bzr/checkout/dirstate') != 
2594
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2595
            # The current test have modified the /bzr directory, we need to
2596
            # recreate a new one or all the followng tests will fail.
2597
            # If you need to inspect its content uncomment the following line
2598
            # import pdb; pdb.set_trace()
4807.3.3 by John Arbash Meinel
Report the test-id when we fail to delete a testing dir.
2599
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2600
            self._create_safety_net()
2601
            raise AssertionError('%s/.bzr should not be modified' % root)
2602
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2603
    def _make_test_root(self):
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2604
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4707.1.1 by Vincent Ladeuil
Fix OSX and FreeBSD failures.
2605
            # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
2606
            root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
2607
                                                    suffix='.tmp'))
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2608
            TestCaseWithMemoryTransport.TEST_ROOT = root
2609
2610
            self._create_safety_net()
2611
2612
            # The same directory is used by all tests, and we're not
2613
            # specifically told when all tests are finished.  This will do.
2614
            atexit.register(_rmtree_temp_dir, root)
2615
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.
2616
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
2617
        self.addCleanup(self._check_safety_net)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2618
2619
    def makeAndChdirToTestDir(self):
2620
        """Create a temporary directories for this one test.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2621
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2622
        This must set self.test_home_dir and self.test_dir and chdir to
2623
        self.test_dir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2624
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2625
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2626
        """
2627
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2628
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2629
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
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.
2630
        self.permit_dir(self.test_dir)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2631
6437.32.1 by Aaron Bentley
Use colocated branch names as nicknames.
2632
    def make_branch(self, relpath, format=None, name=None):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2633
        """Create a branch on the transport at relpath."""
2634
        repo = self.make_repository(relpath, format=format)
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
2635
        return repo.controldir.create_branch(append_revisions_only=False, name=name)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2636
6155.6.2 by Jelmer Vernooij
Simplify handling of default format.
2637
    def get_default_format(self):
2638
        return 'default'
2639
2640
    def resolve_format(self, format):
2641
        """Resolve an object to a ControlDir format object.
2642
2643
        The initial format object can either already be
2644
        a ControlDirFormat, None (for the default format),
2645
        or a string with the name of the control dir format.
2646
2647
        :param format: Object to resolve
2648
        :return A ControlDirFormat instance
2649
        """
2650
        if format is None:
2651
            format = self.get_default_format()
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
2652
        if isinstance(format, str):
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
2653
            format = controldir.format_registry.make_controldir(format)
6123.9.3 by Jelmer Vernooij
Factor out resolve_format method.
2654
        return format
2655
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
2656
    def make_controldir(self, relpath, format=None):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2657
        try:
2658
            # might be a relative or absolute path
2659
            maybe_a_url = self.get_url(relpath)
2660
            segments = maybe_a_url.rsplit('/', 1)
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
2661
            t = _mod_transport.get_transport(maybe_a_url)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2662
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
2663
                t.ensure_base()
6123.9.3 by Jelmer Vernooij
Factor out resolve_format method.
2664
            format = self.resolve_format(format)
5651.3.3 by Jelmer Vernooij
Remove pdb.
2665
            return format.initialize_on_transport(t)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2666
        except errors.UninitializableFormat:
2667
            raise TestSkipped("Format %s is not initializable." % format)
2668
6150.2.2 by Jelmer Vernooij
Make various make_repository methods default their shared setting to None.
2669
    def make_repository(self, relpath, shared=None, format=None):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2670
        """Create a repository on our default transport at relpath.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2671
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2672
        Note that relpath must be a relative path, not a full url.
2673
        """
2674
        # FIXME: If you create a remoterepository this returns the underlying
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2675
        # real format, which is incorrect.  Actually we should make sure that
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2676
        # RemoteBzrDir returns a RemoteRepository.
2677
        # maybe  mbp 20070410
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
2678
        made_control = self.make_controldir(relpath, format=format)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2679
        return made_control.create_repository(shared=shared)
2680
5215.3.8 by Marius Kruger
move make_smart_server back to TestCaseWithMemoryTransport from TestCaseWithTransport as per review
2681
    def make_smart_server(self, path, backing_server=None):
2682
        if backing_server is None:
2683
            backing_server = self.get_server()
2684
        smart_server = test_server.SmartTCPServer_for_testing()
2685
        self.start_server(smart_server, backing_server)
6039.1.5 by Jelmer Vernooij
Add get_transport_from_url and get_transport_from_path functions.
2686
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
2687
                                                   ).clone(path)
5215.3.8 by Marius Kruger
move make_smart_server back to TestCaseWithMemoryTransport from TestCaseWithTransport as per review
2688
        return remote_transport
2689
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
2690
    def make_branch_and_memory_tree(self, relpath, format=None):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2691
        """Create a branch on the default transport and a MemoryTree for it."""
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
2692
        b = self.make_branch(relpath, format=format)
6883.8.2 by Jelmer Vernooij
Use create_memorytree.
2693
        return b.create_memorytree()
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2694
4476.3.59 by Andrew Bennetts
Undo changes that aren't needed anymore.
2695
    def make_branch_builder(self, relpath, format=None):
4257.3.8 by Andrew Bennetts
Fix TestCase.make_branch_builder to make a branch in the specified format. Also add an interrepo test scenario for KnitPack1 -> KnitPack6RichRoot, which fails.
2696
        branch = self.make_branch(relpath, format=format)
4476.3.59 by Andrew Bennetts
Undo changes that aren't needed anymore.
2697
        return branchbuilder.BranchBuilder(branch=branch)
3567.4.12 by John Arbash Meinel
Expose the branch building framework to the test suite.
2698
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2699
    def overrideEnvironmentForTesting(self):
4815.2.2 by Michael Hudson
another approach
2700
        test_home_dir = self.test_home_dir
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
2701
        if not PY3 and isinstance(test_home_dir, text_type):
4815.2.2 by Michael Hudson
another approach
2702
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
2703
        self.overrideEnv('HOME', test_home_dir)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2704
        self.overrideEnv('BRZ_HOME', test_home_dir)
6770.2.5 by Jelmer Vernooij
Set GNUPGHOME in tests.
2705
        self.overrideEnv('GNUPGHOME', os.path.join(test_home_dir, '.gnupg'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2706
4017.2.1 by Robert Collins
Add BzrDirFormatMeta1 test for the amount of rpc calls made initializing over the network.
2707
    def setup_smart_server_with_call_log(self):
2708
        """Sets up a smart server as the transport server with a call log."""
5017.3.23 by Vincent Ladeuil
selftest -s bt.test_bzrdir passing
2709
        self.transport_server = test_server.SmartTCPServer_for_testing
6366.1.3 by Jelmer Vernooij
Support counting number of connections.
2710
        self.hpss_connections = []
4017.2.1 by Robert Collins
Add BzrDirFormatMeta1 test for the amount of rpc calls made initializing over the network.
2711
        self.hpss_calls = []
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
2712
        import traceback
2713
        # Skip the current stack down to the caller of
2714
        # setup_smart_server_with_call_log
2715
        prefix_length = len(traceback.extract_stack()) - 2
4017.2.1 by Robert Collins
Add BzrDirFormatMeta1 test for the amount of rpc calls made initializing over the network.
2716
        def capture_hpss_call(params):
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
2717
            self.hpss_calls.append(
2718
                CapturedCall(params, prefix_length))
6366.1.3 by Jelmer Vernooij
Support counting number of connections.
2719
        def capture_connect(transport):
2720
            self.hpss_connections.append(transport)
4017.2.1 by Robert Collins
Add BzrDirFormatMeta1 test for the amount of rpc calls made initializing over the network.
2721
        client._SmartClient.hooks.install_named_hook(
2722
            'call', capture_hpss_call, None)
6366.1.3 by Jelmer Vernooij
Support counting number of connections.
2723
        _mod_transport.Transport.hooks.install_named_hook(
2724
            'post_connect', capture_connect, None)
4017.2.1 by Robert Collins
Add BzrDirFormatMeta1 test for the amount of rpc calls made initializing over the network.
2725
2726
    def reset_smart_call_log(self):
2727
        self.hpss_calls = []
6366.1.3 by Jelmer Vernooij
Support counting number of connections.
2728
        self.hpss_connections = []
4017.2.1 by Robert Collins
Add BzrDirFormatMeta1 test for the amount of rpc calls made initializing over the network.
2729
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2730
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2731
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2732
    """Derived class that runs a test within a temporary directory.
2733
2734
    This is useful for tests that need to create a branch, etc.
2735
2736
    The directory is created in a slightly complex way: for each
2737
    Python invocation, a new temporary top-level directory is created.
2738
    All test cases create their own directory within that.  If the
2739
    tests complete successfully, the directory is removed.
2740
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2741
    :ivar test_base_dir: The path of the top-level directory for this
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2742
    test, which contains a home directory and a work directory.
2743
2744
    :ivar test_home_dir: An initially empty directory under test_base_dir
2745
    which is used as $HOME for this test.
2746
2747
    :ivar test_dir: A directory under test_base_dir used as the current
2748
    directory when the test proper is run.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2749
    """
2750
2751
    OVERRIDE_PYTHON = 'python'
2752
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
2753
    def setUp(self):
2754
        super(TestCaseInTempDir, self).setUp()
2755
        # Remove the protection set in isolated_environ, we have a proper
2756
        # access to disk resources now.
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2757
        self.overrideEnv('BRZ_LOG', None)
5984.1.4 by Vincent Ladeuil
Make the test framework more robust against BZR_LOG leaks.
2758
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2759
    def check_file_contents(self, filename, expect):
2760
        self.log("check contents of file %s" % filename)
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
2761
        with open(filename) as f:
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
2762
            contents = f.read()
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2763
        if contents != expect:
2764
            self.log("expected: %r" % expect)
2765
            self.log("actually: %r" % contents)
2766
            self.fail("contents of %s not as expected" % filename)
2767
3549.2.4 by Martin Pool
Rename _getTestDirPrefix not to look like a test
2768
    def _getTestDirPrefix(self):
3549.2.1 by Martin Pool
Use test names in the temporary directory name
2769
        # create a directory within the top level test directory
4615.3.1 by Martin
Extend work around for path length limitations in selftest to cygwin
2770
        if sys.platform in ('win32', 'cygwin'):
3549.2.1 by Martin Pool
Use test names in the temporary directory name
2771
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2772
            # windows is likely to have path-length limits so use a short name
2773
            name_prefix = name_prefix[-30:]
2774
        else:
2775
            name_prefix = re.sub('[/]', '_', self.id())
2776
        return name_prefix
2777
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2778
    def makeAndChdirToTestDir(self):
2779
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2780
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2781
        For TestCaseInTempDir we create a temporary directory based on the test
2782
        name and then create two subdirs - test and home under it.
2783
        """
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
2784
        name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2785
            self._getTestDirPrefix())
3549.2.1 by Martin Pool
Use test names in the temporary directory name
2786
        name = name_prefix
2787
        for i in range(100):
2788
            if os.path.exists(name):
2789
                name = name_prefix + '_' + str(i)
2790
            else:
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.
2791
                # now create test and home directories within this dir
2792
                self.test_base_dir = name
2793
                self.addCleanup(self.deleteTestDir)
2794
                os.mkdir(self.test_base_dir)
3549.2.1 by Martin Pool
Use test names in the temporary directory name
2795
                break
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.
2796
        self.permit_dir(self.test_base_dir)
2797
        # 'sprouting' and 'init' of a branch both walk up the tree to find
2798
        # stacking policy to honour; create a bzr dir with an unshared
2799
        # repository (but not a branch - our code would be trying to escape
2800
        # then!) to stop them, and permit it to be read.
6472.2.2 by Jelmer Vernooij
Use controldir rather than bzrdir in a couple more places.
2801
        # control = controldir.ControlDir.create(self.test_base_dir)
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.
2802
        # control.create_repository()
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2803
        self.test_home_dir = self.test_base_dir + '/home'
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2804
        os.mkdir(self.test_home_dir)
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2805
        self.test_dir = self.test_base_dir + '/work'
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2806
        os.mkdir(self.test_dir)
2807
        os.chdir(self.test_dir)
2808
        # put name of test inside
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
2809
        with open(self.test_base_dir + '/name', 'w') as f:
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2810
            f.write(self.id())
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2811
2812
    def deleteTestDir(self):
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
2813
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
4807.3.3 by John Arbash Meinel
Report the test-id when we fail to delete a testing dir.
2814
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2815
2193.2.1 by Alexander Belchenko
selftest: build tree for test with binary line-endings by default
2816
    def build_tree(self, shape, line_endings='binary', transport=None):
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2817
        """Build a test tree according to a pattern.
2818
2819
        shape is a sequence of file specifications.  If the final
2820
        character is '/', a directory is created.
2821
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
2822
        This assumes that all the elements in the tree being built are new.
2823
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2824
        This doesn't add anything to a branch.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2825
3034.4.8 by Alexander Belchenko
TestCaseInTempDir.build_tree now checks type of shape argument.
2826
        :type shape:    list or tuple.
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
2827
        :param line_endings: Either 'binary' or 'native'
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
2828
            in binary mode, exact contents are written in native mode, the
2829
            line endings match the default platform endings.
2830
        :param transport: A transport to write to, for building trees on VFS's.
2831
            If the transport is readonly or None, "." is opened automatically.
2832
        :return: None
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2833
        """
3044.1.1 by Martin Pool
Fix up calls to TestCase.build_tree passing a string rather than a list
2834
        if type(shape) not in (list, tuple):
2835
            raise AssertionError("Parameter 'shape' should be "
2836
                "a list or a tuple. Got %r instead" % (shape,))
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
2837
        # It's OK to just create them using forward slashes on windows.
1530.1.3 by Robert Collins
transport implementations now tested consistently.
2838
        if transport is None or transport.is_readonly():
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
2839
            transport = _mod_transport.get_transport_from_path(".")
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2840
        for name in shape:
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2841
            self.assertIsInstance(name, (str, text_type))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2842
            if name[-1] == '/':
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2843
                transport.mkdir(urlutils.escape(name[:-1]))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2844
            else:
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
2845
                if line_endings == 'binary':
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2846
                    end = b'\n'
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
2847
                elif line_endings == 'native':
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2848
                    end = os.linesep.encode('ascii')
1185.38.7 by John Arbash Meinel
Updated build_tree to use fixed line-endings for tests which read the file contents and compare
2849
                else:
2227.2.2 by v.ladeuil+lp at free
Cleanup.
2850
                    raise errors.BzrError(
2851
                        'Invalid line ending request %r' % line_endings)
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2852
                content = b"contents of %s%s" % (name.encode('utf-8'), end)
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
2853
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2854
5200.2.4 by Robert Collins
Review feedback.
2855
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2856
2655.2.5 by Marius Kruger
* Improve BzrRemoveChangedFilesError message.
2857
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2858
        """Assert whether path or paths are in the WorkingTree"""
2859
        if tree is None:
2860
            tree = workingtree.WorkingTree.open(root_path)
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2861
        if not isinstance(path, (str, text_type)):
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2862
            for p in path:
3585.2.1 by Robert Collins
Create acceptance test for bug 150438.
2863
                self.assertInWorkingTree(p, tree=tree)
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2864
        else:
6852.3.1 by Jelmer Vernooij
add Tree.is_versioned.
2865
            self.assertTrue(tree.is_versioned(path),
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2866
                path+' not in working tree.')
2867
2655.2.5 by Marius Kruger
* Improve BzrRemoveChangedFilesError message.
2868
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2869
        """Assert whether path or paths are not in the WorkingTree"""
2870
        if tree is None:
2871
            tree = workingtree.WorkingTree.open(root_path)
6695.3.1 by Martin
Remove remaining uses of basestring from the codebase
2872
        if not isinstance(path, (str, text_type)):
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2873
            for p in path:
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
2874
                self.assertNotInWorkingTree(p, tree=tree)
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
2875
        else:
6852.3.1 by Jelmer Vernooij
add Tree.is_versioned.
2876
            self.assertFalse(tree.is_versioned(path), path+' in working tree.')
2227.2.1 by v.ladeuil+lp at free
Small fixes to test suite in the hope that it will facilitate the
2877
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2878
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2879
class TestCaseWithTransport(TestCaseInTempDir):
2880
    """A test case that provides get_url and get_readonly_url facilities.
2881
2882
    These back onto two transport servers, one for readonly access and one for
2883
    read write access.
2884
2885
    If no explicit class is provided for readonly access, a
2886
    ReadonlyTransportDecorator is used instead which allows the use of non disk
2887
    based read write transports.
2888
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2889
    If an explicit class is provided for readonly access, that server and the
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2890
    readwrite one must both define get_url() as resolving to os.getcwd().
2891
    """
2892
6499.3.9 by Vincent Ladeuil
Provide fresh config stores for tests.
2893
    def setUp(self):
2894
        super(TestCaseWithTransport, self).setUp()
2895
        self.__vfs_server = None
2896
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2897
    def get_vfs_only_server(self):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2898
        """See TestCaseWithMemoryTransport.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2899
2900
        This is useful for some tests with specific servers that need
2901
        diagnostics.
2902
        """
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2903
        if self.__vfs_server is None:
2904
            self.__vfs_server = self.vfs_transport_factory()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2905
            self.start_server(self.__vfs_server)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2906
        return self.__vfs_server
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2907
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2908
    def make_branch_and_tree(self, relpath, format=None):
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2909
        """Create a branch on the transport and a tree locally.
2910
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2911
        If the transport is not a LocalTransport, the Tree can't be created on
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
2912
        the transport.  In that case if the vfs_transport_factory is
2913
        LocalURLServer the working tree is created in the local
2018.5.88 by Andrew Bennetts
Clarify make_branch_and_tree docstring a little.
2914
        directory backing the transport, and the returned tree's branch and
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
2915
        repository will also be accessed locally. Otherwise a lightweight
2916
        checkout is created and returned.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2917
4650.1.2 by Robert Collins
Remove unnecessary use of an SFTP server connection to test the behaviour of TestCase.make_branch_and_tree.
2918
        We do this because we can't physically create a tree in the local
2919
        path, with a branch reference to the transport_factory url, and
2920
        a branch + repository in the vfs_transport, unless the vfs_transport
2921
        namespace is distinct from the local disk - the two branch objects
2922
        would collide. While we could construct a tree with its branch object
2923
        pointing at the transport_factory transport in memory, reopening it
2924
        would behaving unexpectedly, and has in the past caused testing bugs
2925
        when we tried to do it that way.
2926
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2927
        :param format: The BzrDirFormat.
2928
        :returns: the WorkingTree.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2929
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2930
        # TODO: always use the local disk path for the working tree,
2931
        # this obviously requires a format that supports branch references
2932
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2933
        # RBC 20060208
6155.6.7 by Jelmer Vernooij
Simplify
2934
        format = self.resolve_format(format=format)
6182.1.3 by Jelmer Vernooij
Create checkout if bzrdir doesn't support working trees.
2935
        if not format.supports_workingtrees:
2936
            b = self.make_branch(relpath+'.branch', format=format)
2937
            return b.create_checkout(relpath, lightweight=True)
6155.6.7 by Jelmer Vernooij
Simplify
2938
        b = self.make_branch(relpath, format=format)
2939
        try:
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
2940
            return b.controldir.create_workingtree()
6155.6.7 by Jelmer Vernooij
Simplify
2941
        except errors.NotLocalUrl:
2942
            # We can only make working trees locally at the moment.  If the
2943
            # transport can't support them, then we keep the non-disk-backed
2944
            # branch and create a local checkout.
2945
            if self.vfs_transport_factory is test_server.LocalURLServer:
2946
                # the branch is colocated on disk, we cannot create a checkout.
2947
                # hopefully callers will expect this.
6472.2.1 by Jelmer Vernooij
Use bzrdir.controldir for generic access to control directories.
2948
                local_controldir = controldir.ControlDir.open(
2949
                    self.get_vfs_only_url(relpath))
6155.6.7 by Jelmer Vernooij
Simplify
2950
                wt = local_controldir.create_workingtree()
2951
                if wt.branch._format != b._format:
2952
                    wt._branch = b
2953
                    # Make sure that assigning to wt._branch fixes wt.branch,
2954
                    # in case the implementation details of workingtree objects
2955
                    # change.
2956
                    self.assertIs(b, wt.branch)
2957
                return wt
2958
            else:
2959
                return b.create_checkout(relpath, lightweight=True)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2960
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
2961
    def assertIsDirectory(self, relpath, transport):
2962
        """Assert that relpath within transport is a directory.
2963
2964
        This may not be possible on all transports; in that case it propagates
2965
        a TransportNotPossible.
2966
        """
2967
        try:
2968
            mode = transport.stat(relpath).st_mode
2969
        except errors.NoSuchFile:
2970
            self.fail("path %s is not a directory; no such file"
2971
                      % (relpath))
2972
        if not stat.S_ISDIR(mode):
2973
            self.fail("path %s is not a directory; has mode %#o"
2974
                      % (relpath, mode))
2975
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
2976
    def assertTreesEqual(self, left, right):
2977
        """Check that left and right have the same content and properties."""
2978
        # we use a tree delta to check for equality of the content, and we
2979
        # manually check for equality of other things such as the parents list.
2980
        self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2981
        differences = left.changes_from(right)
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
2982
        self.assertFalse(differences.has_changed(),
2983
            "Trees %r and %r are different: %r" % (left, right, differences))
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
2984
4695.3.2 by Vincent Ladeuil
Simplified and claried as per Robert's review.
2985
    def disable_missing_extensions_warning(self):
2986
        """Some tests expect a precise stderr content.
2987
2988
        There is no point in forcing them to duplicate the extension related
2989
        warning.
2990
        """
6695.4.3 by Jelmer Vernooij
Fix running of tests without extensions.
2991
        config.GlobalConfig().set_user_option(
2992
            'suppress_warnings', 'missing_extensions')
4695.3.2 by Vincent Ladeuil
Simplified and claried as per Robert's review.
2993
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2994
1534.4.31 by Robert Collins
cleanedup test_outside_wt
2995
class ChrootedTestCase(TestCaseWithTransport):
2996
    """A support class that provides readonly urls outside the local namespace.
2997
2998
    This is done by checking if self.transport_server is a MemoryServer. if it
2999
    is then we are chrooted already, if it is not then an HttpServer is used
3000
    for readonly urls.
3001
3002
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3003
                       be used without needed to redo it when a different
1534.4.31 by Robert Collins
cleanedup test_outside_wt
3004
                       subclass is in use ?
3005
    """
3006
3007
    def setUp(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3008
        from breezy.tests import http_server
1534.4.31 by Robert Collins
cleanedup test_outside_wt
3009
        super(ChrootedTestCase, 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.
3010
        if not self.vfs_transport_factory == memory.MemoryServer:
4731.2.9 by Vincent Ladeuil
Implement a new -Ethreads to better track the leaks.
3011
            self.transport_readonly_server = http_server.HttpServer
1534.4.31 by Robert Collins
cleanedup test_outside_wt
3012
3013
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3014
def condition_id_re(pattern):
3015
    """Create a condition filter which performs a re check on a test's id.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3016
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3017
    :param pattern: A regular expression string.
3018
    :return: A callable that returns True if the re matches.
3019
    """
5326.2.1 by Parth Malwankar
added InvalidPattern error.
3020
    filter_re = re.compile(pattern, 0)
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3021
    def condition(test):
3022
        test_id = test.id()
3023
        return filter_re.search(test_id)
3024
    return condition
3025
3026
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
3027
def condition_isinstance(klass_or_klass_list):
3028
    """Create a condition filter which returns isinstance(param, klass).
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3029
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
3030
    :return: A callable which when called with one parameter obj return the
3031
        result of isinstance(obj, klass_or_klass_list).
3032
    """
3033
    def condition(obj):
3034
        return isinstance(obj, klass_or_klass_list)
3035
    return condition
3036
3037
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
3038
def condition_id_in_list(id_list):
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
3039
    """Create a condition filter which verify that test's id in a list.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3040
3302.8.4 by Vincent Ladeuil
Cosmetic changes.
3041
    :param id_list: A TestIdList object.
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
3042
    :return: A callable that returns True if the test's id appears in the list.
3043
    """
3044
    def condition(test):
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
3045
        return id_list.includes(test.id())
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
3046
    return condition
3047
3048
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3049
def condition_id_startswith(starts):
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3050
    """Create a condition filter verifying that test's id starts with a string.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3051
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3052
    :param starts: A list of string.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3053
    :return: A callable that returns True if the test's id starts with one of
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3054
        the given strings.
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3055
    """
3056
    def condition(test):
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3057
        for start in starts:
3058
            if test.id().startswith(start):
3059
                return True
3060
        return False
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3061
    return condition
3062
3063
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3064
def exclude_tests_by_condition(suite, condition):
3065
    """Create a test suite which excludes some tests from suite.
3066
3067
    :param suite: The suite to get tests from.
3068
    :param condition: A callable whose result evaluates True when called with a
3069
        test case which should be excluded from the result.
3070
    :return: A suite which contains the tests found in suite that fail
3071
        condition.
3072
    """
3073
    result = []
3074
    for test in iter_suite_tests(suite):
3075
        if not condition(test):
3076
            result.append(test)
3077
    return TestUtil.TestSuite(result)
3078
3079
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
3080
def filter_suite_by_condition(suite, condition):
3081
    """Create a test suite by filtering another one.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3082
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
3083
    :param suite: The source suite.
3084
    :param condition: A callable whose result evaluates True when called with a
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3085
        test case which should be included in the result.
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
3086
    :return: A suite which contains the tests found in suite that pass
3087
        condition.
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3088
    """
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
3089
    result = []
3090
    for test in iter_suite_tests(suite):
3091
        if condition(test):
3092
            result.append(test)
3093
    return TestUtil.TestSuite(result)
3094
3095
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
3096
def filter_suite_by_re(suite, pattern):
2394.2.8 by Ian Clatworthy
incorporate feedback from jam
3097
    """Create a test suite by filtering another one.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3098
2394.2.8 by Ian Clatworthy
incorporate feedback from jam
3099
    :param suite:           the source suite
3100
    :param pattern:         pattern that names must match
3101
    :returns: the newly created suite
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3102
    """
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3103
    condition = condition_id_re(pattern)
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
3104
    result_suite = filter_suite_by_condition(suite, condition)
2921.6.4 by Robert Collins
Move the filter implementation of sort_tests_by_re back to filter_tests_by_re.
3105
    return result_suite
2394.2.8 by Ian Clatworthy
incorporate feedback from jam
3106
3107
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
3108
def filter_suite_by_id_list(suite, test_id_list):
3109
    """Create a test suite by filtering another one.
3110
3111
    :param suite: The source suite.
3112
    :param test_id_list: A list of the test ids to keep as strings.
3113
    :returns: the newly created suite
3114
    """
3115
    condition = condition_id_in_list(test_id_list)
3116
    result_suite = filter_suite_by_condition(suite, condition)
3117
    return result_suite
3118
3119
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3120
def filter_suite_by_id_startswith(suite, start):
3121
    """Create a test suite by filtering another one.
3122
3123
    :param suite: The source suite.
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3124
    :param start: A list of string the test id must start with one of.
3302.11.1 by Vincent Ladeuil
Create a new selftest filter allowing loading only one module/class/test.
3125
    :returns: the newly created suite
3126
    """
3127
    condition = condition_id_startswith(start)
3128
    result_suite = filter_suite_by_condition(suite, condition)
3129
    return result_suite
3130
3131
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
3132
def exclude_tests_by_re(suite, pattern):
3133
    """Create a test suite which excludes some tests from suite.
3134
3135
    :param suite: The suite to get tests from.
3136
    :param pattern: A regular expression string. Test ids that match this
3137
        pattern will be excluded from the result.
3138
    :return: A TestSuite that contains all the tests from suite without the
3139
        tests that matched pattern. The order of tests is the same as it was in
3140
        suite.
3141
    """
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
3142
    return exclude_tests_by_condition(suite, condition_id_re(pattern))
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
3143
3144
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
3145
def preserve_input(something):
3146
    """A helper for performing test suite transformation chains.
3147
3148
    :param something: Anything you want to preserve.
3149
    :return: Something.
3150
    """
3151
    return something
3152
3153
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
3154
def randomize_suite(suite):
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
3155
    """Return a new TestSuite with suite's tests in random order.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3156
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
3157
    The tests in the input suite are flattened into a single suite in order to
3158
    accomplish this. Any nested TestSuites are removed to provide global
3159
    randomness.
3160
    """
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
3161
    tests = list(iter_suite_tests(suite))
3162
    random.shuffle(tests)
3163
    return TestUtil.TestSuite(tests)
3164
3165
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
3166
def split_suite_by_condition(suite, condition):
3167
    """Split a test suite into two by a condition.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3168
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
3169
    :param suite: The suite to split.
3170
    :param condition: The condition to match on. Tests that match this
3171
        condition are returned in the first test suite, ones that do not match
3172
        are in the second suite.
3173
    :return: A tuple of two test suites, where the first contains tests from
3174
        suite matching the condition, and the second contains the remainder
3175
        from suite. The order within each output suite is the same as it was in
3176
        suite.
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3177
    """
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
3178
    matched = []
3179
    did_not_match = []
3180
    for test in iter_suite_tests(suite):
3181
        if condition(test):
3182
            matched.append(test)
3183
        else:
3184
            did_not_match.append(test)
3185
    return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
3186
3187
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
3188
def split_suite_by_re(suite, pattern):
3189
    """Split a test suite into two by a regular expression.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3190
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
3191
    :param suite: The suite to split.
3192
    :param pattern: A regular expression string. Test ids that match this
3193
        pattern will be in the first test suite returned, and the others in the
3194
        second test suite returned.
3195
    :return: A tuple of two test suites, where the first contains tests from
3196
        suite matching pattern, and the second contains the remainder from
3197
        suite. The order within each output suite is the same as it was in
3198
        suite.
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3199
    """
3350.5.1 by Robert Collins
* New helper function for splitting test suites ``split_suite_by_condition``.
3200
    return split_suite_by_condition(suite, condition_id_re(pattern))
2213.2.1 by Martin Pool
Add selftest --first flag
3201
3202
1185.16.58 by mbp at sourcefrog
- run all selftests by default
3203
def run_suite(suite, name='test', verbose=False, pattern=".*",
2485.6.6 by Martin Pool
Put test root directory (containing per-test directories) in TMPDIR
3204
              stop_on_failure=False,
2213.2.1 by Martin Pool
Add selftest --first flag
3205
              transport=None, lsprof_timed=None, bench_history=None,
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
3206
              matching_tests_first=None,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
3207
              list_only=False,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3208
              random_seed=None,
2418.4.1 by John Arbash Meinel
(Ian Clatworthy) Bugs #102679, #102686. Add --exclude and --randomize to 'bzr selftest'
3209
              exclude_pattern=None,
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3210
              strict=False,
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3211
              runner_class=None,
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
3212
              suite_decorators=None,
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3213
              stream=None,
3214
              result_decorators=None,
3215
              ):
6622.1.30 by Jelmer Vernooij
Some more test fixes.
3216
    """Run a test suite for brz selftest.
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3217
3218
    :param runner_class: The class of runner to use. Must support the
3219
        constructor arguments passed by run_suite which are more than standard
3220
        python uses.
3221
    :return: A boolean indicating success.
3222
    """
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
3223
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
3224
    if verbose:
3225
        verbosity = 2
3226
    else:
3227
        verbosity = 1
4000.2.1 by Robert Collins
Add library level support for different test runners to bzrlib.
3228
    if runner_class is None:
3229
        runner_class = TextTestRunner
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
3230
    if stream is None:
3231
        stream = sys.stdout
3232
    runner = runner_class(stream=stream,
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
3233
                            descriptions=0,
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
3234
                            verbosity=verbosity,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
3235
                            bench_history=bench_history,
4271.2.1 by Robert Collins
Move test prelude and suffix output to ExtendedTestResult
3236
                            strict=strict,
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3237
                            result_decorators=result_decorators,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
3238
                            )
1185.16.58 by mbp at sourcefrog
- run all selftests by default
3239
    runner.stop_on_failure=stop_on_failure
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3240
    if isinstance(suite, unittest.TestSuite):
3241
        # Empty out _tests list of passed suite and populate new TestSuite
3242
        suite._tests[:], suite = [], TestSuite(suite)
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3243
    # built in decorator factories:
3244
    decorators = [
3245
        random_order(random_seed, runner),
3246
        exclude_tests(exclude_pattern),
3247
        ]
3248
    if matching_tests_first:
3249
        decorators.append(tests_first(pattern))
3250
    else:
3251
        decorators.append(filter_tests(pattern))
3252
    if suite_decorators:
3253
        decorators.extend(suite_decorators)
4618.1.1 by Vincent Ladeuil
Make --parallel=fork work again.
3254
    # tell the result object how many tests will be running: (except if
4618.1.2 by Vincent Ladeuil
Fixed as per John's review.
3255
    # --parallel=fork is being used. Robert said he will provide a better
4618.1.1 by Vincent Ladeuil
Make --parallel=fork work again.
3256
    # progress design later -- vila 20090817)
4618.1.2 by Vincent Ladeuil
Fixed as per John's review.
3257
    if fork_decorator not in decorators:
4618.1.1 by Vincent Ladeuil
Make --parallel=fork work again.
3258
        decorators.append(CountingDecorator)
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3259
    for decorator in decorators:
3260
        suite = decorator(suite)
4266.2.1 by Robert Collins
Remove noise from bzr selftest --list-only so that it is easier to use in scripts.
3261
    if list_only:
4650.1.9 by Robert Collins
Detangle test listing: its more part of the ui layer not the execute-this-test-layer.
3262
        # Done after test suite decoration to allow randomisation etc
3263
        # to take effect, though that is of marginal benefit.
3264
        if verbosity >= 2:
3265
            stream.write("Listing tests only ...\n")
6765.1.2 by Jelmer Vernooij
Fix compatibility.
3266
        if getattr(runner, 'list', None) is not None:
3267
            runner.list(suite)
3268
        else:
3269
            for t in iter_suite_tests(suite):
3270
                stream.write("%s\n" % (t.id()))
4266.2.1 by Robert Collins
Remove noise from bzr selftest --list-only so that it is easier to use in scripts.
3271
        return True
4650.1.9 by Robert Collins
Detangle test listing: its more part of the ui layer not the execute-this-test-layer.
3272
    result = runner.run(suite)
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3273
    if strict:
3274
        return result.wasStrictlySuccessful()
3275
    else:
3276
        return result.wasSuccessful()
3277
3278
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3279
# A registry where get() returns a suite decorator.
3280
parallel_registry = registry.Registry()
4229.3.1 by Vincent Ladeuil
Fix selftest --parallel for ConcurrentTestSuite uses.
3281
3282
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3283
def fork_decorator(suite):
5393.5.2 by Martin
Move check 'closer to the metal' as requested by lifelss in review
3284
    if getattr(os, "fork", None) is None:
3285
        raise errors.BzrCommandError("platform does not support fork,"
3286
            " try --parallel=subprocess instead.")
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
3287
    concurrency = osutils.local_concurrency()
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3288
    if concurrency == 1:
3289
        return suite
3290
    from testtools import ConcurrentTestSuite
3291
    return ConcurrentTestSuite(suite, fork_for_tests)
3292
parallel_registry.register('fork', fork_decorator)
4229.3.1 by Vincent Ladeuil
Fix selftest --parallel for ConcurrentTestSuite uses.
3293
3294
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3295
def subprocess_decorator(suite):
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
3296
    concurrency = osutils.local_concurrency()
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3297
    if concurrency == 1:
3298
        return suite
3299
    from testtools import ConcurrentTestSuite
3300
    return ConcurrentTestSuite(suite, reinvoke_for_tests)
3301
parallel_registry.register('subprocess', subprocess_decorator)
3302
3303
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3304
def exclude_tests(exclude_pattern):
3305
    """Return a test suite decorator that excludes tests."""
3306
    if exclude_pattern is None:
3307
        return identity_decorator
3308
    def decorator(suite):
3309
        return ExcludeDecorator(suite, exclude_pattern)
3310
    return decorator
3311
3312
3313
def filter_tests(pattern):
3314
    if pattern == '.*':
3315
        return identity_decorator
3316
    def decorator(suite):
3317
        return FilterTestsDecorator(suite, pattern)
3318
    return decorator
3319
3320
3321
def random_order(random_seed, runner):
3322
    """Return a test suite decorator factory for randomising tests order.
6621.18.1 by Martin
Remove or fix use of long type and nearby type issues
3323
3324
    :param random_seed: now, a string which casts to an integer, or an integer.
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3325
    :param runner: A test runner with a stream attribute to report on.
3326
    """
3327
    if random_seed is None:
3328
        return identity_decorator
3329
    def decorator(suite):
3330
        return RandomDecorator(suite, random_seed, runner.stream)
3331
    return decorator
3332
3333
3334
def tests_first(pattern):
3335
    if pattern == '.*':
3336
        return identity_decorator
3337
    def decorator(suite):
3338
        return TestFirstDecorator(suite, pattern)
3339
    return decorator
3340
3341
3342
def identity_decorator(suite):
3343
    """Return suite."""
3344
    return suite
3345
3346
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
3347
class TestDecorator(TestUtil.TestSuite):
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3348
    """A decorator for TestCase/TestSuite objects.
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3349
3350
    Contains rather than flattening suite passed on construction
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3351
    """
3352
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3353
    def __init__(self, suite=None):
3354
        super(TestDecorator, self).__init__()
3355
        if suite is not None:
3356
            self.addTest(suite)
3357
3358
    # Don't need subclass run method with suite emptying
3359
    run = unittest.TestSuite.run
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3360
3361
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
3362
class CountingDecorator(TestDecorator):
3363
    """A decorator which calls result.progress(self.countTestCases)."""
3364
3365
    def run(self, result):
3366
        progress_method = getattr(result, 'progress', None)
3367
        if callable(progress_method):
4573.2.3 by Robert Collins
Support python 2.4.
3368
            progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
4573.2.1 by Robert Collins
Don't call countTestCases from TextTestRunner.run, rather let tests decide if they want to be counted.
3369
        return super(CountingDecorator, self).run(result)
3370
3371
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3372
class ExcludeDecorator(TestDecorator):
3373
    """A decorator which excludes test matching an exclude pattern."""
3374
3375
    def __init__(self, suite, exclude_pattern):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3376
        super(ExcludeDecorator, self).__init__(
3377
            exclude_tests_by_re(suite, exclude_pattern))
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3378
3379
3380
class FilterTestsDecorator(TestDecorator):
3381
    """A decorator which filters tests to those matching a pattern."""
3382
3383
    def __init__(self, suite, pattern):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3384
        super(FilterTestsDecorator, self).__init__(
3385
            filter_suite_by_re(suite, pattern))
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3386
3387
3388
class RandomDecorator(TestDecorator):
3389
    """A decorator which randomises the order of its tests."""
3390
3391
    def __init__(self, suite, random_seed, stream):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3392
        random_seed = self.actual_seed(random_seed)
3393
        stream.write("Randomizing test order using seed %s\n\n" %
3394
            (random_seed,))
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3395
        # Initialise the random number generator.
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3396
        random.seed(random_seed)
3397
        super(RandomDecorator, self).__init__(randomize_suite(suite))
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3398
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3399
    @staticmethod
3400
    def actual_seed(seed):
3401
        if seed == "now":
6621.18.1 by Martin
Remove or fix use of long type and nearby type issues
3402
            # We convert the seed to an integer to make it reuseable across
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3403
            # invocations (because the user can reenter it).
6621.18.1 by Martin
Remove or fix use of long type and nearby type issues
3404
            return int(time.time())
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3405
        else:
6621.18.1 by Martin
Remove or fix use of long type and nearby type issues
3406
            # Convert the seed to an integer if we can
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3407
            try:
6621.18.1 by Martin
Remove or fix use of long type and nearby type issues
3408
                return int(seed)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3409
            except (TypeError, ValueError):
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3410
                pass
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3411
        return seed
4205.3.1 by Robert Collins
Refactor tests.run_suite to be more data driven, making it shorter and able to be extended more easily.
3412
3413
3414
class TestFirstDecorator(TestDecorator):
3415
    """A decorator which moves named tests to the front."""
3416
3417
    def __init__(self, suite, pattern):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3418
        super(TestFirstDecorator, self).__init__()
3419
        self.addTests(split_suite_by_re(suite, pattern))
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
3420
3421
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3422
def partition_tests(suite, count):
3423
    """Partition suite into count lists of tests."""
5365.3.1 by Andrew Bennetts
Better (and simpler) algorithm for partition_tests.
3424
    # This just assigns tests in a round-robin fashion.  On one hand this
3425
    # splits up blocks of related tests that might run faster if they shared
3426
    # resources, but on the other it avoids assigning blocks of slow tests to
3427
    # just one partition.  So the slowest partition shouldn't be much slower
3428
    # than the fastest.
3429
    partitions = [list() for i in range(count)]
3430
    tests = iter_suite_tests(suite)
6631.2.2 by Martin
Run 2to3 itertools fixer and refactor
3431
    for partition, test in zip(itertools.cycle(partitions), tests):
5365.3.1 by Andrew Bennetts
Better (and simpler) algorithm for partition_tests.
3432
        partition.append(test)
3433
    return partitions
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3434
3435
5180.2.1 by Vincent Ladeuil
Workaround ``Crypto.Random`` check leading to spurious test failures
3436
def workaround_zealous_crypto_random():
3437
    """Crypto.Random want to help us being secure, but we don't care here.
3438
3439
    This workaround some test failure related to the sftp server. Once paramiko
3440
    stop using the controversial API in Crypto.Random, we may get rid of it.
3441
    """
3442
    try:
3443
        from Crypto.Random import atfork
3444
        atfork()
3445
    except ImportError:
3446
        pass
3447
3448
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3449
def fork_for_tests(suite):
3450
    """Take suite and start up one runner per CPU by forking()
3451
3452
    :return: An iterable of TestCase-like objects which can each have
4229.3.1 by Vincent Ladeuil
Fix selftest --parallel for ConcurrentTestSuite uses.
3453
        run(result) called on them to feed tests to result.
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3454
    """
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
3455
    concurrency = osutils.local_concurrency()
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3456
    result = []
5340.16.12 by Martin
Use tweaks for subunit protocol client with --parallel=fork as well as --subunit
3457
    from subunit import ProtocolTestCase
4794.1.20 by Robert Collins
Appropriately guard the import of AutoTimingTestResultDecorator from subunit.
3458
    from subunit.test_results import AutoTimingTestResultDecorator
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3459
    class TestInOtherProcess(ProtocolTestCase):
3460
        # Should be in subunit, I think. RBC.
3461
        def __init__(self, stream, pid):
3462
            ProtocolTestCase.__init__(self, stream)
3463
            self.pid = pid
3464
3465
        def run(self, result):
3466
            try:
3467
                ProtocolTestCase.run(self, result)
3468
            finally:
6221.1.5 by Martin Packman
Note where the child exit status is currently being ignored
3469
                pid, status = os.waitpid(self.pid, 0)
3470
            # GZ 2011-10-18: If status is nonzero, should report to the result
3471
            #                that something went wrong.
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3472
3473
    test_blocks = partition_tests(suite, concurrency)
5340.16.9 by Martin
Tweaks and comments
3474
    # Clear the tests from the original suite so it doesn't keep them alive
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3475
    suite._tests[:] = []
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3476
    for process_tests in test_blocks:
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3477
        process_suite = TestUtil.TestSuite(process_tests)
5340.16.9 by Martin
Tweaks and comments
3478
        # Also clear each split list so new suite has only reference
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3479
        process_tests[:] = []
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3480
        c2pread, c2pwrite = os.pipe()
3481
        pid = os.fork()
3482
        if pid == 0:
3483
            try:
6221.1.4 by Martin Packman
Exit with an error if something goes wrong in a forked child and try to show the traceback
3484
                stream = os.fdopen(c2pwrite, 'wb', 1)
6221.1.1 by Martin Packman
Move atfork crypto workaround inside safety net
3485
                workaround_zealous_crypto_random()
6954.1.7 by Jelmer Vernooij
Switch to coverage.
3486
                try:
3487
                    import coverage
3488
                except ImportError:
3489
                    pass
3490
                else:
3491
                    coverage.process_startup()
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3492
                os.close(c2pread)
3493
                # Leave stderr and stdout open so we can see test noise
3494
                # Close stdin so that the child goes away if it decides to
3495
                # read from stdin (otherwise its a roulette to see what
4229.3.1 by Vincent Ladeuil
Fix selftest --parallel for ConcurrentTestSuite uses.
3496
                # child actually gets keystrokes for pdb etc).
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3497
                sys.stdin.close()
4794.1.11 by Robert Collins
Remove decorator class that won't be needed with upgraded dependencies.
3498
                subunit_result = AutoTimingTestResultDecorator(
6765.1.4 by Jelmer Vernooij
Fix tests.
3499
                    SubUnitBzrProtocolClientv1(stream))
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3500
                process_suite.run(subunit_result)
6221.1.4 by Martin Packman
Exit with an error if something goes wrong in a forked child and try to show the traceback
3501
            except:
3502
                # Try and report traceback on stream, but exit with error even
6234.2.2 by Martin Packman
Add comment as suggested by poolie in review
3503
                # if stream couldn't be created or something else goes wrong.
3504
                # The traceback is formatted to a string and written in one go
3505
                # to avoid interleaving lines from multiple failing children.
6221.1.4 by Martin Packman
Exit with an error if something goes wrong in a forked child and try to show the traceback
3506
                try:
6234.2.1 by Martin Packman
Write traceback from forking child errors in one go to avoid interlacing output lines
3507
                    stream.write(traceback.format_exc())
6221.1.4 by Martin Packman
Exit with an error if something goes wrong in a forked child and try to show the traceback
3508
                finally:
3509
                    os._exit(1)
3510
            os._exit(0)
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3511
        else:
3512
            os.close(c2pwrite)
3513
            stream = os.fdopen(c2pread, 'rb', 1)
3514
            test = TestInOtherProcess(stream, pid)
3515
            result.append(test)
3516
    return result
3517
3518
3519
def reinvoke_for_tests(suite):
3520
    """Take suite and start up one runner per CPU using subprocess().
3521
3522
    :return: An iterable of TestCase-like objects which can each have
4229.3.1 by Vincent Ladeuil
Fix selftest --parallel for ConcurrentTestSuite uses.
3523
        run(result) called on them to feed tests to result.
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3524
    """
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
3525
    concurrency = osutils.local_concurrency()
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3526
    result = []
4496.3.6 by Andrew Bennetts
Tidy some more imports.
3527
    from subunit import ProtocolTestCase
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3528
    class TestInSubprocess(ProtocolTestCase):
3529
        def __init__(self, process, name):
3530
            ProtocolTestCase.__init__(self, process.stdout)
3531
            self.process = process
3532
            self.process.stdin.close()
3533
            self.name = name
3534
3535
        def run(self, result):
3536
            try:
3537
                ProtocolTestCase.run(self, result)
3538
            finally:
3539
                self.process.wait()
3540
                os.unlink(self.name)
3541
            # print "pid %d finished" % finished_process
3542
    test_blocks = partition_tests(suite, concurrency)
3543
    for process_tests in test_blocks:
3544
        # ugly; currently reimplement rather than reuses TestCase methods.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3545
        bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3546
        if not os.path.isfile(bzr_path):
3547
            # We are probably installed. Assume sys.argv is the right file
3548
            bzr_path = sys.argv[0]
4805.2.1 by Gordon Tyler
Fixed reinvoke_for_tests to work on win32.
3549
        bzr_path = [bzr_path]
3550
        if sys.platform == "win32":
3551
            # if we're on windows, we can't execute the bzr script directly
5163.1.3 by Gordon Tyler
Set stdout to binary mode on win32 if --subunit option given to selftest.
3552
            bzr_path = [sys.executable] + bzr_path
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3553
        fd, test_list_file_name = tempfile.mkstemp()
3554
        test_list_file = os.fdopen(fd, 'wb', 1)
3555
        for test in process_tests:
3556
            test_list_file.write(test.id() + '\n')
3557
        test_list_file.close()
3558
        try:
4805.2.1 by Gordon Tyler
Fixed reinvoke_for_tests to work on win32.
3559
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3560
                '--subunit']
3561
            if '--no-plugins' in sys.argv:
3562
                argv.append('--no-plugins')
5273.1.3 by Vincent Ladeuil
Fix typo.
3563
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
3564
            # noise on stderr it can interrupt the subunit protocol.
5273.1.3 by Vincent Ladeuil
Fix typo.
3565
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
3566
                                      stdout=subprocess.PIPE,
3567
                                      stderr=subprocess.PIPE,
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
3568
                                      bufsize=1)
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3569
            test = TestInSubprocess(process, test_list_file_name)
3570
            result.append(test)
3571
        except:
3572
            os.unlink(test_list_file_name)
3573
            raise
3574
    return result
3575
3576
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.
3577
class ProfileResult(testtools.ExtendedToOriginalDecorator):
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3578
    """Generate profiling data for all activity between start and success.
3579
    
3580
    The profile data is appended to the test's _benchcalls attribute and can
3581
    be accessed by the forwarded-to TestResult.
3582
3583
    While it might be cleaner do accumulate this in stopTest, addSuccess is
3584
    where our existing output support for lsprof is, and this class aims to
3585
    fit in with that: while it could be moved it's not necessary to accomplish
4641.3.4 by Robert Collins
Fix typo.
3586
    test profiling, nor would it be dramatically cleaner.
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3587
    """
3588
3589
    def startTest(self, test):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3590
        self.profiler = breezy.lsprof.BzrProfiler()
5331.1.1 by Robert Collins
``bzrlib.lsprof.profile`` will no longer silently generate bad threaded
3591
        # Prevent deadlocks in tests that use lsprof: those tests will
3592
        # unavoidably fail.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3593
        breezy.lsprof.BzrProfiler.profiler_block = 0
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3594
        self.profiler.start()
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.
3595
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3596
3597
    def addSuccess(self, test):
3598
        stats = self.profiler.stop()
3599
        try:
3600
            calls = test._benchcalls
3601
        except AttributeError:
3602
            test._benchcalls = []
3603
            calls = test._benchcalls
3604
        calls.append(((test.id(), "", ""), stats))
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.
3605
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3606
3607
    def stopTest(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.
3608
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3609
        self.profiler = None
3610
3611
6622.1.30 by Jelmer Vernooij
Some more test fixes.
3612
# Controlled by "brz selftest -E=..." option
4523.4.9 by John Arbash Meinel
Change the flags around a bit.
3613
# Currently supported:
3614
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3615
#                           preserves any flags supplied at the command line.
3616
#   -Edisable_lock_checks   Turns errors in mismatched locks into simple prints
3617
#                           rather than failing tests. And no longer raise
3618
#                           LockContention when fctnl locks are not being used
3619
#                           with proper exclusion rules.
5247.1.2 by Vincent Ladeuil
Fix typo in comment.
3620
#   -Ethreads               Will display thread ident at creation/join time to
4731.2.9 by Vincent Ladeuil
Implement a new -Ethreads to better track the leaks.
3621
#                           help track thread leaks
5340.16.3 by Martin
Use 'uncollected_cases' as the flag name which seems a bit clearer
3622
#   -Euncollected_cases     Display the identity of any test cases that weren't
5340.15.1 by John Arbash Meinel
supersede exc-info branch
3623
#                           deallocated after being completed.
5743.14.17 by Vincent Ladeuil
Fix pqm failure by requiring the right version of testtools :-/
3624
#   -Econfig_stats          Will collect statistics using addDetail
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
3625
selftest_debug_flags = set()
3626
3627
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
3628
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
3629
             transport=None,
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3630
             test_suite_factory=None,
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
3631
             lsprof_timed=None,
2213.2.1 by Martin Pool
Add selftest --first flag
3632
             bench_history=None,
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
3633
             matching_tests_first=None,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
3634
             list_only=False,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3635
             random_seed=None,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
3636
             exclude_pattern=None,
3637
             strict=False,
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
3638
             load_list=None,
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
3639
             debug_flags=None,
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
3640
             starting_with=None,
4000.2.3 by Robert Collins
Allow extra options to bzrlib.tests.selftest from plugins.
3641
             runner_class=None,
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3642
             suite_decorators=None,
4636.2.1 by Robert Collins
Test selftest --list-only and --randomize options using more precisely layers.
3643
             stream=None,
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3644
             lsprof_tests=False,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
3645
             ):
1204 by Martin Pool
doc
3646
    """Run the whole test suite under the enhanced runner"""
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
3647
    # XXX: Very ugly way to do this...
3648
    # Disable warning about old formats because we don't want it to disturb
3649
    # any blackbox tests.
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3650
    from breezy import repository
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
3651
    repository._deprecation_warning_done = True
3652
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
3653
    global default_transport
3654
    if transport is None:
3655
        transport = default_transport
3656
    old_transport = default_transport
3657
    default_transport = transport
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
3658
    global selftest_debug_flags
3659
    old_debug_flags = selftest_debug_flags
3660
    if debug_flags is not None:
3661
        selftest_debug_flags = set(debug_flags)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
3662
    try:
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
3663
        if load_list is None:
3664
            keep_only = None
3665
        else:
3666
            keep_only = load_test_id_list(load_list)
4641.2.1 by Robert Collins
Resolve test aliases at the outermost level that test skip filtering is done.
3667
        if starting_with:
3668
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
3669
                             for start in starting_with]
6754.3.1 by Martin
Always consider unittest as interesting prefix so test load failures are displayed
3670
            # Always consider 'unittest' an interesting name so that failed
3671
            # suites wrapped as test cases appear in the output.
3672
            starting_with.append('unittest')
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
3673
        if test_suite_factory is None:
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
3674
            # Reduce loading time by loading modules based on the starting_with
3675
            # patterns.
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
3676
            suite = test_suite(keep_only, starting_with)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
3677
        else:
3678
            suite = test_suite_factory()
4636.2.4 by Robert Collins
Move selftest internals tests out of blackbox test space - they are not testing our selftest command line.
3679
        if starting_with:
3680
            # But always filter as requested.
3681
            suite = filter_suite_by_id_startswith(suite, starting_with)
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3682
        result_decorators = []
3683
        if lsprof_tests:
3684
            result_decorators.append(ProfileResult)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
3685
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
2485.6.6 by Martin Pool
Put test root directory (containing per-test directories) in TMPDIR
3686
                     stop_on_failure=stop_on_failure,
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3687
                     transport=transport,
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
3688
                     lsprof_timed=lsprof_timed,
2213.2.1 by Martin Pool
Add selftest --first flag
3689
                     bench_history=bench_history,
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
3690
                     matching_tests_first=matching_tests_first,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
3691
                     list_only=list_only,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3692
                     random_seed=random_seed,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
3693
                     exclude_pattern=exclude_pattern,
4000.2.3 by Robert Collins
Allow extra options to bzrlib.tests.selftest from plugins.
3694
                     strict=strict,
3695
                     runner_class=runner_class,
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3696
                     suite_decorators=suite_decorators,
4636.2.1 by Robert Collins
Test selftest --list-only and --randomize options using more precisely layers.
3697
                     stream=stream,
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3698
                     result_decorators=result_decorators,
4000.2.3 by Robert Collins
Allow extra options to bzrlib.tests.selftest from plugins.
3699
                     )
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
3700
    finally:
3701
        default_transport = old_transport
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
3702
        selftest_debug_flags = old_debug_flags
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
3703
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
3704
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
3705
def load_test_id_list(file_name):
3706
    """Load a test id list from a text file.
3707
3708
    The format is one test id by line.  No special care is taken to impose
3709
    strict rules, these test ids are used to filter the test suite so a test id
3710
    that do not match an existing test will do no harm. This allows user to add
3711
    comments, leave blank lines, etc.
3712
    """
3713
    test_list = []
3714
    try:
3715
        ftest = open(file_name, 'rt')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
3716
    except IOError as e:
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
3717
        if e.errno != errno.ENOENT:
3718
            raise
3719
        else:
3720
            raise errors.NoSuchFile(file_name)
3721
3722
    for test_name in ftest.readlines():
3723
        test_list.append(test_name.strip())
3724
    ftest.close()
3725
    return test_list
3726
3302.3.3 by Vincent Ladeuil
Fix PEP8 catched by Aaron. Update NEWS.
3727
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
3728
def suite_matches_id_list(test_suite, id_list):
3729
    """Warns about tests not appearing or appearing more than once.
3730
3731
    :param test_suite: A TestSuite object.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3732
    :param test_id_list: The list of test ids that should be found in
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
3733
         test_suite.
3734
3735
    :return: (absents, duplicates) absents is a list containing the test found
3736
        in id_list but not in test_suite, duplicates is a list containing the
6586.1.1 by Vincent Ladeuil
Fix various typos in docstrings. Rename 'buffer' to 'buf' since it's now a python builtin function.
3737
        tests found multiple times in test_suite.
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
3738
3739
    When using a prefined test id list, it may occurs that some tests do not
3740
    exist anymore or that some tests use the same id. This function warns the
3741
    tester about potential problems in his workflow (test lists are volatile)
3742
    or in the test suite itself (using the same id for several tests does not
3743
    help to localize defects).
3744
    """
3745
    # Build a dict counting id occurrences
3746
    tests = dict()
3747
    for test in iter_suite_tests(test_suite):
3748
        id = test.id()
3749
        tests[id] = tests.get(id, 0) + 1
3750
3751
    not_found = []
3752
    duplicates = []
3753
    for id in id_list:
3754
        occurs = tests.get(id, 0)
3755
        if not occurs:
3756
            not_found.append(id)
3757
        elif occurs > 1:
3758
            duplicates.append(id)
3759
3760
    return not_found, duplicates
3761
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
3762
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
3763
class TestIdList(object):
3764
    """Test id list to filter a test suite.
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
3765
3766
    Relying on the assumption that test ids are built as:
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
3767
    <module>[.<class>.<method>][(<param>+)], <module> being in python dotted
3768
    notation, this class offers methods to :
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
3769
    - avoid building a test suite for modules not refered to in the test list,
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
3770
    - keep only the tests listed from the module test suite.
3771
    """
3772
3773
    def __init__(self, test_id_list):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
3774
        # When a test suite needs to be filtered against us we compare test ids
3775
        # for equality, so a simple dict offers a quick and simple solution.
3776
        self.tests = dict().fromkeys(test_id_list, True)
3777
3778
        # While unittest.TestCase have ids like:
3779
        # <module>.<class>.<method>[(<param+)],
3780
        # doctest.DocTestCase can have ids like:
3781
        # <module>
3782
        # <module>.<class>
3783
        # <module>.<function>
3784
        # <module>.<class>.<method>
3785
3786
        # Since we can't predict a test class from its name only, we settle on
3787
        # a simple constraint: a test id always begins with its module name.
3788
3789
        modules = {}
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
3790
        for test_id in test_id_list:
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
3791
            parts = test_id.split('.')
3792
            mod_name = parts.pop(0)
3793
            modules[mod_name] = True
3794
            for part in parts:
3795
                mod_name += '.' + part
3796
                modules[mod_name] = True
3797
        self.modules = modules
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
3798
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
3799
    def refers_to(self, module_name):
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
3800
        """Is there tests for the module or one of its sub modules."""
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
3801
        return module_name in self.modules
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
3802
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
3803
    def includes(self, test_id):
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
3804
        return test_id in self.tests
3193.1.5 by Vincent Ladeuil
Add helper method to get only listed tests from a module test suite.
3805
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
3806
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3807
class TestPrefixAliasRegistry(registry.Registry):
3808
    """A registry for test prefix aliases.
3809
3810
    This helps implement shorcuts for the --starting-with selftest
3811
    option. Overriding existing prefixes is not allowed but not fatal (a
3812
    warning will be emitted).
3813
    """
3814
3815
    def register(self, key, obj, help=None, info=None,
3816
                 override_existing=False):
3817
        """See Registry.register.
3818
3819
        Trying to override an existing alias causes a warning to be emitted,
3820
        not a fatal execption.
3821
        """
3822
        try:
3823
            super(TestPrefixAliasRegistry, self).register(
3824
                key, obj, help=help, info=info, override_existing=False)
3825
        except KeyError:
3826
            actual = self.get(key)
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
3827
            trace.note(
3828
                'Test prefix alias %s is already used for %s, ignoring %s'
3829
                % (key, actual, obj))
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3830
3831
    def resolve_alias(self, id_start):
3832
        """Replace the alias by the prefix in the given string.
3833
3649.6.3 by Vincent Ladeuil
Fixed typos as per John's review.
3834
        Using an unknown prefix is an error to help catching typos.
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3835
        """
3836
        parts = id_start.split('.')
3837
        try:
3838
            parts[0] = self.get(parts[0])
3839
        except KeyError:
3840
            raise errors.BzrCommandError(
3841
                '%s is not a known test prefix alias' % parts[0])
3842
        return '.'.join(parts)
3843
3844
3845
test_prefix_alias_registry = TestPrefixAliasRegistry()
3649.6.3 by Vincent Ladeuil
Fixed typos as per John's review.
3846
"""Registry of test prefix aliases."""
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3847
3848
3849
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3850
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
3851
test_prefix_alias_registry.register('breezy', 'breezy')
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3852
5009.1.1 by Vincent Ladeuil
(trivial) Fix typos
3853
# Obvious highest levels prefixes, feel free to add your own via a plugin
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3854
test_prefix_alias_registry.register('bd', 'breezy.doc')
3855
test_prefix_alias_registry.register('bu', 'breezy.utils')
3856
test_prefix_alias_registry.register('bt', 'breezy.tests')
3857
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
3858
test_prefix_alias_registry.register('bp', 'breezy.plugins')
3649.6.2 by Vincent Ladeuil
Replace aliases in selftest --starting-with option.
3859
3860
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
3861
def _test_suite_testmod_names():
3862
    """Return the standard list of test module names to test."""
3863
    return [
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3864
        'breezy.doc',
3865
        'breezy.tests.blackbox',
3866
        'breezy.tests.commands',
3867
        'breezy.tests.per_branch',
3868
        'breezy.tests.per_bzrdir',
3869
        'breezy.tests.per_controldir',
3870
        'breezy.tests.per_controldir_colo',
3871
        'breezy.tests.per_foreign_vcs',
3872
        'breezy.tests.per_interrepository',
3873
        'breezy.tests.per_intertree',
3874
        'breezy.tests.per_inventory',
3875
        'breezy.tests.per_interbranch',
3876
        'breezy.tests.per_lock',
3877
        'breezy.tests.per_merger',
3878
        'breezy.tests.per_transport',
3879
        'breezy.tests.per_tree',
3880
        'breezy.tests.per_pack_repository',
3881
        'breezy.tests.per_repository',
3882
        'breezy.tests.per_repository_chk',
3883
        'breezy.tests.per_repository_reference',
3884
        'breezy.tests.per_repository_vf',
3885
        'breezy.tests.per_uifactory',
3886
        'breezy.tests.per_versionedfile',
3887
        'breezy.tests.per_workingtree',
3888
        'breezy.tests.test__annotator',
3889
        'breezy.tests.test__bencode',
3890
        'breezy.tests.test__btree_serializer',
3891
        'breezy.tests.test__chk_map',
3892
        'breezy.tests.test__dirstate_helpers',
3893
        'breezy.tests.test__groupcompress',
3894
        'breezy.tests.test__known_graph',
3895
        'breezy.tests.test__rio',
3896
        'breezy.tests.test__simple_set',
3897
        'breezy.tests.test__static_tuple',
3898
        'breezy.tests.test__walkdirs_win32',
3899
        'breezy.tests.test_ancestry',
3900
        'breezy.tests.test_annotate',
3901
        'breezy.tests.test_atomicfile',
3902
        'breezy.tests.test_bad_files',
6656.2.1 by Jelmer Vernooij
Integrate bisect command into core.
3903
        'breezy.tests.test_bisect',
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3904
        'breezy.tests.test_bisect_multi',
3905
        'breezy.tests.test_branch',
3906
        'breezy.tests.test_branchbuilder',
3907
        'breezy.tests.test_btree_index',
3908
        'breezy.tests.test_bugtracker',
3909
        'breezy.tests.test_bundle',
3910
        'breezy.tests.test_bzrdir',
3911
        'breezy.tests.test__chunks_to_lines',
3912
        'breezy.tests.test_cache_utf8',
3913
        'breezy.tests.test_chk_map',
3914
        'breezy.tests.test_chk_serializer',
3915
        'breezy.tests.test_chunk_writer',
3916
        'breezy.tests.test_clean_tree',
3917
        'breezy.tests.test_cleanup',
3918
        'breezy.tests.test_cmdline',
3919
        'breezy.tests.test_commands',
3920
        'breezy.tests.test_commit',
3921
        'breezy.tests.test_commit_merge',
3922
        'breezy.tests.test_config',
3923
        'breezy.tests.test_conflicts',
3924
        'breezy.tests.test_controldir',
3925
        'breezy.tests.test_counted_lock',
3926
        'breezy.tests.test_crash',
3927
        'breezy.tests.test_decorators',
3928
        'breezy.tests.test_delta',
3929
        'breezy.tests.test_debug',
3930
        'breezy.tests.test_diff',
3931
        'breezy.tests.test_directory_service',
3932
        'breezy.tests.test_dirstate',
3933
        'breezy.tests.test_email_message',
3934
        'breezy.tests.test_eol_filters',
3935
        'breezy.tests.test_errors',
3936
        'breezy.tests.test_estimate_compressed_size',
3937
        'breezy.tests.test_export',
3938
        'breezy.tests.test_export_pot',
3939
        'breezy.tests.test_extract',
3940
        'breezy.tests.test_features',
3941
        'breezy.tests.test_fetch',
6651.3.1 by Jelmer Vernooij
Bundle the fetch-ghosts command as hidden command.
3942
        'breezy.tests.test_fetch_ghosts',
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3943
        'breezy.tests.test_fixtures',
3944
        'breezy.tests.test_fifo_cache',
3945
        'breezy.tests.test_filters',
3946
        'breezy.tests.test_filter_tree',
3947
        'breezy.tests.test_foreign',
3948
        'breezy.tests.test_generate_docs',
3949
        'breezy.tests.test_generate_ids',
3950
        'breezy.tests.test_globbing',
3951
        'breezy.tests.test_gpg',
3952
        'breezy.tests.test_graph',
3953
        'breezy.tests.test_groupcompress',
3954
        'breezy.tests.test_hashcache',
3955
        'breezy.tests.test_help',
3956
        'breezy.tests.test_hooks',
3957
        'breezy.tests.test_http',
3958
        'breezy.tests.test_http_response',
3959
        'breezy.tests.test_https_ca_bundle',
3960
        'breezy.tests.test_https_urllib',
3961
        'breezy.tests.test_i18n',
3962
        'breezy.tests.test_identitymap',
3963
        'breezy.tests.test_ignores',
3964
        'breezy.tests.test_index',
3965
        'breezy.tests.test_import_tariff',
3966
        'breezy.tests.test_info',
3967
        'breezy.tests.test_inv',
3968
        'breezy.tests.test_inventory_delta',
3969
        'breezy.tests.test_knit',
3970
        'breezy.tests.test_lazy_import',
3971
        'breezy.tests.test_lazy_regex',
3972
        'breezy.tests.test_library_state',
3973
        'breezy.tests.test_lock',
3974
        'breezy.tests.test_lockable_files',
3975
        'breezy.tests.test_lockdir',
3976
        'breezy.tests.test_log',
3977
        'breezy.tests.test_lru_cache',
3978
        'breezy.tests.test_lsprof',
3979
        'breezy.tests.test_mail_client',
3980
        'breezy.tests.test_matchers',
3981
        'breezy.tests.test_memorytree',
3982
        'breezy.tests.test_merge',
3983
        'breezy.tests.test_merge3',
3984
        'breezy.tests.test_merge_core',
3985
        'breezy.tests.test_merge_directive',
3986
        'breezy.tests.test_mergetools',
3987
        'breezy.tests.test_missing',
3988
        'breezy.tests.test_msgeditor',
3989
        'breezy.tests.test_multiparent',
3990
        'breezy.tests.test_mutabletree',
3991
        'breezy.tests.test_nonascii',
3992
        'breezy.tests.test_options',
3993
        'breezy.tests.test_osutils',
3994
        'breezy.tests.test_osutils_encodings',
3995
        'breezy.tests.test_pack',
3996
        'breezy.tests.test_patch',
3997
        'breezy.tests.test_patches',
3998
        'breezy.tests.test_permissions',
3999
        'breezy.tests.test_plugins',
4000
        'breezy.tests.test_progress',
4001
        'breezy.tests.test_pyutils',
4002
        'breezy.tests.test_read_bundle',
4003
        'breezy.tests.test_reconcile',
4004
        'breezy.tests.test_reconfigure',
4005
        'breezy.tests.test_registry',
4006
        'breezy.tests.test_remote',
4007
        'breezy.tests.test_rename_map',
4008
        'breezy.tests.test_repository',
4009
        'breezy.tests.test_revert',
4010
        'breezy.tests.test_revision',
4011
        'breezy.tests.test_revisionspec',
4012
        'breezy.tests.test_revisiontree',
4013
        'breezy.tests.test_rio',
4014
        'breezy.tests.test_rules',
4015
        'breezy.tests.test_url_policy_open',
4016
        'breezy.tests.test_sampler',
4017
        'breezy.tests.test_scenarios',
4018
        'breezy.tests.test_script',
4019
        'breezy.tests.test_selftest',
4020
        'breezy.tests.test_serializer',
4021
        'breezy.tests.test_setup',
4022
        'breezy.tests.test_sftp_transport',
4023
        'breezy.tests.test_shelf',
4024
        'breezy.tests.test_shelf_ui',
4025
        'breezy.tests.test_smart',
4026
        'breezy.tests.test_smart_add',
4027
        'breezy.tests.test_smart_request',
4028
        'breezy.tests.test_smart_signals',
4029
        'breezy.tests.test_smart_transport',
4030
        'breezy.tests.test_smtp_connection',
4031
        'breezy.tests.test_source',
4032
        'breezy.tests.test_ssh_transport',
4033
        'breezy.tests.test_status',
4034
        'breezy.tests.test_strace',
4035
        'breezy.tests.test_subsume',
4036
        'breezy.tests.test_switch',
4037
        'breezy.tests.test_symbol_versioning',
4038
        'breezy.tests.test_tag',
4039
        'breezy.tests.test_test_server',
4040
        'breezy.tests.test_testament',
4041
        'breezy.tests.test_textfile',
4042
        'breezy.tests.test_textmerge',
4043
        'breezy.tests.test_cethread',
4044
        'breezy.tests.test_timestamp',
4045
        'breezy.tests.test_trace',
4046
        'breezy.tests.test_transactions',
4047
        'breezy.tests.test_transform',
4048
        'breezy.tests.test_transport',
4049
        'breezy.tests.test_transport_log',
4050
        'breezy.tests.test_tree',
4051
        'breezy.tests.test_treebuilder',
4052
        'breezy.tests.test_treeshape',
4053
        'breezy.tests.test_tsort',
4054
        'breezy.tests.test_tuned_gzip',
4055
        'breezy.tests.test_ui',
4056
        'breezy.tests.test_uncommit',
4057
        'breezy.tests.test_upgrade',
4058
        'breezy.tests.test_upgrade_stacked',
6637.1.2 by Jelmer Vernooij
Add tests.
4059
        'breezy.tests.test_upstream_import',
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4060
        'breezy.tests.test_urlutils',
4061
        'breezy.tests.test_utextwrap',
4062
        'breezy.tests.test_version',
4063
        'breezy.tests.test_version_info',
4064
        'breezy.tests.test_versionedfile',
4065
        'breezy.tests.test_vf_search',
6734.1.1 by Jelmer Vernooij
Fix more imports.
4066
        'breezy.tests.test_views',
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4067
        'breezy.tests.test_weave',
4068
        'breezy.tests.test_whitebox',
4069
        'breezy.tests.test_win32utils',
4070
        'breezy.tests.test_workingtree',
4071
        'breezy.tests.test_workingtree_4',
4072
        'breezy.tests.test_wsgi',
4073
        'breezy.tests.test_xml',
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
4074
        ]
4075
4076
4077
def _test_suite_modules_to_doctest():
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4078
    """Return the list of modules to doctest."""
4079
    if __doc__ is None:
4080
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
4081
        return []
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
4082
    return [
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4083
        'breezy',
4084
        'breezy.branchbuilder',
6670.4.1 by Jelmer Vernooij
Update imports.
4085
        'breezy.bzr.inventory',
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4086
        'breezy.decorators',
4087
        'breezy.iterablefile',
4088
        'breezy.lockdir',
4089
        'breezy.merge3',
4090
        'breezy.option',
4091
        'breezy.pyutils',
4092
        'breezy.symbol_versioning',
4093
        'breezy.tests',
4094
        'breezy.tests.fixtures',
4095
        'breezy.timestamp',
4096
        'breezy.transport.http',
4097
        'breezy.version_info_formats.format_custom',
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
4098
        ]
4099
4100
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4101
def test_suite(keep_only=None, starting_with=None):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4102
    """Build and return TestSuite for the whole of breezy.
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
4103
4104
    :param keep_only: A list of test ids limiting the suite returned.
4105
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4106
    :param starting_with: An id limiting the suite returned to the tests
4107
         starting with it.
4108
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
4109
    This function can be replaced if you need to change the default test
4110
    suite on a global basis, but it is not encouraged.
4111
    """
3302.9.23 by Vincent Ladeuil
Simplify test_suite().
4112
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
4113
    loader = TestUtil.TestLoader()
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
4114
4498.1.2 by Vincent Ladeuil
Fix selftest -s xxx --load yyy usage.
4115
    if keep_only is not None:
4116
        id_filter = TestIdList(keep_only)
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
4117
    if starting_with:
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4118
        # We take precedence over keep_only because *at loading time* using
4119
        # both options means we will load less tests for the same final result.
3302.11.5 by Vincent Ladeuil
Fixed as per John's review. Also added a NEWS entry.
4120
        def interesting_module(name):
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
4121
            for start in starting_with:
4122
                if (
4123
                    # Either the module name starts with the specified string
4124
                    name.startswith(start)
4125
                    # or it may contain tests starting with the specified string
4126
                    or start.startswith(name)
4127
                    ):
4128
                    return True
4129
            return False
3302.11.6 by Vincent Ladeuil
Fixed as per Martin and John reviews. Also fix a bug.
4130
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
3302.11.5 by Vincent Ladeuil
Fixed as per John's review. Also added a NEWS entry.
4131
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4132
    elif keep_only is not None:
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
4133
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
3302.11.5 by Vincent Ladeuil
Fixed as per John's review. Also added a NEWS entry.
4134
        def interesting_module(name):
4135
            return id_filter.refers_to(name)
4136
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4137
    else:
4138
        loader = TestUtil.TestLoader()
3302.11.5 by Vincent Ladeuil
Fixed as per John's review. Also added a NEWS entry.
4139
        def interesting_module(name):
4140
            # No filtering, all modules are interesting
4141
            return True
4142
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
4143
    suite = loader.suiteClass()
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
4144
4145
    # modules building their suite with loadTestsFromModuleNames
4650.1.1 by Robert Collins
Refactor test_suite to make stubbing out the list of tests to load possible without sacrificing coverage.
4146
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
4147
4148
    for mod in _test_suite_modules_to_doctest():
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4149
        if not interesting_module(mod):
3302.8.13 by Vincent Ladeuil
DocTests can now be filtered at module level too.
4150
            # No tests to keep here, move along
4151
            continue
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
4152
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4153
            # note that this really does mean "report only" -- doctest
3825.3.4 by Martin Pool
Doc
4154
            # still runs the rest of the examples
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.
4155
            doc_suite = IsolatedDocTestSuite(
5574.6.4 by Vincent Ladeuil
Really isolate doctest by using bzrlib.tests.DocTestSuite.
4156
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
4157
        except ValueError as e:
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
4158
            print('**failed to get doctest for: %s\n%s' % (mod, e))
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
4159
            raise
3825.3.1 by Martin Pool
selftest errors if modules said to have doctests don't have them
4160
        if len(doc_suite._tests) == 0:
4161
            raise errors.BzrError("no doctests found in %s" % (mod,))
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
4162
        suite.addTest(doc_suite)
4163
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
4164
    default_encoding = sys.getdefaultencoding()
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
4165
    for name, plugin in _mod_plugin.plugins().items():
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4166
        if not interesting_module(plugin.module.__name__):
4167
            continue
3221.4.1 by Martin Pool
Treat failure to load plugin test suites as a fatal error
4168
        plugin_suite = plugin.test_suite()
4169
        # We used to catch ImportError here and turn it into just a warning,
4170
        # but really if you don't have --no-plugins this should be a failure.
4171
        # mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
4172
        if plugin_suite is None:
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
4173
            plugin_suite = plugin.load_plugin_tests(loader)
3221.4.1 by Martin Pool
Treat failure to load plugin test suites as a fatal error
4174
        if plugin_suite is not None:
4175
            suite.addTest(plugin_suite)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
4176
        if default_encoding != sys.getdefaultencoding():
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
4177
            trace.warning(
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
4178
                'Plugin "%s" tried to reset default encoding to: %s', name,
4179
                sys.getdefaultencoding())
4180
            reload(sys)
4181
            sys.setdefaultencoding(default_encoding)
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
4182
4183
    if keep_only is not None:
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
4184
        # Now that the referred modules have loaded their tests, keep only the
4185
        # requested ones.
4186
        suite = filter_suite_by_id_list(suite, id_filter)
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
4187
        # Do some sanity checks on the id_list filtering
4188
        not_found, duplicates = suite_matches_id_list(suite, keep_only)
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
4189
        if starting_with:
3302.11.5 by Vincent Ladeuil
Fixed as per John's review. Also added a NEWS entry.
4190
            # The tester has used both keep_only and starting_with, so he is
4191
            # already aware that some tests are excluded from the list, there
4192
            # is no need to tell him which.
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4193
            pass
4194
        else:
3302.11.5 by Vincent Ladeuil
Fixed as per John's review. Also added a NEWS entry.
4195
            # Some tests mentioned in the list are not in the test suite. The
4196
            # list may be out of date, report to the tester.
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
4197
            for id in not_found:
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
4198
                trace.warning('"%s" not found in the test suite', id)
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
4199
        for id in duplicates:
5574.4.1 by Vincent Ladeuil
Cleanup tests imports, they drive me crazy (we had calls for note, trace.log_exception_quietly and bzrlib.trace.warning...)
4200
            trace.warning('"%s" is used as an id by several tests', id)
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
4201
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
4202
    return suite
764 by Martin Pool
- log messages from a particular test are printed if that test fails
4203
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
4204
5462.3.14 by Martin Pool
Unify varations with scenario protocol
4205
def multiply_scenarios(*scenarios):
4206
    """Multiply two or more iterables of scenarios.
4207
4208
    It is safe to pass scenario generators or iterators.
4209
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
4210
    :returns: A list of compound scenarios: the cross-product of all
5462.3.20 by Martin Pool
doc
4211
        scenarios, with the names concatenated and the parameters
4212
        merged together.
5462.3.14 by Martin Pool
Unify varations with scenario protocol
4213
    """
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
4214
    return functools.reduce(_multiply_two_scenarios, map(list, scenarios))
5462.3.14 by Martin Pool
Unify varations with scenario protocol
4215
4216
4217
def _multiply_two_scenarios(scenarios_left, scenarios_right):
2745.6.58 by Andrew Bennetts
Slightly neater test parameterisation in repository_implementations; extract a 'multiply_scenarios' function.
4218
    """Multiply two sets of scenarios.
4219
4220
    :returns: the cartesian product of the two sets of scenarios, that is
4221
        a scenario for every possible combination of a left scenario and a
4222
        right scenario.
4223
    """
4224
    return [
4225
        ('%s,%s' % (left_name, right_name),
6658.1.1 by Martin
Nibble away at getting test_selftest to pass on Python 3
4226
         dict(left_dict, **right_dict))
2745.6.58 by Andrew Bennetts
Slightly neater test parameterisation in repository_implementations; extract a 'multiply_scenarios' function.
4227
        for left_name, left_dict in scenarios_left
4228
        for right_name, right_dict in scenarios_right]
4229
4230
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4231
def multiply_tests(tests, scenarios, result):
4232
    """Multiply tests_list by scenarios into result.
4233
4234
    This is the core workhorse for test parameterisation.
4235
4236
    Typically the load_tests() method for a per-implementation test suite will
4237
    call multiply_tests and return the result.
4238
4239
    :param tests: The tests to parameterise.
4240
    :param scenarios: The scenarios to apply: pairs of (scenario_name,
4241
        scenario_param_dict).
4242
    :param result: A TestSuite to add created tests to.
4243
4244
    This returns the passed in result TestSuite with the cross product of all
4245
    the tests repeated once for each scenario.  Each test is adapted by adding
4246
    the scenario name at the end of its id(), and updating the test object's
4247
    __dict__ with the scenario_param_dict.
4248
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4249
    >>> import breezy.tests.test_sampler
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4250
    >>> r = multiply_tests(
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4251
    ...     breezy.tests.test_sampler.DemoTest('test_nothing'),
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4252
    ...     [('one', dict(param=1)),
4253
    ...      ('two', dict(param=2))],
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
4254
    ...     TestUtil.TestSuite())
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4255
    >>> tests = list(iter_suite_tests(r))
4256
    >>> len(tests)
4257
    2
4258
    >>> tests[0].id()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4259
    'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4260
    >>> tests[0].param
4261
    1
4262
    >>> tests[1].param
4263
    2
4264
    """
4265
    for test in iter_suite_tests(tests):
4266
        apply_scenarios(test, scenarios, result)
4267
    return result
4268
4269
4270
def apply_scenarios(test, scenarios, result):
4271
    """Apply the scenarios in scenarios to test and add to result.
4272
4273
    :param test: The test to apply scenarios to.
4274
    :param scenarios: An iterable of scenarios to apply to test.
4275
    :return: result
4276
    :seealso: apply_scenario
4277
    """
4278
    for scenario in scenarios:
4279
        result.addTest(apply_scenario(test, scenario))
4280
    return result
4281
4282
4283
def apply_scenario(test, scenario):
4284
    """Copy test and apply scenario to it.
4285
4286
    :param test: A test to adapt.
6586.1.1 by Vincent Ladeuil
Fix various typos in docstrings. Rename 'buffer' to 'buf' since it's now a python builtin function.
4287
    :param scenario: A tuple describing the scenario.
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4288
        The first element of the tuple is the new test id.
4289
        The second element is a dict containing attributes to set on the
4290
        test.
4291
    :return: The adapted test.
4292
    """
4293
    new_id = "%s(%s)" % (test.id(), scenario[0])
4294
    new_test = clone_test(test, new_id)
4295
    for name, value in scenario[1].items():
4296
        setattr(new_test, name, value)
4297
    return new_test
4298
4299
4300
def clone_test(test, new_id):
4301
    """Clone a test giving it a new id.
4302
4303
    :param test: The test to clone.
4304
    :param new_id: The id to assign to it.
4305
    :return: The new test.
4306
    """
5273.1.1 by Vincent Ladeuil
Cleanup some imports in bzrlib.tests.
4307
    new_test = copy.copy(test)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4308
    new_test.id = lambda: new_id
5050.33.6 by Andrew Bennetts
Replace __copy__ hack with more direct workaround in clone_test.
4309
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
4310
    # causes cloned tests to share the 'details' dict.  This makes it hard to
4311
    # read the test output for parameterized tests, because tracebacks will be
4312
    # associated with irrelevant tests.
4313
    try:
4314
        details = new_test._TestCase__details
4315
    except AttributeError:
4316
        # must be a different version of testtools than expected.  Do nothing.
4317
        pass
4318
    else:
4319
        # Reset the '__details' dict.
4320
        new_test._TestCase__details = {}
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
4321
    return new_test
3004.1.5 by Daniel Watkins
Added adapt_tests which will adapt tests at a finer-than-module level.
4322
4323
4913.3.1 by John Arbash Meinel
Implement a permute_for_extension helper.
4324
def permute_tests_for_extension(standard_tests, loader, py_module_name,
4325
                                ext_module_name):
4913.3.6 by John Arbash Meinel
Add doc string for permute_tests_for_extension.
4326
    """Helper for permutating tests against an extension module.
4327
4328
    This is meant to be used inside a modules 'load_tests()' function. It will
4329
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4330
    against both implementations. Setting 'test.module' to the appropriate
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4331
    module. See breezy.tests.test__chk_map.load_tests as an example.
4913.3.6 by John Arbash Meinel
Add doc string for permute_tests_for_extension.
4332
4333
    :param standard_tests: A test suite to permute
4334
    :param loader: A TestLoader
4335
    :param py_module_name: The python path to a python module that can always
4336
        be loaded, and will be considered the 'python' implementation. (eg
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4337
        'breezy._chk_map_py')
4913.3.6 by John Arbash Meinel
Add doc string for permute_tests_for_extension.
4338
    :param ext_module_name: The python path to an extension module. If the
4339
        module cannot be loaded, a single test will be added, which notes that
4340
        the module is not available. If it can be loaded, all standard_tests
4341
        will be run against that module.
4342
    :return: (suite, feature) suite is a test-suite that has all the permuted
4343
        tests. feature is the Feature object that can be used to determine if
4344
        the module is available.
4345
    """
4346
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
4347
    from .features import ModuleAvailableFeature
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
4348
    py_module = pyutils.get_named_object(py_module_name)
4913.3.1 by John Arbash Meinel
Implement a permute_for_extension helper.
4349
    scenarios = [
4350
        ('python', {'module': py_module}),
4351
    ]
4352
    suite = loader.suiteClass()
4353
    feature = ModuleAvailableFeature(ext_module_name)
4354
    if feature.available():
4355
        scenarios.append(('C', {'module': feature.module}))
4356
    else:
4357
        # the compiled module isn't available, so we add a failing test
4358
        class FailWithoutFeature(TestCase):
4359
            def test_fail(self):
4360
                self.requireFeature(feature)
4361
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
4362
    result = multiply_tests(standard_tests, scenarios, suite)
4363
    return result, feature
4364
4365
4807.3.3 by John Arbash Meinel
Report the test-id when we fail to delete a testing dir.
4366
def _rmtree_temp_dir(dirname, test_id=None):
2485.6.4 by Martin Pool
Move unicode handling code into _rmtree_temp_dir
4367
    # If LANG=C we probably have created some bogus paths
4368
    # which rmtree(unicode) will fail to delete
4369
    # so make sure we are using rmtree(str) to delete everything
4370
    # except on win32, where rmtree(str) will fail
4371
    # since it doesn't have the property of byte-stream paths
4372
    # (they are either ascii or mbcs)
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
4373
    if sys.platform == 'win32' and isinstance(dirname, bytes):
2485.6.4 by Martin Pool
Move unicode handling code into _rmtree_temp_dir
4374
        # make sure we are using the unicode win32 api
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
4375
        dirname = dirname.decode('mbcs')
2485.6.4 by Martin Pool
Move unicode handling code into _rmtree_temp_dir
4376
    else:
4377
        dirname = dirname.encode(sys.getfilesystemencoding())
2379.6.4 by Alexander Belchenko
Teach `bzr selftest --clean-output` to remove read-only files (win32-specific)
4378
    try:
4379
        osutils.rmtree(dirname)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
4380
    except OSError as e:
4615.3.2 by Vincent Ladeuil
Allows selftest to finish even without fully cleaning the test dir.
4381
        # We don't want to fail here because some useful display will be lost
4382
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4383
        # possible info to the test runner is even worse.
4807.3.3 by John Arbash Meinel
Report the test-id when we fail to delete a testing dir.
4384
        if test_id != None:
4385
            ui.ui_factory.clear_term()
4857.1.1 by John Arbash Meinel
Add an extra newline. It seems that calling clear_term() just isn't enough.
4386
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
5229.1.4 by Vincent Ladeuil
Tested, explain the intent.
4387
        # Ugly, but the last thing we want here is fail, so bear with it.
5229.1.5 by Vincent Ladeuil
Even more paranoid fix.
4388
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
5229.1.3 by Vincent Ladeuil
The test should go on !
4389
                                    ).encode('ascii', 'replace')
4615.3.2 by Vincent Ladeuil
Allows selftest to finish even without fully cleaning the test dir.
4390
        sys.stderr.write('Unable to remove testing dir %s\n%s'
5229.1.2 by Vincent Ladeuil
First try at fixing the unicode encoding error.
4391
                         % (os.path.basename(dirname), printable_e))
2379.6.4 by Alexander Belchenko
Teach `bzr selftest --clean-output` to remove read-only files (win32-specific)
4392
4393
2785.1.5 by Alexander Belchenko
support for non-ascii BZR_HOME in show_version()
4394
def probe_unicode_in_user_encoding():
4395
    """Try to encode several unicode strings to use in unicode-aware tests.
4396
    Return first successfull match.
4397
4398
    :return:  (unicode value, encoded plain string value) or (None, None)
4399
    """
4400
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
4401
    for uni_val in possible_vals:
4402
        try:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
4403
            str_val = uni_val.encode(osutils.get_user_encoding())
2785.1.5 by Alexander Belchenko
support for non-ascii BZR_HOME in show_version()
4404
        except UnicodeEncodeError:
4405
            # Try a different character
4406
            pass
4407
        else:
4408
            return uni_val, str_val
4409
    return None, None
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
4410
4411
2839.6.2 by Alexander Belchenko
changes after Martin's review
4412
def probe_bad_non_ascii(encoding):
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
4413
    """Try to find [bad] character with code [128..255]
2839.6.2 by Alexander Belchenko
changes after Martin's review
4414
    that cannot be decoded to unicode in some encoding.
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
4415
    Return None if all non-ascii characters is valid
2839.6.2 by Alexander Belchenko
changes after Martin's review
4416
    for given encoding.
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
4417
    """
6651.2.2 by Martin
Apply 2to3 xrange fix and fix up with sixish range
4418
    for i in range(128, 256):
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
4419
        char = chr(i)
4420
        try:
2839.6.2 by Alexander Belchenko
changes after Martin's review
4421
            char.decode(encoding)
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
4422
        except UnicodeDecodeError:
4423
            return char
4424
    return None
2917.3.1 by Vincent Ladeuil
Separate transport from test server.
4425
4426
4165.1.1 by Robert Collins
Add builtin subunit support.
4427
# Only define SubUnitBzrRunner if subunit is available.
4428
try:
4429
    from subunit import TestProtocolClient
4794.1.20 by Robert Collins
Appropriately guard the import of AutoTimingTestResultDecorator from subunit.
4430
    from subunit.test_results import AutoTimingTestResultDecorator
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
4431
4432
    class SubUnitBzrProtocolClientv1(TestProtocolClient):
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
4433
5340.16.6 by Martin
Fix subunit collection tests on Python 2.7 with a little copy code
4434
        def stopTest(self, test):
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
4435
            super(SubUnitBzrProtocolClientv1, self).stopTest(test)
5340.16.14 by Martin
Factor out _type_equality_funcs to a new function
4436
            _clear__type_equality_funcs(test)
5340.16.6 by Martin
Fix subunit collection tests on Python 2.7 with a little copy code
4437
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
4438
        def addSuccess(self, test, details=None):
4439
            # The subunit client always includes the details in the subunit
4440
            # stream, but we don't want to include it in ours.
5387.2.9 by John Arbash Meinel
Have to handle when details is None
4441
            if details is not None and 'log' in details:
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
4442
                del details['log']
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
4443
            return super(SubUnitBzrProtocolClientv1, self).addSuccess(
5387.2.6 by John Arbash Meinel
Do a full test suite against all the subunit permutations.
4444
                test, details)
4445
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
4446
    class SubUnitBzrRunnerv1(TextTestRunner):
4447
4165.1.1 by Robert Collins
Add builtin subunit support.
4448
        def run(self, test):
4794.1.11 by Robert Collins
Remove decorator class that won't be needed with upgraded dependencies.
4449
            result = AutoTimingTestResultDecorator(
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
4450
                SubUnitBzrProtocolClientv1(self.stream))
4165.1.1 by Robert Collins
Add builtin subunit support.
4451
            test.run(result)
4452
            return result
4453
except ImportError:
4454
    pass
6765.1.3 by Jelmer Vernooij
Add --subunit2 option.
4455
4456
4457
try:
4458
    from subunit.run import SubunitTestRunner
4459
4460
    class SubUnitBzrRunnerv2(TextTestRunner, SubunitTestRunner):
4461
4462
        def __init__(self, stream=sys.stderr, descriptions=0, verbosity=1,
4463
                     bench_history=None, strict=False, result_decorators=None):
4464
            TextTestRunner.__init__(
4465
                    self, stream=stream,
4466
                    descriptions=descriptions, verbosity=verbosity,
4467
                    bench_history=bench_history, strict=strict,
4468
                    result_decorators=result_decorators)
4469
            SubunitTestRunner.__init__(self, verbosity=verbosity,
4470
                                       stream=stream)
4471
4472
        run = SubunitTestRunner.run
4473
except ImportError:
4474
    pass