/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3173.1.10 by Martin Pool
Move assertFileEqual to TestCase base class as it's generally usable
1
# Copyright (C) 2005, 2006, 2007, 2008 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
31
from cStringIO import StringIO
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
32
import difflib
1740.6.1 by Martin Pool
Remove Scratch objects used by doctests
33
import doctest
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
34
import errno
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
35
import logging
36
import os
2255.2.185 by Martin Pool
assertEqual uses pformat to show results
37
from pprint import pformat
2394.2.2 by Ian Clatworthy
Add --randomize and update help
38
import random
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
39
import re
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
40
import shlex
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
41
import stat
1752.1.1 by Aaron Bentley
Add run_bzr_external
42
from subprocess import Popen, PIPE
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
43
import sys
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
44
import tempfile
3084.1.1 by Andrew Bennetts
Add a --coverage option to selftest.
45
import time
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
46
import unittest
2485.6.5 by Martin Pool
Remove keep_output option
47
import warnings
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
48
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
49
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
50
from bzrlib import (
51
    bzrdir,
52
    debug,
53
    errors,
54
    memorytree,
55
    osutils,
56
    progress,
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
57
    ui,
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
58
    urlutils,
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
59
    workingtree,
2095.5.3 by Martin Pool
Disable all debug_flags when running blackbox tests
60
    )
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
61
import bzrlib.branch
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
62
import bzrlib.commands
1551.12.28 by Aaron Bentley
Move bundle timestamp code to timestamp
63
import bzrlib.timestamp
2024.2.3 by John Arbash Meinel
Move out export tests from test_too_much, refactor
64
import bzrlib.export
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
65
import bzrlib.inventory
1185.67.6 by Aaron Bentley
Added tests and fixes for LockableFiles.put_utf8(); imported IterableFile
66
import bzrlib.iterablefile
1553.5.19 by Martin Pool
Run lockdir doctests
67
import bzrlib.lockdir
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
68
try:
69
    import bzrlib.lsprof
70
except ImportError:
71
    # lsprof not available
72
    pass
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
73
from bzrlib.merge import merge_inner
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
74
import bzrlib.merge3
75
import bzrlib.plugin
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
76
from bzrlib.revision import common_ancestor
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
77
import bzrlib.store
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
78
from bzrlib import symbol_versioning
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
79
from bzrlib.symbol_versioning import (
2921.6.5 by Robert Collins
* The ``exclude_pattern`` parameter to the ``bzrlib.tests.`` functions
80
    DEPRECATED_PARAMETER,
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
81
    deprecated_function,
82
    deprecated_method,
2921.6.5 by Robert Collins
* The ``exclude_pattern`` parameter to the ``bzrlib.tests.`` functions
83
    deprecated_passed,
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
84
    )
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
85
import bzrlib.trace
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
86
from bzrlib.transport import get_transport
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
87
import bzrlib.transport
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
88
from bzrlib.transport.local import LocalURLServer
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
89
from bzrlib.transport.memory import MemoryServer
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
90
from bzrlib.transport.readonly import ReadonlyServer
2095.4.1 by Martin Pool
Better progress bars during tests
91
from bzrlib.trace import mutter, note
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
92
from bzrlib.tests import TestUtil
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
93
from bzrlib.tests.http_server import HttpServer
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
94
from bzrlib.tests.TestUtil import (
95
                          TestSuite,
96
                          TestLoader,
97
                          )
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
98
from bzrlib.tests.treeshape import build_tree_contents
2948.4.1 by Lukáš Lalinský
Custom template-based version info formatter.
99
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.
100
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
101
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)
102
# Mark this python module as being part of the implementation
103
# of unittest: this gives us better tracebacks where the last
104
# shown frame is the test code, not our assertXYZ.
2598.5.7 by Aaron Bentley
Updates from review
105
__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)
106
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
107
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.
108
1185.82.7 by John Arbash Meinel
Adding patches.py into bzrlib, including the tests into the test suite.
109
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
110
def packages_to_test():
1530.2.1 by Robert Collins
Start tests for api usage.
111
    """Return a list of packages to test.
112
113
    The packages are not globally imported so that import failures are
114
    triggered when running selftest, not when importing the command.
115
    """
116
    import bzrlib.doc
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
117
    import bzrlib.tests.blackbox
1534.4.23 by Robert Collins
Move branch implementations tests into a package.
118
    import bzrlib.tests.branch_implementations
1534.4.39 by Robert Collins
Basic BzrDir support.
119
    import bzrlib.tests.bzrdir_implementations
2485.8.3 by v.ladeuil+lp at free
Change the file naming to clearly separate the command behavior
120
    import bzrlib.tests.commands
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
121
    import bzrlib.tests.interrepository_implementations
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
122
    import bzrlib.tests.interversionedfile_implementations
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
123
    import bzrlib.tests.intertree_implementations
2729.2.1 by Martin Pool
Start adding per-inventory tests
124
    import bzrlib.tests.inventory_implementations
2353.3.9 by John Arbash Meinel
Update the lock code and test code so that if more than one
125
    import bzrlib.tests.per_lock
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
126
    import bzrlib.tests.repository_implementations
1563.2.21 by Robert Collins
Smoke test for RevisionStore factories creating revision stores.
127
    import bzrlib.tests.revisionstore_implementations
1852.6.1 by Robert Collins
Start tree implementation tests.
128
    import bzrlib.tests.tree_implementations
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
129
    import bzrlib.tests.workingtree_implementations
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
130
    return [
1530.2.1 by Robert Collins
Start tests for api usage.
131
            bzrlib.doc,
1551.2.6 by Aaron Bentley
Restored blackbox tests [recommit]
132
            bzrlib.tests.blackbox,
1534.4.23 by Robert Collins
Move branch implementations tests into a package.
133
            bzrlib.tests.branch_implementations,
1534.4.39 by Robert Collins
Basic BzrDir support.
134
            bzrlib.tests.bzrdir_implementations,
2485.8.3 by v.ladeuil+lp at free
Change the file naming to clearly separate the command behavior
135
            bzrlib.tests.commands,
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
136
            bzrlib.tests.interrepository_implementations,
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
137
            bzrlib.tests.interversionedfile_implementations,
1852.8.3 by Robert Collins
Implement an InterTreeTestProvider and a trivial test_compare test case.
138
            bzrlib.tests.intertree_implementations,
2729.2.1 by Martin Pool
Start adding per-inventory tests
139
            bzrlib.tests.inventory_implementations,
2353.3.9 by John Arbash Meinel
Update the lock code and test code so that if more than one
140
            bzrlib.tests.per_lock,
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
141
            bzrlib.tests.repository_implementations,
1563.2.21 by Robert Collins
Smoke test for RevisionStore factories creating revision stores.
142
            bzrlib.tests.revisionstore_implementations,
1852.6.1 by Robert Collins
Start tree implementation tests.
143
            bzrlib.tests.tree_implementations,
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
144
            bzrlib.tests.workingtree_implementations,
1513 by Robert Collins
Blackbox tests are maintained within the bzrlib.tests.blackbox directory.
145
            ]
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
146
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
147
2095.4.1 by Martin Pool
Better progress bars during tests
148
class ExtendedTestResult(unittest._TextTestResult):
149
    """Accepts, reports and accumulates the results of running tests.
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
150
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
151
    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
152
    profiling, benchmarking, stopping as soon as a test fails,  and
153
    skipping tests.  There are further-specialized subclasses for
154
    different types of display.
155
156
    When a test finishes, in whatever way, it calls one of the addSuccess,
157
    addFailure or addError classes.  These in turn may redirect to a more
158
    specific case for the special test results supported by our extended
159
    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
160
161
    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
162
    """
2095.4.1 by Martin Pool
Better progress bars during tests
163
1185.62.21 by John Arbash Meinel
Allow bzr selftest --one to continue, even if we have a Skipped test.
164
    stop_early = False
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
165
    
2095.4.1 by Martin Pool
Better progress bars during tests
166
    def __init__(self, stream, descriptions, verbosity,
167
                 bench_history=None,
168
                 num_tests=None,
169
                 ):
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
170
        """Construct new TestResult.
171
172
        :param bench_history: Optionally, a writable file object to accumulate
173
            benchmark results.
174
        """
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
175
        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
176
        if bench_history is not None:
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
177
            from bzrlib.version import _get_bzr_source_tree
178
            src_tree = _get_bzr_source_tree()
179
            if src_tree:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
180
                try:
181
                    revision_id = src_tree.get_parent_ids()[0]
182
                except IndexError:
183
                    # XXX: if this is a brand new tree, do the same as if there
184
                    # is no branch.
185
                    revision_id = ''
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
186
            else:
187
                # XXX: If there's no branch, what should we do?
188
                revision_id = ''
1819.1.4 by Jan Balster
save the revison id for every benchmark run in .perf-history
189
            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
190
        self._bench_history = bench_history
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
191
        self.ui = ui.ui_factory
2095.4.1 by Martin Pool
Better progress bars during tests
192
        self.num_tests = num_tests
193
        self.error_count = 0
194
        self.failure_count = 0
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
195
        self.known_failure_count = 0
2095.4.1 by Martin Pool
Better progress bars during tests
196
        self.skip_count = 0
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
197
        self.not_applicable_count = 0
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
198
        self.unsupported = {}
2095.4.1 by Martin Pool
Better progress bars during tests
199
        self.count = 0
200
        self._overall_start_time = time.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).
201
    
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
202
    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).
203
        """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
204
        return getattr(testCase, "_benchtime", None)
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
205
    
206
    def _elapsedTestTimeString(self):
207
        """Return a time string for the overall time the current test has taken."""
208
        return self._formatTime(time.time() - self._start_time)
209
2695.1.2 by Martin Pool
_benchmarkTime should not be an attribute of ExtendedTestResult, because it only applies to the most recent test reported
210
    def _testTimeString(self, testCase):
211
        benchmark_time = self._extractBenchmarkTime(testCase)
212
        if benchmark_time is not None:
1707.2.3 by Robert Collins
Add a setBenchmarkTime method to the bzrlib test result allowing introduction of granular benchmarking. (Robert Collins, Martin Pool).
213
            return "%s/%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
214
                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).
215
                self._elapsedTestTimeString())
216
        else:
2196.1.1 by Martin Pool
better formatting of benchmark output so it doesn't wrap
217
            return "           %s" % 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).
218
219
    def _formatTime(self, seconds):
220
        """Format seconds as milliseconds with leading spaces."""
2196.1.1 by Martin Pool
better formatting of benchmark output so it doesn't wrap
221
        # some benchmarks can take thousands of seconds to run, so we need 8
222
        # places
223
        return "%8dms" % (1000 * seconds)
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
224
2095.4.1 by Martin Pool
Better progress bars during tests
225
    def _shortened_test_description(self, test):
226
        what = test.id()
2196.1.1 by Martin Pool
better formatting of benchmark output so it doesn't wrap
227
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
2095.4.1 by Martin Pool
Better progress bars during tests
228
        return what
1534.11.3 by Robert Collins
Show test names and status in the progress bar.
229
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
230
    def startTest(self, test):
231
        unittest.TestResult.startTest(self, test)
2095.4.1 by Martin Pool
Better progress bars during tests
232
        self.report_test_start(test)
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
233
        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).
234
        self._recordTestStartTime()
235
236
    def _recordTestStartTime(self):
237
        """Record that a test has started."""
1185.1.58 by Robert Collins
make selftest -v show the elapsed time for each test run.
238
        self._start_time = time.time()
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
239
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
240
    def _cleanupLogFile(self, test):
241
        # We can only do this if we have one of our TestCases, not if
242
        # we have a doctest.
243
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
244
        if setKeepLogfile is not None:
245
            setKeepLogfile()
246
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
247
    def addError(self, test, err):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
248
        """Tell result that test finished with an error.
249
250
        Called from the TestCase run() method when the test
251
        fails with an unexpected error.
252
        """
253
        self._testConcluded(test)
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
254
        if isinstance(err[1], TestSkipped):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
255
            return self._addSkipped(test, err)
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
256
        elif isinstance(err[1], UnavailableFeature):
257
            return self.addNotSupported(test, err[1].args[0])
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
258
        else:
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
259
            self._cleanupLogFile(test)
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
260
            unittest.TestResult.addError(self, test, err)
261
            self.error_count += 1
262
            self.report_error(test, err)
263
            if self.stop_early:
264
                self.stop()
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
265
266
    def addFailure(self, test, err):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
267
        """Tell result that test failed.
268
269
        Called from the TestCase run() method when the test
270
        fails because e.g. an assert() method failed.
271
        """
272
        self._testConcluded(test)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
273
        if isinstance(err[1], KnownFailure):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
274
            return self._addKnownFailure(test, err)
275
        else:
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
276
            self._cleanupLogFile(test)
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
277
            unittest.TestResult.addFailure(self, test, err)
278
            self.failure_count += 1
279
            self.report_failure(test, err)
280
            if self.stop_early:
281
                self.stop()
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
282
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
283
    def addSuccess(self, test):
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
284
        """Tell result that test completed successfully.
285
286
        Called from the TestCase run()
287
        """
288
        self._testConcluded(test)
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
289
        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
290
            benchmark_time = self._extractBenchmarkTime(test)
291
            if benchmark_time is not None:
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
292
                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
293
                    self._formatTime(benchmark_time),
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
294
                    test.id()))
2095.4.1 by Martin Pool
Better progress bars during tests
295
        self.report_success(test)
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
296
        self._cleanupLogFile(test)
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
297
        unittest.TestResult.addSuccess(self, test)
3224.4.4 by Andrew Bennetts
Tweak clearing of _log_contents (idea from John).
298
        test._log_contents = ''
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
299
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
300
    def _testConcluded(self, test):
301
        """Common code when a test has finished.
302
303
        Called regardless of whether it succeded, failed, etc.
304
        """
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
305
        pass
2695.1.1 by Martin Pool
Fix problem if the first test is missing a dependency
306
307
    def _addKnownFailure(self, test, err):
308
        self.known_failure_count += 1
309
        self.report_known_failure(test, err)
310
311
    def addNotSupported(self, test, feature):
312
        """The test will not be run because of a missing feature.
