/brz/remove-bazaar

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