/brz/remove-bazaar

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