313
        """
314
        # this can be called in two different ways: it may be that the
315
        # test started running, and then raised (through addError) 
316
        # UnavailableFeature.  Alternatively this method can be called
317
        # while probing for features before running the tests; in that
318
        # case we will see startTest and stopTest, but the test will never
319
        # actually run.
320
        self.unsupported.setdefault(str(feature), 0)
321
        self.unsupported[str(feature)] += 1
322
        self.report_unsupported(test, feature)
323
324
    def _addSkipped(self, test, skip_excinfo):
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
325
        if isinstance(skip_excinfo[1], TestNotApplicable):
326
            self.not_applicable_count += 1
327
            self.report_not_applicable(test, skip_excinfo)
328
        else:
329
            self.skip_count += 1
330
            self.report_skip(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.
331
        try:
332
            test.tearDown()
333
        except KeyboardInterrupt:
334
            raise
335
        except:
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
336
            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.
337
        else:
2729.1.4 by Martin Pool
merge trunk
338
            # seems best to treat this as success from point-of-view of unittest
339
            # -- 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.
340
            unittest.TestResult.addSuccess(self, test)
3224.4.6 by Andrew Bennetts
Tweak another _log_contents clearing.
341
            test._log_contents = ''
1185.33.95 by Martin Pool
New TestSkipped facility, and tests for it.
342
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
343
    def printErrorList(self, flavour, errors):
344
        for test, err in errors:
345
            self.stream.writeln(self.separator1)
2321.3.2 by Alexander Belchenko
numbered dirs: printErrorList show test number for NUMBERED_DIRS
346
            self.stream.write("%s: " % flavour)
347
            self.stream.writeln(self.getDescription(test))
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
348
            if getattr(test, '_get_log', None) is not None:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
349
                self.stream.write('\n')
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
350
                self.stream.write(
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
351
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
352
                self.stream.write('\n')
353
                self.stream.write(test._get_log())
354
                self.stream.write('\n')
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
355
                self.stream.write(
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
356
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
357
                self.stream.write('\n')
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
358
            self.stream.writeln(self.separator2)
359
            self.stream.writeln("%s" % err)
360
2095.4.1 by Martin Pool
Better progress bars during tests
361
    def finished(self):
362
        pass
363
364
    def report_cleaning_up(self):
365
        pass
366
367
    def report_success(self, test):
368
        pass
369
2658.3.1 by Daniel Watkins
Added ExtendedTestResult.wasStrictlySuccessful.
370
    def wasStrictlySuccessful(self):
371
        if self.unsupported or self.known_failure_count:
372
            return False
373
        return self.wasSuccessful()
374
375
2095.4.1 by Martin Pool
Better progress bars during tests
376
class TextTestResult(ExtendedTestResult):
377
    """Displays progress and results of tests in text form"""
378
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
379
    def __init__(self, stream, descriptions, verbosity,
380
                 bench_history=None,
381
                 num_tests=None,
382
                 pb=None,
383
                 ):
384
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
385
            bench_history, num_tests)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
386
        if pb is None:
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
387
            self.pb = self.ui.nested_progress_bar()
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
388
            self._supplied_pb = False
389
        else:
390
            self.pb = pb
391
            self._supplied_pb = True
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
392
        self.pb.show_pct = False
393
        self.pb.show_spinner = False
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
394
        self.pb.show_eta = False,
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
395
        self.pb.show_count = False
396
        self.pb.show_bar = False
397
2095.4.1 by Martin Pool
Better progress bars during tests
398
    def report_starting(self):
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
399
        self.pb.update('[test 0/%d] starting...' % (self.num_tests))
2095.4.1 by Martin Pool
Better progress bars during tests
400
401
    def _progress_prefix_text(self):
3297.1.1 by Martin Pool
More concise display of test progress bar
402
        # the longer this text, the less space we have to show the test
403
        # name...
404
        a = '[%d' % self.count              # total that have been run
405
        # tests skipped as known not to be relevant are not important enough
406
        # to show here
407
        ## if self.skip_count:
408
        ##     a += ', %d skip' % self.skip_count
409
        ## if self.known_failure_count:
410
        ##     a += '+%dX' % self.known_failure_count
2095.4.1 by Martin Pool
Better progress bars during tests
411
        if self.num_tests is not None:
412
            a +='/%d' % self.num_tests
3297.1.1 by Martin Pool
More concise display of test progress bar
413
        a += ' in '
414
        runtime = time.time() - self._overall_start_time
415
        if runtime >= 60:
416
            a += '%dm%ds' % (runtime / 60, runtime % 60)
417
        else:
418
            a += '%ds' % runtime
3297.1.3 by Martin Pool
Fix up selftest progress tests
419
        if self.error_count:
420
            a += ', %d err' % self.error_count
421
        if self.failure_count:
422
            a += ', %d fail' % self.failure_count
423
        if self.unsupported:
424
            a += ', %d missing' % len(self.unsupported)
2095.4.3 by Martin Pool
Tweak test display a bit more
425
        a += ']'
2095.4.1 by Martin Pool
Better progress bars during tests
426
        return a
427
428
    def report_test_start(self, test):
429
        self.count += 1
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
430
        self.pb.update(
2095.4.1 by Martin Pool
Better progress bars during tests
431
                self._progress_prefix_text()
432
                + ' ' 
433
                + self._shortened_test_description(test))
434
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
435
    def _test_description(self, test):
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
436
        return self._shortened_test_description(test)
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
437
2095.4.3 by Martin Pool
Tweak test display a bit more
438
    def report_error(self, test, err):
2134.1.1 by Henri Wiechers
Changed TextTestResult's report methods to avoid % formatting in calls to ProgressBar.note(), instead args are passed and note() handles the formatting. This prevents bugs where note() might be passed a string with %'s in it because one of the args contain %'s.
439
        self.pb.note('ERROR: %s\n    %s\n', 
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
440
            self._test_description(test),
2095.4.3 by Martin Pool
Tweak test display a bit more
441
            err[1],
2134.1.1 by Henri Wiechers
Changed TextTestResult's report methods to avoid % formatting in calls to ProgressBar.note(), instead args are passed and note() handles the formatting. This prevents bugs where note() might be passed a string with %'s in it because one of the args contain %'s.
442
            )
2095.4.1 by Martin Pool
Better progress bars during tests
443
2095.4.3 by Martin Pool
Tweak test display a bit more
444
    def report_failure(self, test, err):
2134.1.1 by Henri Wiechers
Changed TextTestResult's report methods to avoid % formatting in calls to ProgressBar.note(), instead args are passed and note() handles the formatting. This prevents bugs where note() might be passed a string with %'s in it because one of the args contain %'s.
445
        self.pb.note('FAIL: %s\n    %s\n', 
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
446
            self._test_description(test),
2095.4.3 by Martin Pool
Tweak test display a bit more
447
            err[1],
2134.1.1 by Henri Wiechers
Changed TextTestResult's report methods to avoid % formatting in calls to ProgressBar.note(), instead args are passed and note() handles the formatting. This prevents bugs where note() might be passed a string with %'s in it because one of the args contain %'s.
448
            )
2095.4.1 by Martin Pool
Better progress bars during tests
449
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
450
    def report_known_failure(self, test, err):
451
        self.pb.note('XFAIL: %s\n%s\n',
452
            self._test_description(test), err[1])
453
2095.4.1 by Martin Pool
Better progress bars during tests
454
    def report_skip(self, test, skip_excinfo):
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
455
        pass
456
457
    def report_not_applicable(self, test, skip_excinfo):
458
        pass
2095.4.1 by Martin Pool
Better progress bars during tests
459
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
460
    def report_unsupported(self, test, feature):
461
        """test cannot be run because feature is missing."""
462
                  
2095.4.1 by Martin Pool
Better progress bars during tests
463
    def report_cleaning_up(self):
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
464
        self.pb.update('cleaning up...')
2095.4.1 by Martin Pool
Better progress bars during tests
465
466
    def finished(self):
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
467
        if not self._supplied_pb:
468
            self.pb.finished()
2095.4.1 by Martin Pool
Better progress bars during tests
469
470
471
class VerboseTestResult(ExtendedTestResult):
472
    """Produce long output, with one line per test run plus times"""
473
474
    def _ellipsize_to_right(self, a_string, final_width):
475
        """Truncate and pad a string, keeping the right hand side"""
476
        if len(a_string) > final_width:
477
            result = '...' + a_string[3-final_width:]
478
        else:
479
            result = a_string
480
        return result.ljust(final_width)
481
482
    def report_starting(self):
483
        self.stream.write('running %d tests...\n' % self.num_tests)
484
485
    def report_test_start(self, test):
486
        self.count += 1
487
        name = self._shortened_test_description(test)
2196.1.1 by Martin Pool
better formatting of benchmark output so it doesn't wrap
488
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
489
        # numbers, plus a trailing blank
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
490
        # 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)
491
        self.stream.write(self._ellipsize_to_right(name,
492
                          osutils.terminal_width()-30))
2095.4.1 by Martin Pool
Better progress bars during tests
493
        self.stream.flush()
494
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
495
    def _error_summary(self, err):
496
        indent = ' ' * 4
497
        return '%s%s' % (indent, err[1])
498
2095.4.3 by Martin Pool
Tweak test display a bit more
499
    def report_error(self, test, err):
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
500
        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
501
                % (self._testTimeString(test),
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
502
                   self._error_summary(err)))
2095.4.1 by Martin Pool
Better progress bars during tests
503
2095.4.3 by Martin Pool
Tweak test display a bit more
504
    def report_failure(self, test, err):
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
505
        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
506
                % (self._testTimeString(test),
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
507
                   self._error_summary(err)))
2095.4.1 by Martin Pool
Better progress bars during tests
508
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
509
    def report_known_failure(self, test, err):
510
        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
511
                % (self._testTimeString(test),
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
512
                   self._error_summary(err)))
513
2095.4.1 by Martin Pool
Better progress bars during tests
514
    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
515
        self.stream.writeln('   OK %s' % self._testTimeString(test))
2095.4.1 by Martin Pool
Better progress bars during tests
516
        for bench_called, stats in getattr(test, '_benchcalls', []):
517
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
518
            stats.pprint(file=self.stream)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
519
        # flush the stream so that we get smooth output. This verbose mode is
520
        # used to show the output in PQM.
2095.4.1 by Martin Pool
Better progress bars during tests
521
        self.stream.flush()
522
523
    def report_skip(self, test, skip_excinfo):
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
524
        self.stream.writeln(' SKIP %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
525
                % (self._testTimeString(test),
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
526
                   self._error_summary(skip_excinfo)))
2095.4.1 by Martin Pool
Better progress bars during tests
527
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
528
    def report_not_applicable(self, test, skip_excinfo):
529
        self.stream.writeln('  N/A %s\n%s'
2729.1.5 by Martin Pool
Update report_not_applicable for _testTimeString fix
530
                % (self._testTimeString(test),
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
531
                   self._error_summary(skip_excinfo)))
532
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
533
    def report_unsupported(self, test, feature):
534
        """test cannot be run because feature is missing."""
535
        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
536
                %(self._testTimeString(test), feature))
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
537
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
538
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
539
class TextTestRunner(object):
1185.16.58 by mbp at sourcefrog
- run all selftests by default
540
    stop_on_failure = False
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
541
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
542
    def __init__(self,
543
                 stream=sys.stderr,
544
                 descriptions=0,
545
                 verbosity=1,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
546
                 bench_history=None,
2418.4.1 by John Arbash Meinel
(Ian Clatworthy) Bugs #102679, #102686. Add --exclude and --randomize to 'bzr selftest'
547
                 list_only=False
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
548
                 ):
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
549
        self.stream = unittest._WritelnDecorator(stream)
550
        self.descriptions = descriptions
551
        self.verbosity = verbosity
1819.1.2 by Carl Friedrich Bolz
(lifeless, cfbolz, hpk): Add a benchmark output parameter to TextTestRunner.
552
        self._bench_history = bench_history
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
553
        self.list_only = list_only
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
554
555
    def run(self, test):
556
        "Run the given test case or test suite."
557
        startTime = time.time()
2095.4.1 by Martin Pool
Better progress bars during tests
558
        if self.verbosity == 1:
559
            result_class = TextTestResult
560
        elif self.verbosity >= 2:
561
            result_class = VerboseTestResult
562
        result = result_class(self.stream,
563
                              self.descriptions,
564
                              self.verbosity,
565
                              bench_history=self._bench_history,
566
                              num_tests=test.countTestCases(),
567
                              )
568
        result.stop_early = self.stop_on_failure
569
        result.report_starting()
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
570
        if self.list_only:
2394.2.2 by Ian Clatworthy
Add --randomize and update help
571
            if self.verbosity >= 2:
572
                self.stream.writeln("Listing tests only ...\n")
573
            run = 0
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
574
            for t in iter_suite_tests(test):
575
                self.stream.writeln("%s" % (t.id()))
2394.2.2 by Ian Clatworthy
Add --randomize and update help
576
                run += 1
577
            actionTaken = "Listed"
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
578
        else: 
579
            test.run(result)
2394.2.2 by Ian Clatworthy
Add --randomize and update help
580
            run = result.testsRun
581
            actionTaken = "Ran"
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
582
        stopTime = time.time()
583
        timeTaken = stopTime - startTime
584
        result.printErrors()
585
        self.stream.writeln(result.separator2)
2394.2.2 by Ian Clatworthy
Add --randomize and update help
586
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
587
                            run, run != 1 and "s" or "", timeTaken))
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
588
        self.stream.writeln()
589
        if not result.wasSuccessful():
590
            self.stream.write("FAILED (")
591
            failed, errored = map(len, (result.failures, result.errors))
592
            if failed:
593
                self.stream.write("failures=%d" % failed)
594
            if errored:
595
                if failed: self.stream.write(", ")
596
                self.stream.write("errors=%d" % errored)
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
597
            if result.known_failure_count:
598
                if failed or errored: self.stream.write(", ")
599
                self.stream.write("known_failure_count=%d" %
600
                    result.known_failure_count)
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
601
            self.stream.writeln(")")
602
        else:
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
603
            if result.known_failure_count:
604
                self.stream.writeln("OK (known_failures=%d)" %
605
                    result.known_failure_count)
606
            else:
607
                self.stream.writeln("OK")
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
608
        if result.skip_count > 0:
609
            skipped = result.skip_count
610
            self.stream.writeln('%d test%s skipped' %
611
                                (skipped, skipped != 1 and "s" or ""))
2367.1.5 by Robert Collins
Implement reporting of Unsupported tests in the bzr test result and runner
612
        if result.unsupported:
613
            for feature, count in sorted(result.unsupported.items()):
614
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
615
                    (feature, count))
2095.4.1 by Martin Pool
Better progress bars during tests
616
        result.finished()
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
617
        return result
618
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
619
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
620
def iter_suite_tests(suite):
621
    """Return all tests in a suite, recursing through nested suites"""
622
    for item in suite._tests:
623
        if isinstance(item, unittest.TestCase):
624
            yield item
625
        elif isinstance(item, unittest.TestSuite):
626
            for r in iter_suite_tests(item):
627
                yield r
628
        else:
629
            raise Exception('unknown object %r inside test suite %r'
630
                            % (item, suite))
631
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
632
633
class TestSkipped(Exception):
634
    """Indicates that a test was intentionally skipped, rather than failing."""
635
636
2729.1.1 by Martin Pool
Add TestNotApplicable exception and handling of it; document test parameterization
637
class TestNotApplicable(TestSkipped):
638
    """A test is not applicable to the situation where it was run.
639
640
    This is only normally raised by parameterized tests, if they find that 
641
    the instance they're constructed upon does not support one aspect 
642
    of its interface.
643
    """
644
645
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
646
class KnownFailure(AssertionError):
647
    """Indicates that a test failed in a precisely expected manner.
648
649
    Such failures dont block the whole test suite from passing because they are
650
    indicators of partially completed code or of future work. We have an
651
    explicit error for them so that we can ensure that they are always visible:
652
    KnownFailures are always shown in the output of bzr selftest.
653
    """
654
655
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
656
class UnavailableFeature(Exception):
657
    """A feature required for this test was not available.
658
659
    The feature should be used to construct the exception.
660
    """
661
662
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
663
class CommandFailed(Exception):
664
    pass
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
665
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
666
667
class StringIOWrapper(object):
668
    """A wrapper around cStringIO which just adds an encoding attribute.
669
    
670
    Internally we can check sys.stdout to see what the output encoding
671
    should be. However, cStringIO has no encoding attribute that we can
672
    set. So we wrap it instead.
673
    """
674
    encoding='ascii'
675
    _cstring = None
676
677
    def __init__(self, s=None):
678
        if s is not None:
679
            self.__dict__['_cstring'] = StringIO(s)
680
        else:
681
            self.__dict__['_cstring'] = StringIO()
682
683
    def __getattr__(self, name, getattr=getattr):
684
        return getattr(self.__dict__['_cstring'], name)
685
686
    def __setattr__(self, name, val):
687
        if name == 'encoding':
688
            self.__dict__['encoding'] = val
689
        else:
690
            return setattr(self._cstring, name, val)
691
692
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
693
class TestUIFactory(ui.CLIUIFactory):
694
    """A UI Factory for testing.
695
696
    Hide the progress bar but emit note()s.
697
    Redirect stdin.
698
    Allows get_password to be tested without real tty attached.
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
699
    """
700
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
701
    def __init__(self,
702
                 stdout=None,
703
                 stderr=None,
704
                 stdin=None):
705
        super(TestUIFactory, self).__init__()
706
        if stdin is not None:
707
            # We use a StringIOWrapper to be able to test various
708
            # encodings, but the user is still responsible to
709
            # encode the string and to set the encoding attribute
710
            # of StringIOWrapper.
711
            self.stdin = StringIOWrapper(stdin)
712
        if stdout is None:
713
            self.stdout = sys.stdout
714
        else:
715
            self.stdout = stdout
716
        if stderr is None:
717
            self.stderr = sys.stderr
718
        else:
719
            self.stderr = stderr
720
721
    def clear(self):
722
        """See progress.ProgressBar.clear()."""
723
724
    def clear_term(self):
725
        """See progress.ProgressBar.clear_term()."""
726
727
    def clear_term(self):
728
        """See progress.ProgressBar.clear_term()."""
729
730
    def finished(self):
731
        """See progress.ProgressBar.finished()."""
732
733
    def note(self, fmt_string, *args, **kwargs):
734
        """See progress.ProgressBar.note()."""
735
        self.stdout.write((fmt_string + "\n") % args)
736
737
    def progress_bar(self):
738
        return self
739
740
    def nested_progress_bar(self):
741
        return self
742
743
    def update(self, message, count=None, total=None):
744
        """See progress.ProgressBar.update()."""
745
746
    def get_non_echoed_password(self, prompt):
747
        """Get password from stdin without trying to handle the echo mode"""
748
        if prompt:
2461.1.1 by Vincent Ladeuil
Fix 110204 by letting TestUIFactory encode password prompt.
749
            self.stdout.write(prompt.encode(self.stdout.encoding, 'replace'))
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
750
        password = self.stdin.readline()
751
        if not password:
752
            raise EOFError
753
        if password[-1] == '\n':
754
            password = password[:-1]
755
        return password
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
756
757
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
758
class TestCase(unittest.TestCase):
759
    """Base class for bzr unit tests.
760
    
761
    Tests that need access to disk resources should subclass 
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
762
    TestCaseInTempDir not TestCase.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
763
764
    Error and debug log messages are redirected from their usual
765
    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.
766
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
767
    so that it can also capture file IO.  When the test completes this file
768
    is read into memory and removed from disk.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
769
       
770
    There are also convenience functions to invoke bzr's command-line
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
771
    routine, and to build and check bzr trees.
772
   
773
    In addition to the usual method of overriding tearDown(), this class also
774
    allows subclasses to register functions into the _cleanups list, which is
775
    run in order as the object is torn down.  It's less likely this will be
776
    accidentally overlooked.
777
    """
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
778
1185.16.14 by Martin Pool
- make TestCase._get_log work even if setup was aborted
779
    _log_file_name = None
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
780
    _log_contents = ''
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
781
    _keep_log_file = False
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
782
    # record lsprof data when performing benchmark calls.
783
    _gather_lsprof_in_benchmarks = False
3405.1.1 by Robert Collins
(robertc) Preserve test ids correctly to aid debugging. (Robert Collins, Andrew Bennetts)
784
    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.
785
                     '_log_contents', '_log_file_name', '_benchtime',
786
                     '_TestCase__testMethodName')
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
787
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
788
    def __init__(self, methodName='testMethod'):
789
        super(TestCase, self).__init__(methodName)
790
        self._cleanups = []
791
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
792
    def setUp(self):
793
        unittest.TestCase.setUp(self)
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
794
        self._cleanEnvironment()
2095.4.1 by Martin Pool
Better progress bars during tests
795
        self._silenceUI()
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
796
        self._startLogFile()
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
797
        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)
798
        self._benchtime = None
2423.1.1 by Martin Pool
fix import order dependency that broke benchmarks
799
        self._clear_hooks()
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
800
        self._clear_debug_flags()
801
802
    def _clear_debug_flags(self):
803
        """Prevent externally set debug flags affecting tests.
804
        
805
        Tests that want to use debug flags can just set them in the
806
        debug_flags set during setup/teardown.
807
        """
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
808
        if 'allow_debug' not in selftest_debug_flags:
3302.2.1 by Andrew Bennetts
Add -Dselftest_debug debug flag.
809
            self._preserved_debug_flags = set(debug.debug_flags)
810
            debug.debug_flags.clear()
811
            self.addCleanup(self._restore_debug_flags)
2423.1.1 by Martin Pool
fix import order dependency that broke benchmarks
812
813
    def _clear_hooks(self):
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
814
        # prevent hooks affecting tests
2423.1.1 by Martin Pool
fix import order dependency that broke benchmarks
815
        import bzrlib.branch
816
        import bzrlib.smart.server
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
817
        self._preserved_hooks = {
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
818
            bzrlib.branch.Branch: bzrlib.branch.Branch.hooks,
3335.1.1 by Jelmer Vernooij
Add tests for mutabletree hooks.
819
            bzrlib.mutabletree.MutableTree: bzrlib.mutabletree.MutableTree.hooks,
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
820
            bzrlib.smart.server.SmartTCPServer: bzrlib.smart.server.SmartTCPServer.hooks,
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
821
            }
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
822
        self.addCleanup(self._restoreHooks)
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
823
        # reset all hooks to an empty instance of the appropriate type
2245.1.2 by Robert Collins
Remove the static DefaultHooks method from Branch, replacing it with a derived dict BranchHooks object, which is easier to use and provides a place to put the policy-checking add method discussed on list.
824
        bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
825
        bzrlib.smart.server.SmartTCPServer.hooks = bzrlib.smart.server.SmartServerHooks()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
826
2095.4.1 by Martin Pool
Better progress bars during tests
827
    def _silenceUI(self):
828
        """Turn off UI for duration of test"""
829
        # 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.
830
        saved = ui.ui_factory
2095.4.1 by Martin Pool
Better progress bars during tests
831
        def _restore():
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
832
            ui.ui_factory = saved
833
        ui.ui_factory = ui.SilentUIFactory()
2095.4.1 by Martin Pool
Better progress bars during tests
834
        self.addCleanup(_restore)
835
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
836
    def _ndiff_strings(self, a, b):
1185.16.67 by Martin Pool
- assertEqualDiff handles strings without trailing newline
837
        """Return ndiff between two strings containing lines.
