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