/brz/remove-bazaar

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