838
        
839
        A trailing newline is added if missing to make the strings
840
        print properly."""
841
        if b and b[-1] != '\n':
842
            b += '\n'
843
        if a and a[-1] != '\n':
844
            a += '\n'
1185.16.21 by Martin Pool
- tweak diff shown by assertEqualDiff
845
        difflines = difflib.ndiff(a.splitlines(True),
846
                                  b.splitlines(True),
847
                                  linejunk=lambda x: False,
848
                                  charjunk=lambda x: False)
849
        return ''.join(difflines)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
850
2255.2.190 by Martin Pool
assertEqual can take an option message
851
    def assertEqual(self, a, b, message=''):
2360.1.2 by John Arbash Meinel
Add an overzealous test, for Unicode support of _iter_changes.
852
        try:
853
            if a == b:
854
                return
855
        except UnicodeError, e:
856
            # If we can't compare without getting a UnicodeError, then
857
            # obviously they are different
858
            mutter('UnicodeError: %s', e)
2255.2.190 by Martin Pool
assertEqual can take an option message
859
        if message:
860
            message += '\n'
861
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
862
            % (message,
2477.1.4 by Martin Pool
fix up indenting in pformat of inequalities displayed by test suite
863
               pformat(a), pformat(b)))
2255.2.185 by Martin Pool
assertEqual uses pformat to show results
864
865
    assertEquals = assertEqual
866
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.
867
    def assertEqualDiff(self, a, b, message=None):
1185.16.16 by Martin Pool
- add TestCase.assertEqualDiffs helper
868
        """Assert two texts are equal, if not raise an exception.
869
        
870
        This is intended for use with multi-line strings where it can 
871
        be hard to find the differences by eye.
872
        """
873
        # TODO: perhaps override assertEquals to call this for strings?
874
        if a == b:
875
            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.
876
        if message is None:
877
            message = "texts not equal:\n"
2555.3.3 by Martin Pool
Simple lock tracing in LockDir
878
        raise AssertionError(message +
879
                             self._ndiff_strings(a, b))
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
880
        
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.
881
    def assertEqualMode(self, mode, mode_test):
882
        self.assertEqual(mode, mode_test,
883
                         'mode mismatch %o != %o' % (mode, mode_test))
884
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
885
    def assertPositive(self, val):
886
        """Assert that val is greater than 0."""
887
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
888
889
    def assertNegative(self, val):
890
        """Assert that val is less than 0."""
891
        self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
892
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
893
    def assertStartsWith(self, s, prefix):
894
        if not s.startswith(prefix):
895
            raise AssertionError('string %r does not start with %r' % (s, prefix))
896
897
    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.
898
        """Asserts that s ends with suffix."""
899
        if not s.endswith(suffix):
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
900
            raise AssertionError('string %r does not end with %r' % (s, suffix))
1185.16.42 by Martin Pool
- Add assertContainsRe
901
902
    def assertContainsRe(self, haystack, needle_re):
903
        """Assert that a contains something matching a regular expression."""
904
        if not re.search(needle_re, haystack):
2555.3.1 by Martin Pool
Better messages from assertContainsRe
905
            if '\n' in haystack or len(haystack) > 60:
906
                # a long string, format it in a more readable way
907
                raise AssertionError(
908
                        'pattern "%s" not found in\n"""\\\n%s"""\n'
909
                        % (needle_re, haystack))
910
            else:
911
                raise AssertionError('pattern "%s" not found in "%s"'
912
                        % (needle_re, haystack))
1442.1.70 by Robert Collins
Add assertFileEqual to TestCaseInTempDir.
913
1185.84.3 by Aaron Bentley
Hide diffs for old revisions in bundles
914
    def assertNotContainsRe(self, haystack, needle_re):
915
        """Assert that a does not match a regular expression"""
916
        if re.search(needle_re, haystack):
917
            raise AssertionError('pattern "%s" found in "%s"'
918
                    % (needle_re, haystack))
919
1553.5.3 by Martin Pool
[patch] Rename TestCase.AssertSubset to assertSubset for consistency (Jan Hudec)
920
    def assertSubset(self, sublist, superlist):
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
921
        """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)
922
        missing = set(sublist) - set(superlist)
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
923
        if len(missing) > 0:
2695.1.4 by Martin Pool
Much faster assertSubset using sets, not O(n**2)
924
            raise AssertionError("value(s) %r not present in container %r" %
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
925
                                 (missing, superlist))
926
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
927
    def assertListRaises(self, excClass, func, *args, **kwargs):
928
        """Fail unless excClass is raised when the iterator from func is used.
929
        
930
        Many functions can return generators this makes sure
931
        to wrap them in a list() call to make sure the whole generator
932
        is run, and that the proper exception is raised.
933
        """
934
        try:
935
            list(func(*args, **kwargs))
936
        except excClass:
937
            return
938
        else:
939
            if getattr(excClass,'__name__', None) is not None:
940
                excName = excClass.__name__
941
            else:
942
                excName = str(excClass)
943
            raise self.failureException, "%s not raised" % excName
