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