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