944
2399.1.7 by John Arbash Meinel
Cleanup bzrlib/benchmarks/* so that everything at least has a valid doc string.
945
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
946
        """Assert that a callable raises a particular exception.
947
2323.5.9 by Martin Pool
Clear up assertRaises (r=robert)
948
        :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.
949
            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.
950
        :param callableObj: A callable, will be passed ``*args`` and
951
            ``**kwargs``.
2323.5.9 by Martin Pool
Clear up assertRaises (r=robert)
952
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
953
        Returns the exception so that you can examine it.
954
        """
955
        try:
2399.1.10 by John Arbash Meinel
fix assertRaises to use the right parameter...
956
            callableObj(*args, **kwargs)
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
957
        except excClass, e:
958
            return e
959
        else:
960
            if getattr(excClass,'__name__', None) is not None:
961
                excName = excClass.__name__
962
            else:
2323.5.9 by Martin Pool
Clear up assertRaises (r=robert)
963
                # probably a tuple
2323.5.5 by Martin Pool
override TestCase.assertRaises to return the exception
964
                excName = str(excClass)
965
            raise self.failureException, "%s not raised" % excName
966
2220.1.13 by Marius Kruger
Remove assertNone
967
    def assertIs(self, left, right, message=None):
1185.68.1 by Aaron Bentley
test transactions
968
        if not (left is right):
2220.1.13 by Marius Kruger
Remove assertNone
969
            if message is not None:
970
                raise AssertionError(message)
971
            else:
972
                raise AssertionError("%r is not %r." % (left, right))
973
974
    def assertIsNot(self, left, right, message=None):
975
        if (left is right):
976
            if message is not None:
977
                raise AssertionError(message)
978
            else:
979
                raise AssertionError("%r is %r." % (left, right))
2220.1.4 by Marius Kruger
* bzrlib/tests/__init__
980
1530.1.21 by Robert Collins
Review feedback fixes.
981
    def assertTransportMode(self, transport, path, mode):
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
982
        """Fail if a path does not have mode mode.
983
        
1651.1.3 by Martin Pool
Use transport._can_roundtrip_unix_modebits to decide whether to check transport results
984
        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.
985
        """
1651.1.3 by Martin Pool
Use transport._can_roundtrip_unix_modebits to decide whether to check transport results
986
        if not transport._can_roundtrip_unix_modebits():
1530.1.17 by Robert Collins
Move check_mode to TestCase.assertMode to make it generally accessible.
987
            return
988
        path_stat = transport.stat(path)
989
        actual_mode = stat.S_IMODE(path_stat.st_mode)
990
        self.assertEqual(mode, actual_mode,
991
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
992
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
993
    def assertIsSameRealPath(self, path1, path2):
994
        """Fail if path1 and path2 points to different files"""
2823.1.11 by Vincent Ladeuil
Review feedback.
995
        self.assertEqual(osutils.realpath(path1),
996
                         osutils.realpath(path2),
997
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
998
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
999
    def assertIsInstance(self, obj, kls):
1000
        """Fail if obj is not an instance of kls"""
1001
        if not isinstance(obj, kls):
1666.1.6 by Robert Collins
Make knit the default format.
1002
            self.fail("%r is an instance of %s rather than %s" % (
1003
                obj, obj.__class__, kls))
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
1004
1551.13.10 by Aaron Bentley
Changes from review (poolie)
1005
    def expectFailure(self, reason, assertion, *args, **kwargs):
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1006
        """Invoke a test, expecting it to fail for the given reason.
1007
1551.13.10 by Aaron Bentley
Changes from review (poolie)
1008
        This is for assertions that ought to succeed, but currently fail.
1551.13.11 by Aaron Bentley
Update docs
1009
        (The failure is *expected* but not *wanted*.)  Please be very precise
1010
        about the failure you're expecting.  If a new bug is introduced,
1011
        AssertionError should be raised, not KnownFailure.
1012
1013
        Frequently, expectFailure should be followed by an opposite assertion.
1014
        See example below.
1551.13.10 by Aaron Bentley
Changes from review (poolie)
1015
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1016
        Intended to be used with a callable that raises AssertionError as the
1551.13.10 by Aaron Bentley
Changes from review (poolie)
1017
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1018
1019
        Raises KnownFailure if the test fails.  Raises AssertionError if the
1020
        test succeeds.
1021
1022
        example usage::
1551.13.11 by Aaron Bentley
Update docs
1023
1024
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
1025
                             dynamic_val)
1026
          self.assertEqual(42, dynamic_val)
1027
1028
          This means that a dynamic_val of 54 will cause the test to raise
1029
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
1030
          only a dynamic_val of 42 will allow the test to pass.  Anything other
1031
          than 54 or 42 will cause an AssertionError.
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1032
        """
1033
        try:
1551.13.10 by Aaron Bentley
Changes from review (poolie)
1034
            assertion(*args, **kwargs)
1551.13.9 by Aaron Bentley
Implement TestCase.expectFailure
1035
        except AssertionError:
1036
            raise KnownFailure(reason)
1037
        else:
1038
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1039
3173.1.10 by Martin Pool
Move assertFileEqual to TestCase base class as it's generally usable
1040
    def assertFileEqual(self, content, path):
1041
        """Fail if path does not contain 'content'."""
1042
        self.failUnlessExists(path)
1043
        f = file(path, 'rb')
1044
        try:
1045
            s = f.read()
1046
        finally:
1047
            f.close()
1048
        self.assertEqualDiff(content, s)
1049
3173.1.12 by Martin Pool
Add test_push_log_file
1050
    def failUnlessExists(self, path):
1051
        """Fail unless path or paths, which may be abs or relative, exist."""
1052
        if not isinstance(path, basestring):
1053
            for p in path:
1054
                self.failUnlessExists(p)
1055
        else:
1056
            self.failUnless(osutils.lexists(path),path+" does not exist")
1057
1058
    def failIfExists(self, path):
1059
        """Fail if path or paths, which may be abs or relative, exist."""
1060
        if not isinstance(path, basestring):
1061
            for p in path:
1062
                self.failIfExists(p)
1063
        else:
1064
            self.failIf(osutils.lexists(path),path+" exists")
1065
2592.3.243 by Martin Pool
Rename TestCase._capture_warnings
1066
    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
1067
        """A helper for callDeprecated and applyDeprecated.
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1068
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1069
        :param a_callable: A callable to call.
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1070
        :param args: The positional arguments for the callable
1071
        :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
1072
        :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.
1073
            a_callable(``*args``, ``**kwargs``).
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1074
        """
1075
        local_warnings = []
2067.3.3 by Martin Pool
merge bzr.dev and reconcile several changes, also some test fixes
1076
        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
1077
            # we've hooked into a deprecation specific callpath,
1078
            # only deprecations should getting sent via it.
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1079
            self.assertEqual(cls, DeprecationWarning)
1080
            local_warnings.append(msg)
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1081
        original_warning_method = symbol_versioning.warn
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1082
        symbol_versioning.set_warning_method(capture_warnings)
1083
        try:
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1084
            result = a_callable(*args, **kwargs)
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1085
        finally:
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1086
            symbol_versioning.set_warning_method(original_warning_method)
1087
        return (local_warnings, result)
1088
1089
    def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1090
        """Call a deprecated callable without warning the user.
1091
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1092
        Note that this only captures warnings raised by symbol_versioning.warn,
1093
        not other callers that go direct to the warning module.
1094
2697.2.2 by Martin Pool
deprecate Branch.append_revision
1095
        To test that a deprecated method raises an error, do something like
1096
        this::
1097
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
1098
            self.assertRaises(errors.ReservedId,
1099
                self.applyDeprecated,
1100
                deprecated_in((1, 5, 0)),
1101
                br.append_revision,
1102
                'current:')
2697.2.2 by Martin Pool
deprecate Branch.append_revision
1103
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1104
        :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.
1105
            should have been deprecated with. This is the same type as the
1106
            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
1107
            callable is not deprecated with this format, an assertion error
1108
            will be raised.
1109
        :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.
1110
            a regular function. It will be called with ``*args`` and
1111
            ``**kwargs``.
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1112
        :param args: The positional arguments for the callable
1113
        :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.
1114
        :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
1115
        """
2592.3.243 by Martin Pool
Rename TestCase._capture_warnings
1116
        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
1117
            *args, **kwargs)
1118
        expected_first_warning = symbol_versioning.deprecation_string(
1119
            a_callable, deprecation_format)
1120
        if len(call_warnings) == 0:
2255.7.47 by Robert Collins
Improve applyDeprecated warning message.
1121
            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
1122
                a_callable)
1123
        self.assertEqual(expected_first_warning, call_warnings[0])
1124
        return result
1125
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1126
    def callCatchWarnings(self, fn, *args, **kw):
1127
        """Call a callable that raises python warnings.
1128
1129
        The caller's responsible for examining the returned warnings.
1130
1131
        If the callable raises an exception, the exception is not
1132
        caught and propagates up to the caller.  In that case, the list
1133
        of warnings is not available.
1134
1135
        :returns: ([warning_object, ...], fn_result)
1136
        """
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1137
        # XXX: This is not perfect, because it completely overrides the
1138
        # warnings filters, and some code may depend on suppressing particular
1139
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
1140
        # though.  -- Andrew, 20071062
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1141
        wlist = []
1142
        def _catcher(message, category, filename, lineno, file=None):
1143
            # despite the name, 'message' is normally(?) a Warning subclass
1144
            # instance
1145
            wlist.append(message)
1146
        saved_showwarning = warnings.showwarning
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1147
        saved_filters = warnings.filters
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1148
        try:
1149
            warnings.showwarning = _catcher
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1150
            warnings.filters = []
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1151
            result = fn(*args, **kw)
1152
        finally:
1153
            warnings.showwarning = saved_showwarning
2592.3.246 by Andrew Bennetts
Override warnings.filters in callCatchWarnings, to insulate it from -Werror.
1154
            warnings.filters = saved_filters
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1155
        return wlist, result
1156
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1157
    def callDeprecated(self, expected, callable, *args, **kwargs):
1158
        """Assert that a callable is deprecated in a particular way.
1159
1160
        This is a very precise test for unusual requirements. The 
1161
        applyDeprecated helper function is probably more suited for most tests
1162
        as it allows you to simply specify the deprecation format being used
1163
        and will ensure that that is issued for the function being called.
1164
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1165
        Note that this only captures warnings raised by symbol_versioning.warn,
2592.3.242 by Martin Pool
New method TestCase.call_catch_warnings
1166
        not other callers that go direct to the warning module.  To catch
1167
        general warnings, use callCatchWarnings.
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1168
1982.3.2 by Robert Collins
New TestCase helper applyDeprecated. This allows you to call a callable
1169
        :param expected: a list of the deprecation warnings expected, in order
1170
        :param callable: The callable to call
1171
        :param args: The positional arguments for the callable
1172
        :param kwargs: The keyword arguments for the callable
1173
        """
2592.3.243 by Martin Pool
Rename TestCase._capture_warnings
1174
        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
1175
            *args, **kwargs)
1176
        self.assertEqual(expected, call_warnings)
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
1177
        return result
1178
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
1179
    def _startLogFile(self):
1180
        """Send bzr and test log messages to a temporary file.
1181
1182
        The file is removed as the test is torn down.
1183
        """
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1184
        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
1185
        self._log_file = os.fdopen(fileno, 'w+')
3173.1.9 by Martin Pool
tests should now call push/pop_test_log
1186
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1187
        self._log_file_name = name
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
1188
        self.addCleanup(self._finishLogFile)
1189
1190
    def _finishLogFile(self):
1191
        """Finished with the log file.
1192
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1193
        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.
1194
        """
1711.7.10 by John Arbash Meinel
Nothing to clean up if self._log_file is None
1195
        if self._log_file is None:
1196
            return
3173.1.9 by Martin Pool
tests should now call push/pop_test_log
1197
        bzrlib.trace.pop_log_file(self._log_memento)
1185.16.122 by Martin Pool
[patch] Close test log file before deleting, needed on Windows
1198
        self._log_file.close()
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1199
        self._log_file = None
2024.2.9 by John Arbash Meinel
Bring back log deletions
1200
        if not self._keep_log_file:
1201
            os.remove(self._log_file_name)
1202
            self._log_file_name = None
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1203
1204
    def setKeepLogfile(self):
1205
        """Make the logfile not be deleted when _finishLogFile is called."""
1206
        self._keep_log_file = True
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1207
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
1208
    def addCleanup(self, callable):
1209
        """Arrange to run a callable when this case is torn down.
1210
1211
        Callables are run in the reverse of the order they are registered, 
1212
        ie last-in first-out.
1213
        """
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
1214
        if callable in self._cleanups:
1215
            raise ValueError("cleanup function %r already registered on %s" 
1216
                    % (callable, self))
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
1217
        self._cleanups.append(callable)
1218
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
1219
    def _cleanEnvironment(self):
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
1220
        new_env = {
2055.1.2 by John Arbash Meinel
Clean up BZR_HOME in ENV for the test suite
1221
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
1222
            'HOME': os.getcwd(),
2309.2.6 by Alexander Belchenko
bzr now use Win32 API to determine Application Data location, and don't rely solely on $APPDATA
1223
            'APPDATA': None,  # bzr now use Win32 API and don't rely on APPDATA
2839.6.2 by Alexander Belchenko
changes after Martin's review
1224
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1225
            'BZR_EMAIL': None,
1912.2.1 by Adeodato Simó
Clear $BZREMAIL in tests, not only the newer $BZR_EMAIL, since the
1226
            'BZREMAIL': None, # may still be present in the environment
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
1227
            'EMAIL': None,
1963.1.6 by John Arbash Meinel
Use the new helper function in a few places
1228
            'BZR_PROGRESS_BAR': None,
3193.6.1 by Alexander Belchenko
``BZR_LOG=disable`` suppresses writing messages to .bzr.log.
1229
            'BZR_LOG': None,
2617.2.1 by Jelmer Vernooij
Sanitize SSH_AUTH_SOCK environment variable (#125955).
1230
            # SSH Agent
1231
            'SSH_AUTH_SOCK': None,
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
1232
            # Proxies
1233
            'http_proxy': None,
1234
            'HTTP_PROXY': None,
1235
            'https_proxy': None,
1236
            'HTTPS_PROXY': None,
1237
            'no_proxy': None,
1238
            'NO_PROXY': None,
1239
            'all_proxy': None,
1240
            'ALL_PROXY': None,
1241
            # Nobody cares about these ones AFAIK. So far at
1242
            # least. If you do (care), please update this comment
1243
            # -- vila 20061212
1244
            'ftp_proxy': None,
1245
            '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.
1246
            'BZR_REMOTE_PATH': None,
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
1247
        }
1185.38.4 by John Arbash Meinel
Making old_env a private member
1248
        self.__old_env = {}
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
1249
        self.addCleanup(self._restoreEnvironment)
1185.38.3 by John Arbash Meinel
Refactored environment cleaning code
1250
        for name, value in new_env.iteritems():
1251
            self._captureVar(name, value)
1252
1253
    def _captureVar(self, name, newvalue):
1963.1.6 by John Arbash Meinel
Use the new helper function in a few places
1254
        """Set an environment variable, and reset it when finished."""
1255
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1185.38.2 by John Arbash Meinel
[patch] Aaron Bentley's HOME fix.
1256
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1257
    def _restore_debug_flags(self):
2560.1.3 by Robert Collins
Allow 'from debug import debug_flags'
1258
        debug.debug_flags.clear()
1259
        debug.debug_flags.update(self._preserved_debug_flags)
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1260
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
1261
    def _restoreEnvironment(self):
1185.38.4 by John Arbash Meinel
Making old_env a private member
1262
        for name, value in self.__old_env.iteritems():
1963.1.6 by John Arbash Meinel
Use the new helper function in a few places
1263
            osutils.set_or_unset_env(name, value)
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
1264
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1265
    def _restoreHooks(self):
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
1266
        for klass, hooks in self._preserved_hooks.items():
1267
            setattr(klass, 'hooks', hooks)
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1268
2367.1.2 by Robert Collins
Some minor cleanups of test code, and implement KnownFailure support as
1269
    def knownFailure(self, reason):
1270
        """This test has failed for some known reason."""
1271
        raise KnownFailure(reason)
1272
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1273
    def run(self, result=None):
1274
        if result is None: result = self.defaultTestResult()
1275
        for feature in getattr(self, '_test_needs_features', []):
1276
            if not feature.available():
1277
                result.startTest(self)
1278
                if getattr(result, 'addNotSupported', None):
1279
                    result.addNotSupported(self, feature)
1280
                else:
1281
                    result.addSuccess(self)
1282
                result.stopTest(self)
1283
                return
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1284
        try:
1285
            return unittest.TestCase.run(self, result)
1286
        finally:
1287
            saved_attrs = {}
3224.4.3 by Andrew Bennetts
Rename 'not_found' marker to 'absent_attr'.
1288
            absent_attr = object()
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1289
            for attr_name in self.attrs_to_keep:
3224.4.3 by Andrew Bennetts
Rename 'not_found' marker to 'absent_attr'.
1290
                attr = getattr(self, attr_name, absent_attr)
1291
                if attr is not absent_attr:
3224.4.1 by Andrew Bennetts
Prune __dict__ of TestCases after they have run to save memory.
1292
                    saved_attrs[attr_name] = attr
1293
            self.__dict__ = saved_attrs
2367.1.3 by Robert Collins
Add support for calling addNotSupported on TestResults to bzr TestCase's
1294
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
1295
    def tearDown(self):
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
1296
        self._runCleanups()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1297
        unittest.TestCase.tearDown(self)
1298
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)
1299
    def time(self, callable, *args, **kwargs):
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1300
        """Run callable and accrue the time it takes to the benchmark time.
1301
        
1302
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1303
        this will cause lsprofile statistics to be gathered and stored in
1304
        self._benchcalls.
1305
        """
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)
1306
        if self._benchtime is None:
1307
            self._benchtime = 0
1308
        start = time.time()
1309
        try:
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
1310
            if not self._gather_lsprof_in_benchmarks:
1311
                return callable(*args, **kwargs)
1312
            else:
1313
                # record this benchmark
1314
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
1315
                stats.sort()
1316
                self._benchcalls.append(((callable, args, kwargs), stats))
1317
                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)
1318
        finally:
1319
            self._benchtime += time.time() - start
1320
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
1321
    def _runCleanups(self):
1322
        """Run registered cleanup functions. 
1323
1324
        This should only be called from TestCase.tearDown.
1325
        """
1541 by Martin Pool
doc
1326
        # TODO: Perhaps this should keep running cleanups even if 
1327
        # 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.
1328
1329
        # Actually pop the cleanups from the list so tearDown running
1330
        # twice is safe (this happens for skipped tests).
1331
        while self._cleanups:
1332
            self._cleanups.pop()()
1185.16.108 by mbp at sourcefrog
Add TestCase.addCleanup method.
1333
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1334
    def log(self, *args):
1185.43.1 by Martin Pool
Remove direct logging calls from selftest
1335
        mutter(*args)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1336
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1337
    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.
1338
        """Get the log from bzrlib.trace calls from this test.
1339
1340
        :param keep_log_file: When True, if the log is still a file on disk
1341
            leave it as a file on disk. When False, if the log is still a file
1342
            on disk, the log file is deleted and the log preserved as
1343
            self._log_contents.
1344
        :return: A string containing the log.
1345
        """
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1346
        # flush the log file, to get all content
1347
        import bzrlib.trace
1348
        bzrlib.trace._trace_file.flush()
1349
        if self._log_contents:
3199.1.1 by Vincent Ladeuil
Get rid of ~1000 useless log files out of 10.000 tests in /tmp.
1350
            # XXX: this can hardly contain the content flushed above --vila
1351
            # 20080128
1185.16.109 by mbp at sourcefrog
Clean up test log files when tests complete.
1352
            return self._log_contents
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1353
        if self._log_file_name is not None:
1354
            logfile = open(self._log_file_name)
1355
            try:
1356
                log_contents = logfile.read()
1357
            finally:
1358
                logfile.close()
1359
            if not keep_log_file:
1360
                self._log_contents = log_contents
2309.2.7 by Alexander Belchenko
Skip permission denied (on win32) during selftest cleanup
1361
                try:
1362
                    os.remove(self._log_file_name)
1363
                except OSError, e:
1364
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1365
                        sys.stderr.write(('Unable to delete log file '
1366
                                             ' %r\n' % self._log_file_name))
2309.2.7 by Alexander Belchenko
Skip permission denied (on win32) during selftest cleanup
1367
                    else:
1368
                        raise
1927.3.1 by Carl Friedrich Bolz
Throw away on-disk logfile when possible.
1369
            return log_contents
1370
        else:
1371
            return "DELETED log file to reduce memory footprint"
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1372
2367.1.6 by Robert Collins
Allow per-test-fixture feature requirements via 'requireFeature'.(Robert Collins)
1373
    def requireFeature(self, feature):
1374
        """This test requires a specific feature is available.
1375
1376
        :raises UnavailableFeature: When feature is not available.
1377
        """
1378
        if not feature.available():
1379
            raise UnavailableFeature(feature)
1380
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1381
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1382
            working_dir):
2530.3.3 by Martin Pool
Clean up some callers that use varargs syntax for run_bzr, but don't
1383
        """Run bazaar command line, splitting up a string command line."""
1384
        if isinstance(args, basestring):
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
1385
            # shlex don't understand unicode strings,
1386
            # so args should be plain string (bialix 20070906)
1387
            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
1388
        return self._run_bzr_core(args, retcode=retcode,
1389
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1390
                )
1391
1392
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1393
            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
1394
        if encoding is None:
1395
            encoding = bzrlib.user_encoding
1396
        stdout = StringIOWrapper()
1397
        stderr = StringIOWrapper()
1398
        stdout.encoding = encoding
1399
        stderr.encoding = encoding
1400
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1401
        self.log('run bzr: %r', args)
1185.43.5 by Martin Pool
Update log message quoting
1402
        # FIXME: don't call into logging here
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
1403
        handler = logging.StreamHandler(stderr)
1404
        handler.setLevel(logging.INFO)
1405
        logger = logging.getLogger('')
1406
        logger.addHandler(handler)
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
1407
        old_ui_factory = ui.ui_factory
1408
        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
1409
1410
        cwd = None
1411
        if working_dir is not None:
1412
            cwd = osutils.getcwd()
1413
            os.chdir(working_dir)
1414
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
1415
        try:
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1416
            result = self.apply_redirected(ui.ui_factory.stdin,
1417
                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
1418
                bzrlib.commands.run_bzr_catch_user_errors,
2560.1.1 by Robert Collins
Make debug.debug_flags be isolated for all tests.
1419
                args)
1185.3.20 by Martin Pool
- run_bzr_captured also includes logged errors in
1420
        finally:
1421
            logger.removeHandler(handler)
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
1422
            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
1423
            if cwd is not None:
1424
                os.chdir(cwd)
1685.1.69 by Wouter van Heyst
merge bzr.dev 1740
1425
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1426
        out = stdout.getvalue()
1427
        err = stderr.getvalue()
1428
        if out:
1185.85.72 by John Arbash Meinel
Fix some of the tests.
1429
            self.log('output:\n%r', out)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1430
        if err:
1185.85.72 by John Arbash Meinel
Fix some of the tests.
1431
            self.log('errors:\n%r', err)
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1432
        if retcode is not None:
2292.1.32 by Marius Kruger
* tests/__init__.run_bzr
1433
            self.assertEquals(retcode, result,
1434
                              message='Unexpected return code')
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1435
        return out, err
1436
2830.2.5 by Martin Pool
Deprecated ``run_bzr_decode``; use the new ``output_encoding`` parameter to
1437
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1438
                working_dir=None, error_regexes=[], output_encoding=None):
1119 by Martin Pool
doc
1439
        """Invoke bzr, as if it were run from the command line.
1440
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1441
        The argument list should not include the bzr program name - the
1442
        first argument is normally the bzr command.  Arguments may be
1443
        passed in three ways:
1444
1445
        1- A list of strings, eg ["commit", "a"].  This is recommended
1446
        when the command contains whitespace or metacharacters, or 
1447
        is built up at run time.
1448
1449
        2- A single string, eg "add a".  This is the most convenient 
1450
        for hardcoded commands.
1451
2530.3.4 by Martin Pool
Deprecate run_bzr_captured in favour of just run_bzr
1452
        This runs bzr through the interface that catches and reports
1453
        errors, and with logging set to something approximating the
1454
        default, so that error reporting can be checked.
1455
1119 by Martin Pool
doc
1456
        This should be the main method for tests that want to exercise the
1457
        overall behavior of the bzr application (rather than a unit test
1458
        or a functional test of the library.)
1459
1185.3.18 by Martin Pool
- add new helper TestBase.run_bzr_captured
1460
        This sends the stdout/stderr results into the test's log,
1461
        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.
1462
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1463
        :keyword stdin: A string to be used as stdin for the command.
2399.1.17 by John Arbash Meinel
[merge] bzr.dev 2562
1464
        :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.
1465
            default 0.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1466
        :keyword working_dir: The directory to run the command in
2399.1.17 by John Arbash Meinel
[merge] bzr.dev 2562
1467
        :keyword error_regexes: A list of expected error messages.  If
1468
            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
1469
        """
2830.2.5 by Martin Pool
Deprecated ``run_bzr_decode``; use the new ``output_encoding`` parameter to
1470
        out, err = self._run_bzr_autosplit(
1471
            args=args,
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1472
            retcode=retcode,
2830.2.5 by Martin Pool
Deprecated ``run_bzr_decode``; use the new ``output_encoding`` parameter to
1473
            encoding=encoding,
1474
            stdin=stdin,
1475
            working_dir=working_dir,
2530.3.2 by Martin Pool
Refactoring run_bzr code into more of a common base.
1476
            )
2292.1.27 by Marius Kruger
* tests/__init__.TestCase.run_bzr_captured
1477
        for regex in error_regexes:
1478
            self.assertContainsRe(err, regex)
1479
        return out, err
1480
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.
1481
    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
1482
        """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.
1483
1484
        :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.
1485
            must each be found in the error output. The relative ordering
1486
            is not enforced.
1487
        :param args: command-line arguments for bzr
1488
        :param kwargs: Keyword arguments which are interpreted by run_bzr
1489
            This function changes the default value of retcode to be 3,
1490
            since in most cases this is run when you expect bzr to fail.
2581.1.1 by Martin Pool
Merge more runbzr cleanups
1491
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1492
        :return: (out, err) The actual output of running the command (in case
1493
            you want to do more inspection)
1494
1495
        Examples of use::
1496
1711.7.11 by John Arbash Meinel
Clean up the documentation for run_bzr_error on Martin's suggestion.
1497
            # Make sure that commit is failing because there is nothing to do
1498
            self.run_bzr_error(['no changes to commit'],
2665.1.1 by Michael Hudson
make run_bzr stricter about the keyword arguments it takes.
1499
                               ['commit', '-m', 'my commit comment'])
1711.7.11 by John Arbash Meinel
Clean up the documentation for run_bzr_error on Martin's suggestion.
1500
            # Make sure --strict is handling an unknown file, rather than
1501
            # giving us the 'nothing to do' error
1502
            self.build_tree(['unknown'])
1503
            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.
1504
                               ['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
1505
        """
1506
        kwargs.setdefault('retcode', 3)
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
1507
        kwargs['error_regexes'] = error_regexes
1508
        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
1509
        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.
1510
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
1511
    def run_bzr_subprocess(self, *args, **kwargs):
1512
        """Run bzr in a subprocess for testing.
1513
1514
        This starts a new Python interpreter and runs bzr in there. 
1515
        This should only be used for tests that have a justifiable need for
1516
        this isolation: e.g. they are testing startup time, or signal
1517
        handling, or early startup code, etc.  Subprocess code can't be 
1518
        profiled or debugged so easily.
1752.1.7 by Aaron Bentley
Stop using shlex in run_bzr_subprocess
1519
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1520
        :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
1521
            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.
1522
        :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
1523
            variables. A value of None will unset the env variable.
1524
            The values must be strings. The change will only occur in the
1525
            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.
1526
        :keyword universal_newlines: Convert CRLF => LF
1527
        :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.
1528
            --no-plugins to ensure test reproducibility. Also, it is possible
2067.2.2 by John Arbash Meinel
Review comments from Robert
1529
            for system-wide plugins to create unexpected output on stderr,
1530
            which can cause unnecessary test failures.
1752.1.6 by Aaron Bentley
Rename run_bzr_external -> run_bzr_subprocess, add docstring
1531
        """
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
1532
        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
1533
        working_dir = kwargs.get('working_dir', None)
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
1534
        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
1535
        if len(args) == 1:
1536
            if isinstance(args[0], list):
1537
                args = args[0]
1538
            elif isinstance(args[0], basestring):
1539
                args = list(shlex.split(args[0]))
1540
        else:
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
1541
            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
1542
        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.
1543
                                            working_dir=working_dir,
1544
                                            allow_plugins=allow_plugins)
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
1545
        # We distinguish between retcode=None and retcode not passed.
1546
        supplied_retcode = kwargs.get('retcode', 0)
1547
        return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
1548
            universal_newlines=kwargs.get('universal_newlines', False),
1549
            process_args=args)
1550
1910.17.9 by Andrew Bennetts
Add skip_if_plan_to_signal flag to start_bzr_subprocess.
1551
    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
1552
                             skip_if_plan_to_signal=False,
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
1553
                             working_dir=None,
1554
                             allow_plugins=False):
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
1555
        """Start bzr in a subprocess for testing.
1556
1557
        This starts a new Python interpreter and runs bzr in there.
1558
        This should only be used for tests that have a justifiable need for
1559
        this isolation: e.g. they are testing startup time, or signal
1560
        handling, or early startup code, etc.  Subprocess code can't be
1561
        profiled or debugged so easily.
1562
1563
        :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.
1564
            for example ``['--version']``.
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
1565
        :param env_changes: A dictionary which lists changes to environment
1566
            variables. A value of None will unset the env variable.
1567
            The values must be strings. The change will only occur in the
1568
            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.
1569
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1570
            is not available.
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
1571
        :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.
1572
1573
        :returns: Popen object for the started process.
1574
        """
1910.17.9 by Andrew Bennetts
Add skip_if_plan_to_signal flag to start_bzr_subprocess.
1575
        if skip_if_plan_to_signal:
1576
            if not getattr(os, 'kill', None):
1577
                raise TestSkipped("os.kill not available.")
1578
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
1579
        if env_changes is None:
1580
            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
1581
        old_env = {}
1582
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
1583
        def cleanup_environment():
1584
            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
1585
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1586
1587
        def restore_environment():
1588
            for env_var, value in old_env.iteritems():
1589
                osutils.set_or_unset_env(env_var, value)
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
1590
2018.1.1 by Andrew Bennetts
Make bzr+ssh:// actually work (at least with absolute paths).
1591
        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
1592
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
1593
        cwd = None
1594
        if working_dir is not None:
1595
            cwd = osutils.getcwd()
1596
            os.chdir(working_dir)
1597
1963.1.7 by John Arbash Meinel
Switch to directly setting the env, and cleaning it up. So that it works on all platforms
1598
        try:
1599
            # win32 subprocess doesn't support preexec_fn
1600
            # so we will avoid using it on all platforms, just to
1601
            # make sure the code path is used, and we don't break on win32
1602
            cleanup_environment()
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
1603
            command = [sys.executable, bzr_path]
1604
            if not allow_plugins:
1605
                command.append('--no-plugins')
1606
            command.extend(process_args)
1607
            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
1608
        finally:
1609
            restore_environment()
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
1610
            if cwd is not None:
1611
                os.chdir(cwd)
1612
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
1613
        return process
1614
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
1615
    def _popen(self, *args, **kwargs):
1616
        """Place a call to Popen.
2067.2.2 by John Arbash Meinel
Review comments from Robert
1617
1618
        Allows tests to override this method to intercept the calls made to
1619
        Popen for introspection.
2067.2.1 by John Arbash Meinel
Change run_bzr_subprocess to default to supplying --no-plugins.
1620
        """
1621
        return Popen(*args, **kwargs)
1622
2018.1.1 by Andrew Bennetts
Make bzr+ssh:// actually work (at least with absolute paths).
1623
    def get_bzr_path(self):
2018.1.9 by Andrew Bennetts
Implement ParamikoVendor.connect_ssh
1624
        """Return the path of the 'bzr' executable for this test suite."""
2018.1.1 by Andrew Bennetts
Make bzr+ssh:// actually work (at least with absolute paths).
1625
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
1626
        if not os.path.isfile(bzr_path):
1627
            # We are probably installed. Assume sys.argv is the right file
1628
            bzr_path = sys.argv[0]
1629
        return bzr_path
1630
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
1631
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
1632
                              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
1633
        """Finish the execution of process.
1634
1635
        :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.
1636
        :param retcode: The status code that is expected.  Defaults to 0.  If
1637
            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
1638
        :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.
1639
        :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
1640
        :returns: (stdout, stderr)
1641
        """
1642
        if send_signal is not None:
1643
            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.
1644
        out, err = process.communicate()
1645
1646
        if universal_newlines:
1647
            out = out.replace('\r\n', '\n')
1648
            err = err.replace('\r\n', '\n')
1649
1650
        if retcode is not None and retcode != process.returncode:
1651
            if process_args is None:
1652
                process_args = "(unknown args)"
1653
            mutter('Output of bzr %s:\n%s', process_args, out)
1654
            mutter('Error for bzr %s:\n%s', process_args, err)
1655
            self.fail('Command bzr %s failed with retcode %s != %s'
1656
                      % (process_args, retcode, process.returncode))
1657
        return [out, err]
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
1658
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1659
    def check_inventory_shape(self, inv, shape):
1291 by Martin Pool
- add test for moving files between directories
1660
        """Compare an inventory to a list of expected names.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1661
1662
        Fail if they are not precisely equal.
1663
        """
1664
        extras = []
1665
        shape = list(shape)             # copy
1666
        for path, ie in inv.entries():
1667
            name = path.replace('\\', '/')
2545.3.1 by James Westby
Fix detection of directory entries in the inventory.
1668
            if ie.kind == 'directory':
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1669
                name = name + '/'
1670
            if name in shape:
1671
                shape.remove(name)
1672
            else:
1673
                extras.append(name)
1674
        if shape:
1675
            self.fail("expected paths not found in inventory: %r" % shape)
1676
        if extras:
1677
            self.fail("unexpected paths found in inventory: %r" % extras)
1678
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
1679
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
1680
                         a_callable=None, *args, **kwargs):
1681
        """Call callable with redirected std io pipes.
1682
1683
        Returns the return code."""
1684
        if not callable(a_callable):
1685
            raise ValueError("a_callable must be callable.")
1686
        if stdin is None:
1687
            stdin = StringIO("")
1688
        if stdout is None:
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
1689
            if getattr(self, "_log_file", None) is not None:
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
1690
                stdout = self._log_file
1691
            else:
1692
                stdout = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
1693
        if stderr is None:
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
1694
            if getattr(self, "_log_file", None is not None):
974.1.70 by Aaron Bentley
Fixed selftest spewage (Brian M. Carlson)
1695
                stderr = self._log_file
1696
            else:
1697
                stderr = StringIO()
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
1698
        real_stdin = sys.stdin
1699
        real_stdout = sys.stdout
1700
        real_stderr = sys.stderr
1701
        try:
1702
            sys.stdout = stdout
1703
            sys.stderr = stderr
1704
            sys.stdin = stdin
1160 by Martin Pool
- tiny refactoring
1705
            return a_callable(*args, **kwargs)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
1706
        finally:
1707
            sys.stdout = real_stdout
1708
            sys.stderr = real_stderr
1709
            sys.stdin = real_stdin
1710
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1711
    def reduceLockdirTimeout(self):
1712
        """Reduce the default lock timeout for the duration of the test, so that
1713
        if LockContention occurs during a test, it does so quickly.
1714
1715
        Tests that expect to provoke LockContention errors should call this.
1716
        """
1717
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
1718
        def resetTimeout():
1719
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
1720
        self.addCleanup(resetTimeout)
1721
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
1722
2717.1.1 by Lukáš Lalinsky
Use UTF-8 encoded StringIO for log tests to avoid failures on non-ASCII committer names.
1723
    def make_utf8_encoded_stringio(self, encoding_type=None):
1724
        """Return a StringIOWrapper instance, that will encode Unicode
1725
        input to UTF-8.
1726
        """
1727
        if encoding_type is None:
1728
            encoding_type = 'strict'
1729
        sio = StringIO()
1730
        output_encoding = 'utf-8'
1731
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
1732
        sio.encoding = output_encoding
1733
        return sio
1734
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1735
1736
class TestCaseWithMemoryTransport(TestCase):
1737
    """Common test class for tests that do not need disk resources.
1738
1739
    Tests that need disk resources should derive from TestCaseWithTransport.
1740
1741
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
1742
1743
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
1744
    a directory which does not exist. This serves to help ensure test isolation
1745
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
1746
    must exist. However, TestCaseWithMemoryTransport does not offer local
1747
    file defaults for the transport in tests, nor does it obey the command line
1748
    override, so tests that accidentally write to the common directory should
1749
    be rare.
2485.6.6 by Martin Pool
Put test root directory (containing per-test directories) in TMPDIR
1750
1751
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
1752
    a .bzr directory that stops us ascending higher into the filesystem.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1753
    """
1754
1755
    TEST_ROOT = None
1756
    _TEST_NAME = 'test'
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1757
1986.2.5 by Robert Collins
Unbreak transport tests.
1758
    def __init__(self, methodName='runTest'):
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
1759
        # allow test parameterization after test construction and before test
1760
        # execution. Variables that the parameterizer sets need to be 
1986.2.5 by Robert Collins
Unbreak transport tests.
1761
        # ones that are not set by setUp, or setUp will trash them.
1762
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1763
        self.vfs_transport_factory = default_transport
1764
        self.transport_server = None
1986.2.5 by Robert Collins
Unbreak transport tests.
1765
        self.transport_readonly_server = None
2018.5.44 by Andrew Bennetts
Small changes to help a couple more tests pass.
1766
        self.__vfs_server = None
1986.2.5 by Robert Collins
Unbreak transport tests.
1767
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
1768
    def get_transport(self, relpath=None):
1769
        """Return a writeable transport.
1770
1771
        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.
1772
        "self._test_root"
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
1773
        
1774
        :param relpath: a path relative to the base url.
1775
        """
1776
        t = get_transport(self.get_url(relpath))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1777
        self.assertFalse(t.is_readonly())
1778
        return t
1779
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
1780
    def get_readonly_transport(self, relpath=None):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1781
        """Return a readonly transport for the test scratch space
1782
        
1783
        This can be used to test that operations which should only need
1784
        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.
1785
1786
        :param relpath: a path relative to the base url.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1787
        """
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
1788
        t = get_transport(self.get_readonly_url(relpath))
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1789
        self.assertTrue(t.is_readonly())
1790
        return t
1791
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
1792
    def create_transport_readonly_server(self):
1793
        """Create a transport server from class defined at init.
1794
2145.1.1 by mbp at sourcefrog
merge urllib keepalive etc
1795
        This is mostly a hook for daughter classes.
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
1796
        """
1797
        return self.transport_readonly_server()
1798
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1799
    def get_readonly_server(self):
1800
        """Get the server instance for the readonly transport
1801
1802
        This is useful for some tests with specific servers to do diagnostics.
1803
        """
1804
        if self.__readonly_server is None:
1805
            if self.transport_readonly_server is None:
1806
                # readonly decorator requested
1807
                # bring up the server
1808
                self.__readonly_server = ReadonlyServer()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1809
                self.__readonly_server.setUp(self.get_vfs_only_server())
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1810
            else:
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
1811
                self.__readonly_server = self.create_transport_readonly_server()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1812
                self.__readonly_server.setUp(self.get_vfs_only_server())
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1813
            self.addCleanup(self.__readonly_server.tearDown)
1814
        return self.__readonly_server
1815
1816
    def get_readonly_url(self, relpath=None):
1817
        """Get a URL for the readonly transport.
1818
1819
        This will either be backed by '.' or a decorator to the transport 
1820
        used by self.get_url()
1821
        relpath provides for clients to get a path relative to the base url.
1822
        These should only be downwards relative, not upwards.
1823
        """
1824
        base = self.get_readonly_server().get_url()
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
1825
        return self._adjust_url(base, relpath)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1826
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1827
    def get_vfs_only_server(self):
2018.5.44 by Andrew Bennetts
Small changes to help a couple more tests pass.
1828
        """Get the vfs only read/write server instance.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1829
1830
        This is useful for some tests with specific servers that need
1831
        diagnostics.
1832
1833
        For TestCaseWithMemoryTransport this is always a MemoryServer, and there
1834
        is no means to override it.
1835
        """
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1836
        if self.__vfs_server is None:
1837
            self.__vfs_server = MemoryServer()
1838
            self.__vfs_server.setUp()
1839
            self.addCleanup(self.__vfs_server.tearDown)
1840
        return self.__vfs_server
1841
1842
    def get_server(self):
1843
        """Get the read/write server instance.
1844
1845
        This is useful for some tests with specific servers that need
1846
        diagnostics.
1847
1848
        This is built from the self.transport_server factory. If that is None,
1849
        then the self.get_vfs_server is returned.
1850
        """
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1851
        if self.__server is None:
2381.1.1 by Robert Collins
Split out hpss test fixes which dont depend on new or altered API's.
1852
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1853
                return self.get_vfs_only_server()
1854
            else:
1855
                # bring up a decorated means of access to the vfs only server.
1856
                self.__server = self.transport_server()
2381.1.1 by Robert Collins
Split out hpss test fixes which dont depend on new or altered API's.
1857
                try:
1858
                    self.__server.setUp(self.get_vfs_only_server())
1859
                except TypeError, e:
1860
                    # This should never happen; the try:Except here is to assist
1861
                    # developers having to update code rather than seeing an
1862
                    # uninformative TypeError.
1863
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1864
            self.addCleanup(self.__server.tearDown)
1865
        return self.__server
1866
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1867
    def _adjust_url(self, base, relpath):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1868
        """Get a URL (or maybe a path) for the readwrite transport.
1869
1870
        This will either be backed by '.' or to an equivalent non-file based
1871
        facility.
1872
        relpath provides for clients to get a path relative to the base url.
1873
        These should only be downwards relative, not upwards.
1874
        """
1875
        if relpath is not None and relpath != '.':
1876
            if not base.endswith('/'):
1877
                base = base + '/'
1878
            # XXX: Really base should be a url; we did after all call
1879
            # get_url()!  But sometimes it's just a path (from
1880
            # LocalAbspathServer), and it'd be wrong to append urlescaped data
1881
            # to a non-escaped local path.
1882
            if base.startswith('./') or base.startswith('/'):
1883
                base += relpath
1884
            else:
1885
                base += urlutils.escape(relpath)
1886
        return base
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1887
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1888
    def get_url(self, relpath=None):
1889
        """Get a URL (or maybe a path) for the readwrite transport.
1890
1891
        This will either be backed by '.' or to an equivalent non-file based
1892
        facility.
1893
        relpath provides for clients to get a path relative to the base url.
1894
        These should only be downwards relative, not upwards.
1895
        """
1896
        base = self.get_server().get_url()
1897
        return self._adjust_url(base, relpath)
1898
1899
    def get_vfs_only_url(self, relpath=None):
1900
        """Get a URL (or maybe a path for the plain old vfs transport.
1901
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1902
        This will never be a smart protocol.  It always has all the
1903
        capabilities of the local filesystem, but it might actually be a
1904
        MemoryTransport or some other similar virtual filesystem.
1905
2399.1.16 by John Arbash Meinel
[merge] bzr.dev 2466
1906
        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
1907
        get_url and get_readonly_url.
2399.1.6 by John Arbash Meinel
Cleanup bzrlib/tests/__init__.py so that epydoc doesn't complain.
1908
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1909
        :param relpath: provides for clients to get a path relative to the base
1910
            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.
1911
        :return: A URL
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
1912
        """
1913
        base = self.get_vfs_only_server().get_url()
1914
        return self._adjust_url(base, relpath)
1915
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
1916
    def _create_safety_net(self):
1917
        """Make a fake bzr directory.
1918
2875.1.1 by Vincent Ladeuil
Fix #147986 by monitoring a safety .bzr directory.
1919
        This prevents any tests propagating up onto the TEST_ROOT directory's
1920
        real branch.
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
1921
        """
1922
        root = TestCaseWithMemoryTransport.TEST_ROOT
1923
        bzrdir.BzrDir.create_standalone_workingtree(root)
1924
1925
    def _check_safety_net(self):
1926
        """Check that the safety .bzr directory have not been touched.
1927
1928
        _make_test_root have created a .bzr directory to prevent tests from
1929
        propagating. This method ensures than a test did not leaked.
1930
        """
1931
        root = TestCaseWithMemoryTransport.TEST_ROOT
1932
        wt = workingtree.WorkingTree.open(root)
1933
        last_rev = wt.last_revision()
1934
        if last_rev != 'null:':
1935
            # The current test have modified the /bzr directory, we need to
1936
            # recreate a new one or all the followng tests will fail.
1937
            # If you need to inspect its content uncomment the following line
1938
            # import pdb; pdb.set_trace()
1939
            _rmtree_temp_dir(root + '/.bzr')
1940
            self._create_safety_net()
1941
            raise AssertionError('%s/.bzr should not be modified' % root)
1942
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
1943
    def _make_test_root(self):
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
1944
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
2875.1.1 by Vincent Ladeuil
Fix #147986 by monitoring a safety .bzr directory.
1945
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2817.5.1 by Vincent Ladeuil
Catch leaking tests.
1946
            TestCaseWithMemoryTransport.TEST_ROOT = root
1947
1948
            self._create_safety_net()
1949
1950
            # The same directory is used by all tests, and we're not
1951
            # specifically told when all tests are finished.  This will do.
1952
            atexit.register(_rmtree_temp_dir, root)
1953
1954
        self.addCleanup(self._check_safety_net)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1955
1956
    def makeAndChdirToTestDir(self):
1957
        """Create a temporary directories for this one test.
1958
        
1959
        This must set self.test_home_dir and self.test_dir and chdir to
1960
        self.test_dir.
1961
        
1962
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
1963
        """
1964
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
1965
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
1966
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
1967
        
1968
    def make_branch(self, relpath, format=None):
1969
        """Create a branch on the transport at relpath."""
1970
        repo = self.make_repository(relpath, format=format)
1971
        return repo.bzrdir.create_branch()
1972
1973
    def make_bzrdir(self, relpath, format=None):
1974
        try:
1975
            # might be a relative or absolute path
1976
            maybe_a_url = self.get_url(relpath)
1977
            segments = maybe_a_url.rsplit('/', 1)
1978
            t = get_transport(maybe_a_url)
1979
            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()
1980
                t.ensure_base()
2230.3.22 by Aaron Bentley
Make test suite use format registry default, not BzrDir default
1981
            if format is None:
1982
                format = 'default'
2204.4.11 by Aaron Bentley
deprecate Repository.set_default_format, update upgrade tests
1983
            if isinstance(format, basestring):
1984
                format = bzrdir.format_registry.make_bzrdir(format)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1985
            return format.initialize_on_transport(t)
1986
        except errors.UninitializableFormat:
1987
            raise TestSkipped("Format %s is not initializable." % format)
1988
1989
    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
1990
        """Create a repository on our default transport at relpath.
1991
        
1992
        Note that relpath must be a relative path, not a full url.
1993
        """
1994
        # FIXME: If you create a remoterepository this returns the underlying
1995
        # real format, which is incorrect.  Actually we should make sure that 
1996
        # RemoteBzrDir returns a RemoteRepository.
1997
        # maybe  mbp 20070410
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
1998
        made_control = self.make_bzrdir(relpath, format=format)
1999
        return made_control.create_repository(shared=shared)
2000
1986.4.9 by Robert Collins
``TestCase.make_branch_and_memory_tree`` now takes a format
2001
    def make_branch_and_memory_tree(self, relpath, format=None):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2002
        """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
2003
        b = self.make_branch(relpath, format=format)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2004
        return memorytree.MemoryTree.create_on_branch(b)
2005
2006
    def overrideEnvironmentForTesting(self):
2007
        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
2008
        os.environ['BZR_HOME'] = self.test_home_dir
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2009
        
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2010
    def setUp(self):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2011
        super(TestCaseWithMemoryTransport, self).setUp()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2012
        self._make_test_root()
1185.16.110 by mbp at sourcefrog
Refactor test setup/teardown into cleanup callbacks
2013
        _currentdir = os.getcwdu()
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2014
        def _leaveDirectory():
2015
            os.chdir(_currentdir)
2016
        self.addCleanup(_leaveDirectory)
2017
        self.makeAndChdirToTestDir()
2018
        self.overrideEnvironmentForTesting()
2019
        self.__readonly_server = None
2020
        self.__server = None
2381.1.3 by Robert Collins
Review feedback.
2021
        self.reduceLockdirTimeout()
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2022
2023
     
2024
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2025
    """Derived class that runs a test within a temporary directory.
2026
2027
    This is useful for tests that need to create a branch, etc.
2028
2029
    The directory is created in a slightly complex way: for each
2030
    Python invocation, a new temporary top-level directory is created.
2031
    All test cases create their own directory within that.  If the
2032
    tests complete successfully, the directory is removed.
2033
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2034
    :ivar test_base_dir: The path of the top-level directory for this 
2035
    test, which contains a home directory and a work directory.
2036
2037
    :ivar test_home_dir: An initially empty directory under test_base_dir
2038
    which is used as $HOME for this test.
2039
2040
    :ivar test_dir: A directory under test_base_dir used as the current
2041
    directory when the test proper is run.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2042
    """
2043
2044
    OVERRIDE_PYTHON = 'python'
2045
2046
    def check_file_contents(self, filename, expect):
2047
        self.log("check contents of file %s" % filename)
2048
        contents = file(filename, 'r').read()
2049
        if contents != expect:
2050
            self.log("expected: %r" % expect)
2051
            self.log("actually: %r" % contents)
2052
            self.fail("contents of %s not as expected" % filename)
2053
2054
    def makeAndChdirToTestDir(self):
2055
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2056
        
2057
        For TestCaseInTempDir we create a temporary directory based on the test
2058
        name and then create two subdirs - test and home under it.
2059
        """
2485.6.7 by Martin Pool
Run exitfuncs explicitly before exiting
2060
        # create a directory within the top level test directory
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
2061
        candidate_dir = osutils.mkdtemp(dir=self.TEST_ROOT)
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2062
        # now create test and home directories within this dir
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2063
        self.test_base_dir = candidate_dir
2064
        self.test_home_dir = self.test_base_dir + '/home'
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2065
        os.mkdir(self.test_home_dir)
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2066
        self.test_dir = self.test_base_dir + '/work'
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2067
        os.mkdir(self.test_dir)
2068
        os.chdir(self.test_dir)
2069
        # put name of test inside
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2070
        f = file(self.test_base_dir + '/name', 'w')
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2071
        try:
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2072
            f.write(self.id())
2485.6.1 by Martin Pool
Remove duplication in TestCaseInTempDir.makeAndChdirToTestDir
2073
        finally:
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2074
            f.close()
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2075
        self.addCleanup(self.deleteTestDir)
2076
2077
    def deleteTestDir(self):
2564.1.1 by Martin Pool
Change out of the test directory before unlinking it, to avoid permission denied errors on Windows (gzlist)
2078
        os.chdir(self.TEST_ROOT)
2485.6.3 by Martin Pool
TestCaseInTempDir takes responsibility for cleaning up its own test dir
2079
        _rmtree_temp_dir(self.test_base_dir)
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2080
2193.2.1 by Alexander Belchenko
selftest: build tree for test with binary line-endings by default
2081
    def build_tree(self, shape, line_endings='binary', transport=None):
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2082
        """Build a test tree according to a pattern.
2083
2084
        shape is a sequence of file specifications.  If the final
2085
        character is '/', a directory is created.
2086
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
2087
        This assumes that all the elements in the tree being built are new.
2088
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2089
        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.
2090
3034.4.8 by Alexander Belchenko
TestCaseInTempDir.build_tree now checks type of shape argument.
2091
        :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
2092
        :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.
2093
            in binary mode, exact contents are written in native mode, the
2094
            line endings match the default platform endings.
2095
        :param transport: A transport to write to, for building trees on VFS's.
2096
            If the transport is readonly or None, "." is opened automatically.
2097
        :return: None
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2098
        """
3044.1.1 by Martin Pool
Fix up calls to TestCase.build_tree passing a string rather than a list
2099
        if type(shape) not in (list, tuple):
2100
            raise AssertionError("Parameter 'shape' should be "
2101
                "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.
2102
        # It's OK to just create them using forward slashes on windows.
1530.1.3 by Robert Collins
transport implementations now tested consistently.
2103
        if transport is None or transport.is_readonly():
1553.5.9 by Martin Pool
Add TestCaseWithTransport.get_transport and get_readonly_transport
2104
            transport = get_transport(".")
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2105
        for name in shape:
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
2106
            self.assert_(isinstance(name, basestring))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2107
            if name[-1] == '/':
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2108
                transport.mkdir(urlutils.escape(name[:-1]))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2109
            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
2110
                if line_endings == 'binary':
1530.1.3 by Robert Collins
transport implementations now tested consistently.
2111
                    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
2112
                elif line_endings == 'native':
1530.1.3 by Robert Collins
transport implementations now tested consistently.
2113
                    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
2114
                else:
2227.2.2 by v.ladeuil+lp at free
Cleanup.
2115
                    raise errors.BzrError(
2116
                        '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
2117
                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
2118
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2119
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2120
    def build_tree_contents(self, shape):
1514 by Robert Collins
Unbreak self.build_tree_shape in tests.
2121
        build_tree_contents(shape)
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2122
2655.2.5 by Marius Kruger
* Improve BzrRemoveChangedFilesError message.
2123
    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.
2124
        """Assert whether path or paths are in the WorkingTree"""
2125
        if tree is None:
2126
            tree = workingtree.WorkingTree.open(root_path)
2127
        if not isinstance(path, basestring):
2128
            for p in path:
2129
                self.assertInWorkingTree(p,tree=tree)
2130
        else:
2131
            self.assertIsNot(tree.path2id(path), None,
2132
                path+' not in working tree.')
2133
2655.2.5 by Marius Kruger
* Improve BzrRemoveChangedFilesError message.
2134
    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.
2135
        """Assert whether path or paths are not in the WorkingTree"""
2136
        if tree is None:
2137
            tree = workingtree.WorkingTree.open(root_path)
2138
        if not isinstance(path, basestring):
2139
            for p in path:
2140
                self.assertNotInWorkingTree(p,tree=tree)
2141
        else:
2142
            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
2143
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
2144
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2145
class TestCaseWithTransport(TestCaseInTempDir):
2146
    """A test case that provides get_url and get_readonly_url facilities.
2147
2148
    These back onto two transport servers, one for readonly access and one for
2149
    read write access.
2150
2151
    If no explicit class is provided for readonly access, a
2152
    ReadonlyTransportDecorator is used instead which allows the use of non disk
2153
    based read write transports.
2154
2155
    If an explicit class is provided for readonly access, that server and the 
2156
    readwrite one must both define get_url() as resolving to os.getcwd().
2157
    """
2158
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2159
    def get_vfs_only_server(self):
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2160
        """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.
2161
2162
        This is useful for some tests with specific servers that need
2163
        diagnostics.
2164
        """
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2165
        if self.__vfs_server is None:
2166
            self.__vfs_server = self.vfs_transport_factory()
2167
            self.__vfs_server.setUp()
2168
            self.addCleanup(self.__vfs_server.tearDown)
2169
        return self.__vfs_server
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2170
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2171
    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.
2172
        """Create a branch on the transport and a tree locally.
2173
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2174
        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.
2175
        the transport.  In that case if the vfs_transport_factory is
2176
        LocalURLServer the working tree is created in the local
2018.5.88 by Andrew Bennetts
Clarify make_branch_and_tree docstring a little.
2177
        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.
2178
        repository will also be accessed locally. Otherwise a lightweight
2179
        checkout is created and returned.
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2180
2181
        :param format: The BzrDirFormat.
2182
        :returns: the WorkingTree.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2183
        """
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.
2184
        # TODO: always use the local disk path for the working tree,
2185
        # this obviously requires a format that supports branch references
2186
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2187
        # RBC 20060208
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2188
        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.
2189
        try:
2190
            return b.bzrdir.create_workingtree()
2191
        except errors.NotLocalUrl:
1910.14.1 by Andrew Bennetts
Fix to make_branch_and_tree's behavior when used with an sftp transport.
2192
            # 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.
2193
            # transport can't support them, then we keep the non-disk-backed
2194
            # 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.
2195
            if self.vfs_transport_factory is LocalURLServer:
2196
                # the branch is colocated on disk, we cannot create a checkout.
2197
                # hopefully callers will expect this.
2198
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2199
                return local_controldir.create_workingtree()
2200
            else:
2201
                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.
2202
1553.5.68 by Martin Pool
Add new TestCaseWithTransport.assertIsDirectory() and tests
2203
    def assertIsDirectory(self, relpath, transport):
2204
        """Assert that relpath within transport is a directory.
2205
2206
        This may not be possible on all transports; in that case it propagates
2207
        a TransportNotPossible.
2208
        """
2209
        try:
2210
            mode = transport.stat(relpath).st_mode
2211
        except errors.NoSuchFile:
2212
            self.fail("path %s is not a directory; no such file"
2213
                      % (relpath))
2214
        if not stat.S_ISDIR(mode):
2215
            self.fail("path %s is not a directory; has mode %#o"
2216
                      % (relpath, mode))
2217
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
2218
    def assertTreesEqual(self, left, right):
2219
        """Check that left and right have the same content and properties."""
2220
        # we use a tree delta to check for equality of the content, and we
2221
        # manually check for equality of other things such as the parents list.
2222
        self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2223
        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.
2224
        self.assertFalse(differences.has_changed(),
2225
            "Trees %r and %r are different: %r" % (left, right, differences))
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
2226
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2227
    def setUp(self):
2228
        super(TestCaseWithTransport, self).setUp()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2229
        self.__vfs_server = None
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
2230
1534.4.10 by Robert Collins
Add TestCaseWithTransport class that provides tests with read and write transport pairs.
2231
1534.4.31 by Robert Collins
cleanedup test_outside_wt
2232
class ChrootedTestCase(TestCaseWithTransport):
2233
    """A support class that provides readonly urls outside the local namespace.
2234
2235
    This is done by checking if self.transport_server is a MemoryServer. if it
2236
    is then we are chrooted already, if it is not then an HttpServer is used
2237
    for readonly urls.
2238
2239
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
2240
                       be used without needed to redo it when a different 
2241
                       subclass is in use ?
2242
    """
2243
2244
    def setUp(self):
2245
        super(ChrootedTestCase, self).setUp()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
2246
        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 :)
2247
            self.transport_readonly_server = HttpServer
1534.4.31 by Robert Collins
cleanedup test_outside_wt
2248
2249
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2250
def condition_id_re(pattern):
2251
    """Create a condition filter which performs a re check on a test's id.
2252
    
2253
    :param pattern: A regular expression string.
2254
    :return: A callable that returns True if the re matches.
2255
    """
2256
    filter_re = re.compile(pattern)
2257
    def condition(test):
2258
        test_id = test.id()
2259
        return filter_re.search(test_id)
2260
    return condition
2261
2262
2921.6.8 by Robert Collins
* New helper function ``bzrlib.tests.condition_isinstance`` which helps
2263
def condition_isinstance(klass_or_klass_list):
2264
    """Create a condition filter which returns isinstance(param, klass).
2265
    
2266
    :return: A callable which when called with one parameter obj return the
2267
        result of isinstance(obj, klass_or_klass_list).
2268
    """
2269
    def condition(obj):
2270
        return isinstance(obj, klass_or_klass_list)
2271
    return condition
2272
2273
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2274
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.
2275
    """Create a condition filter which verify that test's id in a list.
2276
    
3302.8.4 by Vincent Ladeuil
Cosmetic changes.
2277
    :param id_list: A TestIdList object.
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2278
    :return: A callable that returns True if the test's id appears in the list.
2279
    """
2280
    def condition(test):
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2281
        return id_list.includes(test.id())
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2282
    return condition
2283
2284
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2285
def exclude_tests_by_condition(suite, condition):
2286
    """Create a test suite which excludes some tests from suite.
2287
2288
    :param suite: The suite to get tests from.
2289
    :param condition: A callable whose result evaluates True when called with a
2290
        test case which should be excluded from the result.
2291
    :return: A suite which contains the tests found in suite that fail
2292
        condition.
2293
    """
2294
    result = []
2295
    for test in iter_suite_tests(suite):
2296
        if not condition(test):
2297
            result.append(test)
2298
    return TestUtil.TestSuite(result)
2299
2300
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2301
def filter_suite_by_condition(suite, condition):
2302
    """Create a test suite by filtering another one.
2303
    
2304
    :param suite: The source suite.
2305
    :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
2306
        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
2307
    :return: A suite which contains the tests found in suite that pass
2308
        condition.
2309
    """ 
2310
    result = []
2311
    for test in iter_suite_tests(suite):
2312
        if condition(test):
2313
            result.append(test)
2314
    return TestUtil.TestSuite(result)
2315
2316
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
2317
def filter_suite_by_re(suite, pattern):
2394.2.8 by Ian Clatworthy
incorporate feedback from jam
2318
    """Create a test suite by filtering another one.
2319
    
2320
    :param suite:           the source suite
2321
    :param pattern:         pattern that names must match
2322
    :returns: the newly created suite
2323
    """ 
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2324
    condition = condition_id_re(pattern)
2921.6.7 by Robert Collins
* New helper function ``bzrlib.tests.filter_suite_by_condition`` which
2325
    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.
2326
    return result_suite
2394.2.8 by Ian Clatworthy
incorporate feedback from jam
2327
2328
3193.1.2 by Vincent Ladeuil
Add condition_id_in_list and filter_suite_by_id_list capabilities.
2329
def filter_suite_by_id_list(suite, test_id_list):
2330
    """Create a test suite by filtering another one.
2331
2332
    :param suite: The source suite.
2333
    :param test_id_list: A list of the test ids to keep as strings.
2334
    :returns: the newly created suite
2335
    """
2336
    condition = condition_id_in_list(test_id_list)
2337
    result_suite = filter_suite_by_condition(suite, condition)
2338
    return result_suite
2339
2340
2921.6.2 by Robert Collins
* New helper method ``bzrlib.tests.exclude_tests_by_re`` which gives a new
2341
def exclude_tests_by_re(suite, pattern):
2342
    """Create a test suite which excludes some tests from suite.
2343
2344
    :param suite: The suite to get tests from.
2345
    :param pattern: A regular expression string. Test ids that match this
2346
        pattern will be excluded from the result.
2347
    :return: A TestSuite that contains all the tests from suite without the
2348
        tests that matched pattern. The order of tests is the same as it was in
2349
        suite.
2350
    """
2921.6.9 by Robert Collins
* New helper function ``bzrlib.tests.condition_id_re`` which helps
2351
    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
2352
2353
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2354
def preserve_input(something):
2355
    """A helper for performing test suite transformation chains.
2356
2357
    :param something: Anything you want to preserve.
2358
    :return: Something.
2359
    """
2360
    return something
2361
2362
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
2363
def randomize_suite(suite):
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2364
    """Return a new TestSuite with suite's tests in random order.
2365
    
2366
    The tests in the input suite are flattened into a single suite in order to
2367
    accomplish this. Any nested TestSuites are removed to provide global
2368
    randomness.
2369
    """
2921.6.3 by Robert Collins
* New helper method ``bzrlib.tests.randomise_suite`` which returns a
2370
    tests = list(iter_suite_tests(suite))
2371
    random.shuffle(tests)
2372
    return TestUtil.TestSuite(tests)
2373
2374
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2375
def split_suite_by_re(suite, pattern):
2376
    """Split a test suite into two by a regular expression.
2377
    
2378
    :param suite: The suite to split.
2379
    :param pattern: A regular expression string. Test ids that match this
2380
        pattern will be in the first test suite returned, and the others in the
2381
        second test suite returned.
2382
    :return: A tuple of two test suites, where the first contains tests from
2383
        suite matching pattern, and the second contains the remainder from
2384
        suite. The order within each output suite is the same as it was in
2385
        suite.
2386
    """ 
2387
    matched = []
2388
    did_not_match = []
2213.2.1 by Martin Pool
Add selftest --first flag
2389
    filter_re = re.compile(pattern)
2390
    for test in iter_suite_tests(suite):
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
2391
        test_id = test.id()
2921.6.1 by Robert Collins
* New helper method ``bzrlib.tests.split_suite_by_re`` which splits a test
2392
        if filter_re.search(test_id):
2393
            matched.append(test)
2394
        else:
2395
            did_not_match.append(test)
2396
    return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
2213.2.1 by Martin Pool
Add selftest --first flag
2397
2398
1185.16.58 by mbp at sourcefrog
- run all selftests by default
2399
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
2400
              stop_on_failure=False,
2213.2.1 by Martin Pool
Add selftest --first flag
2401
              transport=None, lsprof_timed=None, bench_history=None,
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2402
              matching_tests_first=None,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
2403
              list_only=False,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2404
              random_seed=None,
2418.4.1 by John Arbash Meinel
(Ian Clatworthy) Bugs #102679, #102686. Add --exclude and --randomize to 'bzr selftest'
2405
              exclude_pattern=None,
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
2406
              strict=False):
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
2407
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
2408
    if verbose:
2409
        verbosity = 2
2410
    else:
2411
        verbosity = 1
2412
    runner = TextTestRunner(stream=sys.stdout,
2413
                            descriptions=0,
1534.11.1 by Robert Collins
Teach bzr selftest to use a progress bar in non verbose mode.
2414
                            verbosity=verbosity,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
2415
                            bench_history=bench_history,
2418.4.1 by John Arbash Meinel
(Ian Clatworthy) Bugs #102679, #102686. Add --exclude and --randomize to 'bzr selftest'
2416
                            list_only=list_only,
2379.6.3 by Alexander Belchenko
Rework NUMBERED_DIRS usage to keep test_selftest.py passing the tests on win32
2417
                            )
1185.16.58 by mbp at sourcefrog
- run all selftests by default
2418
    runner.stop_on_failure=stop_on_failure
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2419
    # Initialise the random number generator and display the seed used.
2420
    # We convert the seed to a long to make it reuseable across invocations.
2421
    random_order = False
2422
    if random_seed is not None:
2423
        random_order = True
2424
        if random_seed == "now":
2425
            random_seed = long(time.time())
2426
        else:
2427
            # Convert the seed to a long if we can
2428
            try:
2429
                random_seed = long(random_seed)
2430
            except:
2431
                pass
2432
        runner.stream.writeln("Randomizing test order using seed %s\n" %
2433
            (random_seed))
2434
        random.seed(random_seed)
2435
    # Customise the list of tests if requested
2921.6.5 by Robert Collins
* The ``exclude_pattern`` parameter to the ``bzrlib.tests.`` functions
2436
    if exclude_pattern is not None:
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2437
        suite = exclude_tests_by_re(suite, exclude_pattern)
2438
    if random_order:
3128.1.2 by Vincent Ladeuil
Tweak as per review feedback: s/randomise.*/randomize&/, 0.92 -> 1.0.
2439
        order_changer = randomize_suite
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2440
    else:
2441
        order_changer = preserve_input
2921.6.5 by Robert Collins
* The ``exclude_pattern`` parameter to the ``bzrlib.tests.`` functions
2442
    if pattern != '.*' or random_order:
2213.2.1 by Martin Pool
Add selftest --first flag
2443
        if matching_tests_first:
2921.6.11 by Robert Collins
Last typo.
2444
            suites = map(order_changer, split_suite_by_re(suite, pattern))
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2445
            suite = TestUtil.TestSuite(suites)
2213.2.1 by Martin Pool
Add selftest --first flag
2446
        else:
2921.6.6 by Robert Collins
* The ``exclude_pattern`` and ``random_order`` parameters to the function
2447
            suite = order_changer(filter_suite_by_re(suite, pattern))
3084.1.1 by Andrew Bennetts
Add a --coverage option to selftest.
2448
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
2449
    result = runner.run(suite)
2658.3.4 by Daniel Watkins
'bzr selftest --strict' now fails if there are any unsupported features or tests that are known to fail.
2450
2451
    if strict:
2452
        return result.wasStrictlySuccessful()
2453
1393.1.6 by Martin Pool
- fold testsweet into bzrlib.selftest
2454
    return result.wasSuccessful()
2455
2456
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
2457
# Controlled by "bzr selftest -E=..." option
2458
selftest_debug_flags = set()
2459
2460
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
2461
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2462
             transport=None,
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
2463
             test_suite_factory=None,
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
2464
             lsprof_timed=None,
2213.2.1 by Martin Pool
Add selftest --first flag
2465
             bench_history=None,
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2466
             matching_tests_first=None,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
2467
             list_only=False,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2468
             random_seed=None,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
2469
             exclude_pattern=None,
2470
             strict=False,
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
2471
             load_list=None,
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
2472
             debug_flags=None,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
2473
             ):
1204 by Martin Pool
doc
2474
    """Run the whole test suite under the enhanced runner"""
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
2475
    # XXX: Very ugly way to do this...
2476
    # Disable warning about old formats because we don't want it to disturb
2477
    # any blackbox tests.
2478
    from bzrlib import repository
2479
    repository._deprecation_warning_done = True
2480
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.
2481
    global default_transport
2482
    if transport is None:
2483
        transport = default_transport
2484
    old_transport = default_transport
2485
    default_transport = transport
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
2486
    global selftest_debug_flags
2487
    old_debug_flags = selftest_debug_flags
2488
    if debug_flags is not None:
2489
        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.
2490
    try:
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
2491
        if load_list is None:
2492
            keep_only = None
2493
        else:
2494
            keep_only = load_test_id_list(load_list)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2495
        if test_suite_factory is None:
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
2496
            suite = test_suite(keep_only)
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2497
        else:
2498
            suite = test_suite_factory()
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2499
        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
2500
                     stop_on_failure=stop_on_failure,
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
2501
                     transport=transport,
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
2502
                     lsprof_timed=lsprof_timed,
2213.2.1 by Martin Pool
Add selftest --first flag
2503
                     bench_history=bench_history,
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2504
                     matching_tests_first=matching_tests_first,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
2505
                     list_only=list_only,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2506
                     random_seed=random_seed,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
2507
                     exclude_pattern=exclude_pattern,
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
2508
                     strict=strict)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2509
    finally:
2510
        default_transport = old_transport
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
2511
        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.
2512
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
2513
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2514
def load_test_id_list(file_name):
2515
    """Load a test id list from a text file.
2516
2517
    The format is one test id by line.  No special care is taken to impose
2518
    strict rules, these test ids are used to filter the test suite so a test id
2519
    that do not match an existing test will do no harm. This allows user to add
2520
    comments, leave blank lines, etc.
2521
    """
2522
    test_list = []
2523
    try:
2524
        ftest = open(file_name, 'rt')
2525
    except IOError, e:
2526
        if e.errno != errno.ENOENT:
2527
            raise
2528
        else:
2529
            raise errors.NoSuchFile(file_name)
2530
2531
    for test_name in ftest.readlines():
2532
        test_list.append(test_name.strip())
2533
    ftest.close()
2534
    return test_list
2535
3302.3.3 by Vincent Ladeuil
Fix PEP8 catched by Aaron. Update NEWS.
2536
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2537
def suite_matches_id_list(test_suite, id_list):
2538
    """Warns about tests not appearing or appearing more than once.
2539
2540
    :param test_suite: A TestSuite object.
2541
    :param test_id_list: The list of test ids that should be found in 
2542
         test_suite.
2543
2544
    :return: (absents, duplicates) absents is a list containing the test found
2545
        in id_list but not in test_suite, duplicates is a list containing the
2546
        test found multiple times in test_suite.
2547
2548
    When using a prefined test id list, it may occurs that some tests do not
2549
    exist anymore or that some tests use the same id. This function warns the
2550
    tester about potential problems in his workflow (test lists are volatile)
2551
    or in the test suite itself (using the same id for several tests does not
2552
    help to localize defects).
2553
    """
2554
    # Build a dict counting id occurrences
2555
    tests = dict()
2556
    for test in iter_suite_tests(test_suite):
2557
        id = test.id()
2558
        tests[id] = tests.get(id, 0) + 1
2559
2560
    not_found = []
2561
    duplicates = []
2562
    for id in id_list:
2563
        occurs = tests.get(id, 0)
2564
        if not occurs:
2565
            not_found.append(id)
2566
        elif occurs > 1:
2567
            duplicates.append(id)
2568
2569
    return not_found, duplicates
2570
3193.1.7 by Vincent Ladeuil
Load test id list from a text file.
2571
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2572
class TestIdList(object):
2573
    """Test id list to filter a test suite.
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
2574
2575
    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.
2576
    <module>[.<class>.<method>][(<param>+)], <module> being in python dotted
2577
    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
2578
    - 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.
2579
    - keep only the tests listed from the module test suite.
2580
    """
2581
2582
    def __init__(self, test_id_list):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2583
        # When a test suite needs to be filtered against us we compare test ids
2584
        # for equality, so a simple dict offers a quick and simple solution.
2585
        self.tests = dict().fromkeys(test_id_list, True)
2586
2587
        # While unittest.TestCase have ids like:
2588
        # <module>.<class>.<method>[(<param+)],
2589
        # doctest.DocTestCase can have ids like:
2590
        # <module>
2591
        # <module>.<class>
2592
        # <module>.<function>
2593
        # <module>.<class>.<method>
2594
2595
        # Since we can't predict a test class from its name only, we settle on
2596
        # a simple constraint: a test id always begins with its module name.
2597
2598
        modules = {}
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
2599
        for test_id in test_id_list:
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2600
            parts = test_id.split('.')
2601
            mod_name = parts.pop(0)
2602
            modules[mod_name] = True
2603
            for part in parts:
2604
                mod_name += '.' + part
2605
                modules[mod_name] = True
2606
        self.modules = modules
3193.1.4 by Vincent Ladeuil
Make TestTestIdListFilter aware that a test exists for a module or one of
2607
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2608
    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
2609
        """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.
2610
        return self.modules.has_key(module_name)
2611
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2612
    def includes(self, test_id):
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2613
        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.
2614
3193.1.3 by Vincent Ladeuil
Create a TestIdListFilter helper object to make testing easier.
2615
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2616
def test_suite(keep_only=None):
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2617
    """Build and return TestSuite for the whole of bzrlib.
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2618
2619
    :param keep_only: A list of test ids limiting the suite returned.
2620
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2621
    This function can be replaced if you need to change the default test
2622
    suite on a global basis, but it is not encouraged.
2623
    """
1740.6.1 by Martin Pool
Remove Scratch objects used by doctests
2624
    testmod_names = [
2613.1.2 by Martin Pool
Move bencode tests into util.tests
2625
                   'bzrlib.util.tests.test_bencode',
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
2626
                   'bzrlib.tests.test__dirstate_helpers',
1518 by Robert Collins
Merge from mbp.
2627
                   'bzrlib.tests.test_ancestry',
1551.9.17 by Aaron Bentley
Annotate for working trees across all parents
2628
                   'bzrlib.tests.test_annotate',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2629
                   'bzrlib.tests.test_api',
1755.3.6 by John Arbash Meinel
Add a test suite for Atomic File, and clean it up so that it really does set the mode properly.
2630
                   'bzrlib.tests.test_atomicfile',
1518 by Robert Collins
Merge from mbp.
2631
                   'bzrlib.tests.test_bad_files',
2890.2.3 by Robert Collins
* New module ``bzrlib.bisect_multi`` with generic multiple-bisection-at-once
2632
                   'bzrlib.tests.test_bisect_multi',
1518 by Robert Collins
Merge from mbp.
2633
                   'bzrlib.tests.test_branch',
2466.7.3 by Robert Collins
Create bzrlib.branchbuilder.
2634
                   'bzrlib.tests.test_branchbuilder',
2376.4.4 by jml at canonical
Beginnings of generic bug-tracker plugin system.
2635
                   'bzrlib.tests.test_bugtracker',
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
2636
                   'bzrlib.tests.test_bundle',
1534.4.39 by Robert Collins
Basic BzrDir support.
2637
                   'bzrlib.tests.test_bzrdir',
1911.2.3 by John Arbash Meinel
Moving everything into a new location so that we can cache more than just revision ids
2638
                   'bzrlib.tests.test_cache_utf8',
2172.1.3 by Aaron Bentley
Rename test_commands in the test suite
2639
                   'bzrlib.tests.test_commands',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2640
                   'bzrlib.tests.test_commit',
2641
                   'bzrlib.tests.test_commit_merge',
2642
                   'bzrlib.tests.test_config',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2643
                   'bzrlib.tests.test_conflicts',
2475.4.1 by Martin Pool
Start adding CountedLock class to partially replace LockableFiles
2644
                   'bzrlib.tests.test_counted_lock',
1551.3.11 by Aaron Bentley
Merge from Robert
2645
                   'bzrlib.tests.test_decorators',
2225.1.1 by Aaron Bentley
Added revert change display, with tests
2646
                   'bzrlib.tests.test_delta',
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
2647
                   'bzrlib.tests.test_deprecated_graph',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2648
                   'bzrlib.tests.test_diff',
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
2649
                   'bzrlib.tests.test_dirstate',
3251.3.1 by Aaron Bentley
Add support for directory services
2650
                   'bzrlib.tests.test_directory_service',
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
2651
                   'bzrlib.tests.test_email_message',
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2652
                   'bzrlib.tests.test_errors',
1185.80.5 by John Arbash Meinel
Changing the escaping just a little bit. Now we can handle unicode characters.
2653
                   'bzrlib.tests.test_escaped_store',
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
2654
                   'bzrlib.tests.test_extract',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2655
                   'bzrlib.tests.test_fetch',
1752.5.4 by Andrew Bennetts
Merge from bzr.dev.
2656
                   'bzrlib.tests.test_ftp_transport',
2215.5.1 by Alexander Belchenko
Fix generation of rstx man page (problem with short names of options) and provide simple tests for future.
2657
                   'bzrlib.tests.test_generate_docs',
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
2658
                   'bzrlib.tests.test_generate_ids',
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
2659
                   'bzrlib.tests.test_globbing',
1518 by Robert Collins
Merge from mbp.
2660
                   'bzrlib.tests.test_gpg',
2661
                   'bzrlib.tests.test_graph',
2662
                   'bzrlib.tests.test_hashcache',
2425.2.2 by Robert Collins
``bzr help`` now provides cross references to other help topics using the
2663
                   'bzrlib.tests.test_help',
2553.1.1 by Robert Collins
Give Hooks names.
2664
                   'bzrlib.tests.test_hooks',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2665
                   'bzrlib.tests.test_http',
3111.1.6 by Vincent Ladeuil
Begin refactoring test_http.py into parameterized tests.
2666
                   'bzrlib.tests.test_http_implementations',
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
2667
                   'bzrlib.tests.test_http_response',
2298.5.1 by Alexander Belchenko
Bugfix #82086: Searching location of CA bundle for PyCurl in env variable (CURL_CA_BUNDLE), and on win32 along the PATH
2668
                   'bzrlib.tests.test_https_ca_bundle',
1518 by Robert Collins
Merge from mbp.
2669
                   'bzrlib.tests.test_identitymap',
1836.1.13 by John Arbash Meinel
Adding functions for getting user ignores.
2670
                   'bzrlib.tests.test_ignores',
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
2671
                   'bzrlib.tests.test_index',
2363.5.2 by Aaron Bentley
Implement layout description
2672
                   'bzrlib.tests.test_info',
1518 by Robert Collins
Merge from mbp.
2673
                   'bzrlib.tests.test_inv',
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2674
                   'bzrlib.tests.test_knit',
1996.1.1 by John Arbash Meinel
Adding a ScopeReplacer class, which can replace itself on demand
2675
                   'bzrlib.tests.test_lazy_import',
2063.4.1 by John Arbash Meinel
bzrlib.lazy_regex.lazy_compile creates a proxy object around re.compile()
2676
                   'bzrlib.tests.test_lazy_regex',
1553.5.12 by Martin Pool
New LockDir locking mechanism
2677
                   'bzrlib.tests.test_lockdir',
1185.67.4 by Aaron Bentley
Throw if we try to write to a LockableFiles with no write lock
2678
                   'bzrlib.tests.test_lockable_files',
1518 by Robert Collins
Merge from mbp.
2679
                   'bzrlib.tests.test_log',
2493.2.3 by Ian Clatworthy
changes requested in jameinel's review incorporated
2680
                   'bzrlib.tests.test_lsprof',
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
2681
                   'bzrlib.tests.test_lru_cache',
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
2682
                   'bzrlib.tests.test_mail_client',
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
2683
                   'bzrlib.tests.test_memorytree',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2684
                   'bzrlib.tests.test_merge',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2685
                   'bzrlib.tests.test_merge3',
1518 by Robert Collins
Merge from mbp.
2686
                   'bzrlib.tests.test_merge_core',
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
2687
                   'bzrlib.tests.test_merge_directive',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2688
                   'bzrlib.tests.test_missing',
1518 by Robert Collins
Merge from mbp.
2689
                   'bzrlib.tests.test_msgeditor',
2520.4.2 by Aaron Bentley
Integrate mpdiff into bazaar
2690
                   'bzrlib.tests.test_multiparent',
3335.1.1 by Jelmer Vernooij
Add tests for mutabletree hooks.
2691
                   'bzrlib.tests.test_mutabletree',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2692
                   'bzrlib.tests.test_nonascii',
1518 by Robert Collins
Merge from mbp.
2693
                   'bzrlib.tests.test_options',
1185.50.20 by John Arbash Meinel
merge permissions branch, also fixup tests so they are lined up with bzr.dev to help prevent conflicts.
2694
                   'bzrlib.tests.test_osutils',
2192.1.2 by Alexander Belchenko
Tests for osutils.get_terminal_encoding()
2695
                   'bzrlib.tests.test_osutils_encodings',
2617.4.2 by Robert Collins
Add FileCollection support class.
2696
                   'bzrlib.tests.test_pack',
1558.15.6 by Aaron Bentley
Added more tests
2697
                   'bzrlib.tests.test_patch',
1185.82.9 by John Arbash Meinel
Moving patches testing into main test suite.
2698
                   'bzrlib.tests.test_patches',
1185.58.1 by John Arbash Meinel
Added new permissions test (currently don't pass)
2699
                   'bzrlib.tests.test_permissions',
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
2700
                   'bzrlib.tests.test_plugins',
1551.2.27 by Aaron Bentley
Got propogation under test
2701
                   'bzrlib.tests.test_progress',
2796.2.1 by Aaron Bentley
Begin work on reconfigure command
2702
                   'bzrlib.tests.test_reconfigure',
1570.1.11 by Robert Collins
Make reconcile work with shared repositories.
2703
                   'bzrlib.tests.test_reconcile',
1911.4.3 by John Arbash Meinel
[merge] Adeodato Simó: change factory => registry
2704
                   'bzrlib.tests.test_registry',
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2705
                   'bzrlib.tests.test_remote',
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2706
                   'bzrlib.tests.test_repository',
1551.8.15 by Aaron Bentley
bug #54172: handle new directories properly in revert
2707
                   'bzrlib.tests.test_revert',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2708
                   'bzrlib.tests.test_revision',
3298.2.7 by John Arbash Meinel
Rename test_revisionnamespaces => test_revisionspec
2709
                   'bzrlib.tests.test_revisionspec',
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
2710
                   'bzrlib.tests.test_revisiontree',
1185.47.1 by Martin Pool
[broken] start converting basic_io to more rfc822-like format
2711
                   'bzrlib.tests.test_rio',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2712
                   'bzrlib.tests.test_sampler',
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
2713
                   'bzrlib.tests.test_selftest',
1185.33.89 by Martin Pool
[patch] add a selftest test that the setup build script works (Alexander Belchenko)
2714
                   'bzrlib.tests.test_setup',
1185.50.20 by John Arbash Meinel
merge permissions branch, also fixup tests so they are lined up with bzr.dev to help prevent conflicts.
2715
                   'bzrlib.tests.test_sftp_transport',
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
2716
                   'bzrlib.tests.test_smart',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2717
                   'bzrlib.tests.test_smart_add',
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
2718
                   'bzrlib.tests.test_smart_transport',
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
2719
                   'bzrlib.tests.test_smtp_connection',
1522 by Robert Collins
Test for the number of uses of self.working_tree() in branch.py
2720
                   'bzrlib.tests.test_source',
2221.5.1 by Dmitry Vasiliev
Added support for Putty's SSH implementation
2721
                   'bzrlib.tests.test_ssh_transport',
1551.6.19 by Aaron Bentley
Fix pending merge status on empty trees
2722
                   'bzrlib.tests.test_status',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2723
                   'bzrlib.tests.test_store',
2018.5.157 by Andrew Bennetts
Remove unnecessary trivial divergences from bzr.dev.
2724
                   'bzrlib.tests.test_strace',
1731.2.4 by Aaron Bentley
Ensure subsume works with Knit2 repos
2725
                   'bzrlib.tests.test_subsume',
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
2726
                   'bzrlib.tests.test_switch',
1534.2.1 by Robert Collins
Implement deprecated_method
2727
                   'bzrlib.tests.test_symbol_versioning',
2220.2.11 by mbp at sourcefrog
Get tag tests working again, stored in the Branch
2728
                   'bzrlib.tests.test_tag',
1518 by Robert Collins
Merge from mbp.
2729
                   'bzrlib.tests.test_testament',
1558.15.1 by Aaron Bentley
Add text_file function
2730
                   'bzrlib.tests.test_textfile',
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
2731
                   'bzrlib.tests.test_textmerge',
1551.12.29 by Aaron Bentley
Copy and extend patch date formatting code, add patch-date parsing
2732
                   'bzrlib.tests.test_timestamp',
1518 by Robert Collins
Merge from mbp.
2733
                   'bzrlib.tests.test_trace',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2734
                   'bzrlib.tests.test_transactions',
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2735
                   'bzrlib.tests.test_transform',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2736
                   'bzrlib.tests.test_transport',
1852.8.2 by Robert Collins
Add InterTree class to represent InterTree operations.
2737
                   'bzrlib.tests.test_tree',
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
2738
                   'bzrlib.tests.test_treebuilder',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2739
                   'bzrlib.tests.test_tsort',
1666.1.2 by Robert Collins
Fix race condition between end of stream and end of file with tuned_gzip.
2740
                   'bzrlib.tests.test_tuned_gzip',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2741
                   'bzrlib.tests.test_ui',
3280.4.1 by John Arbash Meinel
Add uncommit --local.
2742
                   'bzrlib.tests.test_uncommit',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2743
                   'bzrlib.tests.test_upgrade',
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2744
                   'bzrlib.tests.test_urlutils',
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
2745
                   'bzrlib.tests.test_versionedfile',
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
2746
                   'bzrlib.tests.test_version',
2022.1.1 by John Arbash Meinel
[merge] version-info plugin, and cleanup for layout in bzr
2747
                   'bzrlib.tests.test_version_info',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2748
                   'bzrlib.tests.test_weave',
2749
                   'bzrlib.tests.test_whitebox',
2617.5.1 by Kuno Meyer
Added direct unit tests for win32utils.glob_expand().
2750
                   'bzrlib.tests.test_win32utils',
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
2751
                   'bzrlib.tests.test_workingtree',
2255.2.121 by John Arbash Meinel
split out the WorkingTreeFormat4 tests into a separate test file
2752
                   'bzrlib.tests.test_workingtree_4',
2018.4.1 by Andrew Bennetts
Add WSGI smart server.
2753
                   'bzrlib.tests.test_wsgi',
1185.33.91 by Martin Pool
[merge] improved 'missing' command from aaron
2754
                   'bzrlib.tests.test_xml',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
2755
                   ]
1530.1.3 by Robert Collins
transport implementations now tested consistently.
2756
    test_transport_implementations = [
1711.3.2 by John Arbash Meinel
Add the read_bundle_from_url command, which handles lots of exceptions
2757
        'bzrlib.tests.test_transport_implementations',
2758
        'bzrlib.tests.test_read_bundle',
2759
        ]
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
2760
    loader = TestUtil.TestLoader()
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2761
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2762
    if keep_only is None:
2763
        loader = TestUtil.TestLoader()
2764
    else:
3193.1.11 by Vincent Ladeuil
Relax constraint on test ids, simplify implementation and update tests.
2765
        id_filter = TestIdList(keep_only)
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2766
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2767
    suite = loader.suiteClass()
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2768
2769
    # modules building their suite with loadTestsFromModuleNames
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2770
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2771
2772
    # modules adapted for transport implementations
2553.2.5 by Robert Collins
And overhaul TransportTestProviderAdapter too.
2773
    from bzrlib.tests.test_transport_implementations import TransportTestProviderAdapter
1530.1.3 by Robert Collins
transport implementations now tested consistently.
2774
    adapter = TransportTestProviderAdapter()
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2775
    adapt_modules(test_transport_implementations, adapter, loader, suite)
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2776
2777
    # modules defining their own test_suite()
2778
    for package in [p for p in packages_to_test()
2779
                    if (keep_only is None
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2780
                        or id_filter.refers_to(p.__name__))]:
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2781
        pack_suite = package.test_suite()
2782
        suite.addTest(pack_suite)
2783
3302.8.13 by Vincent Ladeuil
DocTests can now be filtered at module level too.
2784
    modules_to_doctest = [
2785
        'bzrlib',
2786
        'bzrlib.errors',
2787
        'bzrlib.export',
2788
        'bzrlib.inventory',
2789
        'bzrlib.iterablefile',
2790
        'bzrlib.lockdir',
2791
        'bzrlib.merge3',
2792
        'bzrlib.option',
2793
        'bzrlib.store',
3388.1.2 by Martin Pool
Add new symbol_versioning.deprecated_in
2794
        'bzrlib.symbol_versioning',
3302.8.13 by Vincent Ladeuil
DocTests can now be filtered at module level too.
2795
        'bzrlib.tests',
2796
        'bzrlib.timestamp',
2797
        'bzrlib.version_info_formats.format_custom',
2798
        ]
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2799
3302.8.13 by Vincent Ladeuil
DocTests can now be filtered at module level too.
2800
    for mod in modules_to_doctest:
2801
        if not (keep_only is None or id_filter.refers_to(mod)):
2802
            # No tests to keep here, move along
2803
            continue
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
2804
        try:
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2805
            doc_suite = doctest.DocTestSuite(mod)
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
2806
        except ValueError, e:
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2807
            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.
2808
            raise
3193.1.6 by Vincent Ladeuil
Filter the whole test suite.
2809
        suite.addTest(doc_suite)
2810
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
2811
    default_encoding = sys.getdefaultencoding()
3221.4.1 by Martin Pool
Treat failure to load plugin test suites as a fatal error
2812
    for name, plugin in bzrlib.plugin.plugins().items():
2813
        if keep_only is not None:
3302.8.3 by Vincent Ladeuil
Use better names for TestIdList methods.
2814
            if not id_filter.refers_to(plugin.module.__name__):
3221.4.1 by Martin Pool
Treat failure to load plugin test suites as a fatal error
2815
                continue
2816
        plugin_suite = plugin.test_suite()
2817
        # We used to catch ImportError here and turn it into just a warning,
2818
        # but really if you don't have --no-plugins this should be a failure.
2819
        # mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2820
        if plugin_suite is None:
3302.8.21 by Vincent Ladeuil
Fixed as per Robert's review.
2821
            plugin_suite = plugin.load_plugin_tests(loader)
3221.4.1 by Martin Pool
Treat failure to load plugin test suites as a fatal error
2822
        if plugin_suite is not None:
2823
            suite.addTest(plugin_suite)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
2824
        if default_encoding != sys.getdefaultencoding():
2825
            bzrlib.trace.warning(
2826
                'Plugin "%s" tried to reset default encoding to: %s', name,
2827
                sys.getdefaultencoding())
2828
            reload(sys)
2829
            sys.setdefaultencoding(default_encoding)
3302.3.1 by Vincent Ladeuil
Help identify duplicates IDs in test suite and missing tests in id
2830
2831
    if keep_only is not None:
3302.8.12 by Vincent Ladeuil
Simplify tests.test_suite.
2832
        # Now that the referred modules have loaded their tests, keep only the
2833
        # requested ones.
2834
        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
2835
        # Do some sanity checks on the id_list filtering
2836
        not_found, duplicates = suite_matches_id_list(suite, keep_only)
2837
        for id in not_found:
2838
            bzrlib.trace.warning('"%s" not found in the test suite', id)
2839
        for id in duplicates:
2840
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
2841
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
2842
    return suite
764 by Martin Pool
- log messages from a particular test are printed if that test fails
2843
1185.51.1 by Martin Pool
Better message when failing to import a test suite.
2844
3302.8.16 by Vincent Ladeuil
Add an optional loader parameter needed when deploying the test
2845
def multiply_tests_from_modules(module_name_list, scenario_iter, loader=None):
2729.1.2 by Martin Pool
Add new multiply_tests_from_modules to give a simpler interface to test scenarios
2846
    """Adapt all tests in some given modules to given scenarios.
2847
2848
    This is the recommended public interface for test parameterization.
2849
    Typically the test_suite() method for a per-implementation test
2850
    suite will call multiply_tests_from_modules and return the 
2851
    result.
2852
2853
    :param module_name_list: List of fully-qualified names of test
2854
        modules.
2729.1.3 by Martin Pool
TestScenarioAdapter must be a list, not an iter
2855
    :param scenario_iter: Iterable of pairs of (scenario_name, 
2729.1.2 by Martin Pool
Add new multiply_tests_from_modules to give a simpler interface to test scenarios
2856
        scenario_param_dict).
3302.8.16 by Vincent Ladeuil
Add an optional loader parameter needed when deploying the test
2857
    :param loader: If provided, will be used instead of a new 
2858
        bzrlib.tests.TestLoader() instance.
2729.1.2 by Martin Pool
Add new multiply_tests_from_modules to give a simpler interface to test scenarios
2859
2860
    This returns a new TestSuite containing the cross product of
2861
    all the tests in all the modules, each repeated for each scenario.
2862
    Each test is adapted by adding the scenario name at the end 
2863
    of its name, and updating the test object's __dict__ with the
2864
    scenario_param_dict.
2865
2866
    >>> r = multiply_tests_from_modules(
2867
    ...     ['bzrlib.tests.test_sampler'],
2868
    ...     [('one', dict(param=1)), 
2869
    ...      ('two', dict(param=2))])
2870
    >>> tests = list(iter_suite_tests(r))
2871
    >>> len(tests)
2872
    2
2873
    >>> tests[0].id()
2874
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
2875
    >>> tests[0].param
2876
    1
2877
    >>> tests[1].param
2878
    2
2879
    """
3302.8.16 by Vincent Ladeuil
Add an optional loader parameter needed when deploying the test
2880
    # XXX: Isn't load_tests() a better way to provide the same functionality
2881
    # without forcing a predefined TestScenarioApplier ? --vila 080215
2882
    if loader is None:
2883
        loader = TestUtil.TestLoader()
2884
2885
    suite = loader.suiteClass()
2886
2729.1.2 by Martin Pool
Add new multiply_tests_from_modules to give a simpler interface to test scenarios
2887
    adapter = TestScenarioApplier()
2729.1.3 by Martin Pool
TestScenarioAdapter must be a list, not an iter
2888
    adapter.scenarios = list(scenario_iter)
2729.1.2 by Martin Pool
Add new multiply_tests_from_modules to give a simpler interface to test scenarios
2889
    adapt_modules(module_name_list, adapter, loader, suite)
2890
    return suite
2891
2892
2745.6.58 by Andrew Bennetts
Slightly neater test parameterisation in repository_implementations; extract a 'multiply_scenarios' function.
2893
def multiply_scenarios(scenarios_left, scenarios_right):
2894
    """Multiply two sets of scenarios.
2895
2896
    :returns: the cartesian product of the two sets of scenarios, that is
2897
        a scenario for every possible combination of a left scenario and a
2898
        right scenario.
2899
    """
2900
    return [
2901
        ('%s,%s' % (left_name, right_name),
2902
         dict(left_dict.items() + right_dict.items()))
2903
        for left_name, left_dict in scenarios_left
2904
        for right_name, right_dict in scenarios_right]
2905
2906
2907
1534.4.23 by Robert Collins
Move branch implementations tests into a package.
2908
def adapt_modules(mods_list, adapter, loader, suite):
2909
    """Adapt the modules in mods_list using adapter and add to suite."""
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
2910
    for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
2911
        suite.addTests(adapter.adapt(test))
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
2912
2913
3004.1.5 by Daniel Watkins
Added adapt_tests which will adapt tests at a finer-than-module level.
2914
def adapt_tests(tests_list, adapter, loader, suite):
2915
    """Adapt the tests in tests_list using adapter and add to suite."""
2916
    for test in tests_list:
2917
        suite.addTests(adapter.adapt(loader.loadTestsFromName(test)))
2918
2919
2379.6.4 by Alexander Belchenko
Teach `bzr selftest --clean-output` to remove read-only files (win32-specific)
2920
def _rmtree_temp_dir(dirname):
2485.6.4 by Martin Pool
Move unicode handling code into _rmtree_temp_dir
2921
    # If LANG=C we probably have created some bogus paths
2922
    # which rmtree(unicode) will fail to delete
2923
    # so make sure we are using rmtree(str) to delete everything
2924
    # except on win32, where rmtree(str) will fail
2925
    # since it doesn't have the property of byte-stream paths
2926
    # (they are either ascii or mbcs)
2927
    if sys.platform == 'win32':
2928
        # make sure we are using the unicode win32 api
2929
        dirname = unicode(dirname)
2930
    else:
2931
        dirname = dirname.encode(sys.getfilesystemencoding())
2379.6.4 by Alexander Belchenko
Teach `bzr selftest --clean-output` to remove read-only files (win32-specific)
2932
    try:
2933
        osutils.rmtree(dirname)
2934
    except OSError, e:
2935
        if sys.platform == 'win32' and e.errno == errno.EACCES:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
2936
            sys.stderr.write(('Permission denied: '
2379.6.4 by Alexander Belchenko
Teach `bzr selftest --clean-output` to remove read-only files (win32-specific)
2937
                                 'unable to remove testing dir '
2946.1.1 by Alexander Belchenko
trivial fix for string formatting in rmtree_temp_dir
2938
                                 '%s\n' % os.path.basename(dirname)))
2379.6.4 by Alexander Belchenko
Teach `bzr selftest --clean-output` to remove read-only files (win32-specific)
2939
        else:
2940
            raise
2941
2942
2367.1.4 by Robert Collins
Add operating system Feature model to bzrlib.tests to allow writing tests
2943
class Feature(object):
2944
    """An operating system Feature."""
2945
2946
    def __init__(self):
2947
        self._available = None
2948
2949
    def available(self):
2950
        """Is the feature available?
2951
2952
        :return: True if the feature is available.
2953
        """
2954
        if self._available is None:
2955
            self._available = self._probe()
2956
        return self._available
2957
2958
    def _probe(self):
2959
        """Implement this method in concrete features.
2960
2961
        :return: True if the feature is available.
2962
        """
2963
        raise NotImplementedError
2964
2965
    def __str__(self):
2966
        if getattr(self, 'feature_name', None):
2967
            return self.feature_name()
2968
        return self.__class__.__name__
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
2969
2970
2776.1.5 by Robert Collins
Add reasonably comprehensive tests for path last modified and per file graph behaviour.
2971
class _SymlinkFeature(Feature):
2972
2973
    def _probe(self):
2974
        return osutils.has_symlinks()
2975
2976
    def feature_name(self):
2977
        return 'symlinks'
2978
2979
SymlinkFeature = _SymlinkFeature()
2980
2981
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
2982
class _HardlinkFeature(Feature):
2983
2984
    def _probe(self):
2985
        return osutils.has_hardlinks()
2986
2987
    def feature_name(self):
2988
        return 'hardlinks'
2989
2990
HardlinkFeature = _HardlinkFeature()
2991
2992
2949.5.2 by Alexander Belchenko
John's review
2993
class _OsFifoFeature(Feature):
2994
2995
    def _probe(self):
2996
        return getattr(os, 'mkfifo', None)
2997
2998
    def feature_name(self):
2999
        return 'filesystem fifos'
3000
3001
OsFifoFeature = _OsFifoFeature()
3002
3003
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
3004
class TestScenarioApplier(object):
3005
    """A tool to apply scenarios to tests."""
3006
3007
    def adapt(self, test):
3008
        """Return a TestSuite containing a copy of test for each scenario."""
3009
        result = unittest.TestSuite()
3010
        for scenario in self.scenarios:
3011
            result.addTest(self.adapt_test_to_scenario(test, scenario))
3012
        return result
3013
3014
    def adapt_test_to_scenario(self, test, scenario):
3015
        """Copy test and apply scenario to it.
3016
3017
        :param test: A test to adapt.
3018
        :param scenario: A tuple describing the scenarion.
3019
            The first element of the tuple is the new test id.
3020
            The second element is a dict containing attributes to set on the
3021
            test.
3022
        :return: The adapted test.
3023
        """
3024
        from copy import deepcopy
3025
        new_test = deepcopy(test)
3026
        for name, value in scenario[1].items():
3027
            setattr(new_test, name, value)
2553.3.1 by Robert Collins
Remove unneeded inner function in adapt_test_to_scenario.
3028
        new_id = "%s(%s)" % (new_test.id(), scenario[0])
3029
        new_test.id = lambda: new_id
2553.2.3 by Robert Collins
Split out the common test scenario support from the repository implementation specific code.
3030
        return new_test
2785.1.5 by Alexander Belchenko
support for non-ascii BZR_HOME in show_version()
3031
3032
3033
def probe_unicode_in_user_encoding():
3034
    """Try to encode several unicode strings to use in unicode-aware tests.
3035
    Return first successfull match.
3036
3037
    :return:  (unicode value, encoded plain string value) or (None, None)
3038
    """
3039
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
3040
    for uni_val in possible_vals:
3041
        try:
3042
            str_val = uni_val.encode(bzrlib.user_encoding)
3043
        except UnicodeEncodeError:
3044
            # Try a different character
3045
            pass
3046
        else:
3047
            return uni_val, str_val
3048
    return None, None
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
3049
3050
2839.6.2 by Alexander Belchenko
changes after Martin's review
3051
def probe_bad_non_ascii(encoding):
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
3052
    """Try to find [bad] character with code [128..255]
2839.6.2 by Alexander Belchenko
changes after Martin's review
3053
    that cannot be decoded to unicode in some encoding.
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
3054
    Return None if all non-ascii characters is valid
2839.6.2 by Alexander Belchenko
changes after Martin's review
3055
    for given encoding.
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
3056
    """
3057
    for i in xrange(128, 256):
3058
        char = chr(i)
3059
        try:
2839.6.2 by Alexander Belchenko
changes after Martin's review
3060
            char.decode(encoding)
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
3061
        except UnicodeDecodeError:
3062
            return char
3063
    return None
2917.3.1 by Vincent Ladeuil
Separate transport from test server.
3064
3065
3066
class _FTPServerFeature(Feature):
3067
    """Some tests want an FTP Server, check if one is available.
3068
3069
    Right now, the only way this is available is if 'medusa' is installed.
3070
    http://www.amk.ca/python/code/medusa.html
3071
    """
3072
3073
    def _probe(self):
3074
        try:
2949.3.3 by Vincent Ladeuil
Fix reference to FTPServer, forgotten in the previous renaming.
3075
            import bzrlib.tests.ftp_server
2917.3.1 by Vincent Ladeuil
Separate transport from test server.
3076
            return True
3077
        except ImportError:
3078
            return False
3079
3080
    def feature_name(self):
3081
        return 'FTPServer'
3082
3083
FTPServerFeature = _FTPServerFeature()
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
3084
3085
3086
class _CaseInsensitiveFilesystemFeature(Feature):
3087
    """Check if underlined filesystem is case-insensitive
3088
    (e.g. on Windows, Cygwin, MacOS)
3089
    """
3090
3091
    def _probe(self):
3092
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
3093
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
3094
            TestCaseWithMemoryTransport.TEST_ROOT = root
3095
        else:
3096
            root = TestCaseWithMemoryTransport.TEST_ROOT
3097
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
3098
            dir=root)
3099
        name_a = osutils.pathjoin(tdir, 'a')
3100
        name_A = osutils.pathjoin(tdir, 'A')
3101
        os.mkdir(name_a)
3102
        result = osutils.isdir(name_A)
3103
        _rmtree_temp_dir(tdir)
3104
        return result
3105
3106
    def feature_name(self):
3107
        return 'case-insensitive filesystem'
3108
3109
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()